2026-02-06 01:18:12 +01:00
|
|
|
using System;
|
2024-04-18 01:44:37 +02:00
|
|
|
using System.Collections.Concurrent;
|
2024-06-17 02:16:06 +02:00
|
|
|
using System.IO;
|
2024-06-21 01:13:25 +02:00
|
|
|
using System.Net;
|
2024-09-14 21:51:43 +02:00
|
|
|
using System.Net.Security;
|
|
|
|
|
using System.Security.Cryptography.X509Certificates;
|
2024-06-17 02:16:06 +02:00
|
|
|
using System.Text;
|
2024-04-18 01:44:37 +02:00
|
|
|
using System.Threading;
|
2026-02-06 01:18:12 +01:00
|
|
|
using System.Threading.Channels;
|
2024-04-18 01:44:37 +02:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using MailKit.Net.Imap;
|
|
|
|
|
using MailKit.Net.Proxy;
|
|
|
|
|
using MailKit.Security;
|
2024-09-14 21:51:43 +02:00
|
|
|
using MimeKit.Cryptography;
|
2024-04-18 01:44:37 +02:00
|
|
|
using Serilog;
|
2024-11-10 23:28:25 +01:00
|
|
|
using Wino.Core.Domain.Entities.Shared;
|
2024-04-18 01:44:37 +02:00
|
|
|
using Wino.Core.Domain.Enums;
|
|
|
|
|
using Wino.Core.Domain.Exceptions;
|
2024-09-29 21:21:51 +02:00
|
|
|
using Wino.Core.Domain.Models.Connectivity;
|
2024-04-18 01:44:37 +02:00
|
|
|
|
2025-02-16 11:54:23 +01:00
|
|
|
namespace Wino.Core.Integration;
|
2026-02-06 01:18:12 +01:00
|
|
|
|
2025-02-16 11:54:23 +01:00
|
|
|
/// <summary>
|
2026-02-06 01:18:12 +01:00
|
|
|
/// Connection state for tracking individual client health.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public enum ImapClientState
|
|
|
|
|
{
|
|
|
|
|
Available,
|
|
|
|
|
InUse,
|
|
|
|
|
Idle,
|
|
|
|
|
Reconnecting,
|
|
|
|
|
Failed,
|
|
|
|
|
Disposed
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Provides an enhanced pooling mechanism for ImapClient with Channel-based async rental.
|
|
|
|
|
/// Maintains minimum active connections and a dedicated IDLE client.
|
2025-02-16 11:54:23 +01:00
|
|
|
/// </summary>
|
|
|
|
|
public class ImapClientPool : IDisposable
|
2024-04-18 01:44:37 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
private const int MinActiveConnections = 3;
|
|
|
|
|
private const int IdleConnectionReserved = 1;
|
|
|
|
|
private const int KeepAliveIntervalMs = 4 * 60 * 1000; // 4 minutes
|
|
|
|
|
private const int ConnectionMonitorIntervalMs = 30 * 1000; // 30 seconds
|
|
|
|
|
private const int MaintenanceIntervalMs = 60 * 1000; // 1 minute
|
|
|
|
|
|
2025-02-16 11:54:23 +01:00
|
|
|
private readonly ImapImplementation _implementation = new()
|
|
|
|
|
{
|
|
|
|
|
Version = "1.8.0",
|
|
|
|
|
OS = "Windows",
|
|
|
|
|
Vendor = "Wino",
|
|
|
|
|
SupportUrl = "https://www.winomail.app",
|
|
|
|
|
Name = "Wino Mail User",
|
|
|
|
|
};
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private readonly ILogger _logger = Log.ForContext<ImapClientPool>();
|
2025-02-16 11:54:23 +01:00
|
|
|
private readonly CustomServerInformation _customServerInformation;
|
|
|
|
|
private readonly Stream _protocolLogStream;
|
2026-02-06 01:18:12 +01:00
|
|
|
private readonly ConcurrentDictionary<WinoImapClient, ImapClientState> _clientStates = new();
|
|
|
|
|
private readonly Channel<WinoImapClient> _availableClients;
|
|
|
|
|
private readonly CancellationTokenSource _maintenanceCts = new();
|
|
|
|
|
private readonly object _idleClientLock = new();
|
|
|
|
|
|
|
|
|
|
private WinoImapClient _dedicatedIdleClient;
|
|
|
|
|
private bool _disposedValue;
|
|
|
|
|
private bool _initialized;
|
|
|
|
|
private Task _maintenanceTask;
|
2025-02-26 23:11:16 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
public bool ThrowOnSSLHandshakeCallback { get; set; }
|
|
|
|
|
public ImapClientPoolOptions ImapClientPoolOptions { get; }
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Gets the current health status of the connection pool.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public ConnectionPoolHealth Health => GetHealthInternal();
|
2025-02-16 11:54:23 +01:00
|
|
|
|
|
|
|
|
public ImapClientPool(ImapClientPoolOptions imapClientPoolOptions)
|
|
|
|
|
{
|
|
|
|
|
_customServerInformation = imapClientPoolOptions.ServerInformation;
|
|
|
|
|
_protocolLogStream = imapClientPoolOptions.ProtocolLog;
|
|
|
|
|
ImapClientPoolOptions = imapClientPoolOptions;
|
2025-02-26 23:11:16 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
CryptographyContext.Register(typeof(WindowsSecureMimeContext));
|
2025-02-26 23:11:16 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Create unbounded channel for available clients
|
|
|
|
|
_availableClients = Channel.CreateUnbounded<WinoImapClient>(new UnboundedChannelOptions
|
|
|
|
|
{
|
|
|
|
|
SingleReader = false,
|
|
|
|
|
SingleWriter = false,
|
|
|
|
|
AllowSynchronousContinuations = false
|
|
|
|
|
});
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// Initializes the pool by creating minimum connections and starting maintenance.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public async Task InitializeAsync(CancellationToken cancellationToken = default)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (_initialized) return;
|
|
|
|
|
|
|
|
|
|
_logger.Information("Initializing IMAP client pool with {MinConnections} connections", MinActiveConnections);
|
|
|
|
|
|
2025-02-26 23:11:16 +01:00
|
|
|
try
|
|
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
// Create initial connections
|
|
|
|
|
for (int i = 0; i < MinActiveConnections; i++)
|
|
|
|
|
{
|
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
|
|
|
|
|
|
var client = await CreateAndConnectClientAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
if (client != null)
|
|
|
|
|
{
|
|
|
|
|
_clientStates[client] = ImapClientState.Available;
|
|
|
|
|
await _availableClients.Writer.WriteAsync(client, cancellationToken).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create dedicated IDLE client
|
|
|
|
|
_dedicatedIdleClient = await CreateAndConnectClientAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
if (_dedicatedIdleClient != null)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_clientStates[_dedicatedIdleClient] = ImapClientState.Idle;
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Start maintenance task
|
|
|
|
|
_maintenanceTask = Task.Run(() => MaintenanceLoopAsync(_maintenanceCts.Token), _maintenanceCts.Token);
|
|
|
|
|
|
|
|
|
|
_initialized = true;
|
|
|
|
|
_logger.Information("IMAP client pool initialized. Health: {Health}", Health.Summary);
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_logger.Error(ex, "Failed to initialize IMAP client pool");
|
|
|
|
|
throw;
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// Pre-warms the pool (legacy compatibility method).
|
|
|
|
|
/// </summary>
|
|
|
|
|
public Task PreWarmPoolAsync() => InitializeAsync(CancellationToken.None);
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Rents a client from the pool. Blocks until a client is available.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public async Task<WinoImapClient> RentAsync(CancellationToken cancellationToken = default)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (!_initialized)
|
|
|
|
|
await InitializeAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
while (!cancellationToken.IsCancellationRequested)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
// Try to get an available client from the channel
|
|
|
|
|
if (_availableClients.Reader.TryRead(out var client))
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (client != null && _clientStates.TryGetValue(client, out var state) && state == ImapClientState.Available)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
// Ensure client is still connected
|
|
|
|
|
await EnsureClientReadyAsync(client, cancellationToken).ConfigureAwait(false);
|
|
|
|
|
_clientStates[client] = ImapClientState.InUse;
|
|
|
|
|
return client;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.Warning(ex, "Client from pool was not ready, marking as failed");
|
|
|
|
|
_clientStates[client] = ImapClientState.Failed;
|
|
|
|
|
// Continue to try next client or create new one
|
|
|
|
|
}
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
|
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
|
|
|
|
|
// No available client, try to create a new one
|
|
|
|
|
var newClient = await CreateAndConnectClientAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
if (newClient != null)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_clientStates[newClient] = ImapClientState.InUse;
|
|
|
|
|
return newClient;
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
|
|
|
|
|
// Wait a bit before retrying
|
|
|
|
|
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
|
|
|
|
|
throw new OperationCanceledException(cancellationToken);
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// Gets a client from the pool (legacy compatibility method).
|
|
|
|
|
/// </summary>
|
|
|
|
|
public async Task<IImapClient> GetClientAsync() => await RentAsync(CancellationToken.None).ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Returns a client to the pool.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public void Return(WinoImapClient client, bool isFaulted = false)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (client == null) return;
|
|
|
|
|
|
|
|
|
|
if (isFaulted || !client.IsConnected)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_clientStates[client] = ImapClientState.Failed;
|
|
|
|
|
DisposeClient(client);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!_disposedValue)
|
|
|
|
|
{
|
|
|
|
|
_clientStates[client] = ImapClientState.Available;
|
|
|
|
|
_availableClients.Writer.TryWrite(client);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
DisposeClient(client);
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// Releases a client (legacy compatibility method).
|
|
|
|
|
/// </summary>
|
|
|
|
|
public void Release(IImapClient item, bool destroyClient = false)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (item is WinoImapClient winoClient)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
Return(winoClient, destroyClient);
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
else if (item != null)
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
DisposeClient(item);
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2025-02-16 11:43:30 +01:00
|
|
|
|
2025-02-16 11:54:23 +01:00
|
|
|
/// <summary>
|
2026-02-06 01:18:12 +01:00
|
|
|
/// Gets the dedicated IDLE client. Creates one if not available.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public async Task<WinoImapClient> GetIdleClientAsync(CancellationToken cancellationToken = default)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
lock (_idleClientLock)
|
2024-04-18 01:44:37 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (_dedicatedIdleClient != null && _dedicatedIdleClient.IsConnected)
|
2024-04-18 01:44:37 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
return _dedicatedIdleClient;
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-11-30 11:48:05 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Need to create or reconnect IDLE client
|
|
|
|
|
var idleClient = await CreateAndConnectClientAsync(cancellationToken).ConfigureAwait(false);
|
2024-06-18 02:22:55 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
lock (_idleClientLock)
|
|
|
|
|
{
|
|
|
|
|
if (_dedicatedIdleClient != null)
|
|
|
|
|
{
|
|
|
|
|
DisposeClient(_dedicatedIdleClient);
|
2024-04-18 01:44:37 +02:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
_dedicatedIdleClient = idleClient;
|
|
|
|
|
if (idleClient != null)
|
|
|
|
|
{
|
|
|
|
|
_clientStates[idleClient] = ImapClientState.Idle;
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-06-17 02:16:06 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
return idleClient;
|
|
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// Releases the IDLE client for reconnection.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public void ReleaseIdleClient(bool isFaulted = false)
|
|
|
|
|
{
|
|
|
|
|
lock (_idleClientLock)
|
|
|
|
|
{
|
|
|
|
|
if (_dedicatedIdleClient != null)
|
2025-02-16 11:43:30 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (isFaulted)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_clientStates[_dedicatedIdleClient] = ImapClientState.Failed;
|
|
|
|
|
DisposeClient(_dedicatedIdleClient);
|
|
|
|
|
_dedicatedIdleClient = null;
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
_clientStates[_dedicatedIdleClient] = ImapClientState.Idle;
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2025-02-16 11:43:30 +01:00
|
|
|
}
|
2025-02-16 11:35:43 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private ConnectionPoolHealth GetHealthInternal()
|
|
|
|
|
{
|
|
|
|
|
var health = new ConnectionPoolHealth
|
2025-02-16 11:43:30 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
LastHealthCheck = DateTime.UtcNow,
|
|
|
|
|
IdleConnectionActive = _dedicatedIdleClient?.IsConnected ?? false
|
|
|
|
|
};
|
2025-02-16 11:35:43 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
foreach (var kvp in _clientStates)
|
2025-02-16 11:35:43 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
health.TotalConnections++;
|
|
|
|
|
switch (kvp.Value)
|
|
|
|
|
{
|
|
|
|
|
case ImapClientState.Available:
|
|
|
|
|
health.AvailableConnections++;
|
|
|
|
|
break;
|
|
|
|
|
case ImapClientState.InUse:
|
|
|
|
|
health.InUseConnections++;
|
|
|
|
|
break;
|
|
|
|
|
case ImapClientState.Failed:
|
|
|
|
|
health.FailedConnections++;
|
|
|
|
|
break;
|
|
|
|
|
case ImapClientState.Reconnecting:
|
|
|
|
|
health.ReconnectingConnections++;
|
|
|
|
|
break;
|
|
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
|
|
|
|
|
return health;
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2024-04-18 01:44:37 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private async Task MaintenanceLoopAsync(CancellationToken cancellationToken)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
while (!cancellationToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await Task.Delay(MaintenanceIntervalMs, cancellationToken).ConfigureAwait(false);
|
2024-04-18 01:44:37 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Send NOOP to keep connections alive
|
|
|
|
|
await SendNoOpToAvailableClientsAsync(cancellationToken).ConfigureAwait(false);
|
2025-02-16 11:35:43 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Ensure minimum connections
|
|
|
|
|
await EnsureMinimumConnectionsAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
// Clean up failed connections
|
|
|
|
|
await CleanupFailedConnectionsAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.Warning(ex, "Error in pool maintenance loop");
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private async Task SendNoOpToAvailableClientsAsync(CancellationToken cancellationToken)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
foreach (var kvp in _clientStates)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (kvp.Value == ImapClientState.Available && kvp.Key.IsConnected && !kvp.Key.IsBusy())
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await kvp.Key.NoOpAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.Debug(ex, "NOOP failed for client, marking as failed");
|
|
|
|
|
_clientStates[kvp.Key] = ImapClientState.Failed;
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-02-16 11:43:30 +01:00
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private async Task EnsureMinimumConnectionsAsync(CancellationToken cancellationToken)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
var health = Health;
|
|
|
|
|
var neededConnections = MinActiveConnections - health.AvailableConnections;
|
|
|
|
|
|
|
|
|
|
if (neededConnections > 0)
|
2024-04-18 01:44:37 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_logger.Debug("Creating {Count} connections to maintain minimum pool size", neededConnections);
|
|
|
|
|
|
|
|
|
|
for (int i = 0; i < neededConnections; i++)
|
2024-04-18 01:44:37 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
try
|
2024-06-21 04:27:44 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
var client = await CreateAndConnectClientAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
if (client != null)
|
2024-06-21 04:27:44 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_clientStates[client] = ImapClientState.Available;
|
|
|
|
|
await _availableClients.Writer.WriteAsync(client, cancellationToken).ConfigureAwait(false);
|
2024-06-21 04:27:44 +02:00
|
|
|
}
|
|
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.Warning(ex, "Failed to create new connection during maintenance");
|
|
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private Task CleanupFailedConnectionsAsync(CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
foreach (var kvp in _clientStates)
|
|
|
|
|
{
|
|
|
|
|
if (kvp.Value == ImapClientState.Failed)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
DisposeClient(kvp.Key);
|
|
|
|
|
_clientStates.TryRemove(kvp.Key, out _);
|
2025-02-16 11:35:43 +01:00
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
return Task.CompletedTask;
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2024-04-18 01:44:37 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private async Task<WinoImapClient> CreateAndConnectClientAsync(CancellationToken cancellationToken)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
var client = CreateNewClient();
|
2024-09-14 21:51:43 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
try
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
await EnsureClientReadyAsync(client, cancellationToken).ConfigureAwait(false);
|
|
|
|
|
return client;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.Warning(ex, "Failed to create and connect new client");
|
|
|
|
|
DisposeClient(client);
|
|
|
|
|
return null;
|
2025-02-16 11:43:30 +01:00
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2025-02-16 11:43:30 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private async Task EnsureClientReadyAsync(WinoImapClient client, CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
// Connect if needed
|
|
|
|
|
if (!client.IsConnected)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
client.ServerCertificateValidationCallback = MyServerCertificateValidationCallback;
|
2025-02-16 11:43:30 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
await client.ConnectAsync(
|
|
|
|
|
_customServerInformation.IncomingServer,
|
|
|
|
|
int.Parse(_customServerInformation.IncomingServerPort),
|
|
|
|
|
GetSocketOptions(_customServerInformation.IncomingServerSocketOption),
|
|
|
|
|
cancellationToken).ConfigureAwait(false);
|
2024-11-03 16:47:33 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Enable compression if supported
|
|
|
|
|
if (client.Capabilities.HasFlag(ImapCapabilities.Compress))
|
|
|
|
|
{
|
|
|
|
|
await client.CompressAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
}
|
2024-11-03 16:47:33 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Handle ID extension
|
|
|
|
|
if (client.Capabilities.HasFlag(ImapCapabilities.Id))
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await client.IdentifyAsync(_implementation, cancellationToken).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
catch (ImapCommandException)
|
|
|
|
|
{
|
|
|
|
|
// Some servers require post-auth identification
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-09-29 21:21:51 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Authenticate if needed
|
|
|
|
|
if (!client.IsAuthenticated)
|
2024-09-29 21:21:51 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
var cred = new NetworkCredential(
|
|
|
|
|
_customServerInformation.IncomingServerUsername,
|
|
|
|
|
_customServerInformation.IncomingServerPassword);
|
2024-09-29 21:21:51 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
var authMethod = _customServerInformation.IncomingAuthenticationMethod;
|
|
|
|
|
|
|
|
|
|
if (authMethod != ImapAuthenticationMethod.Auto)
|
2025-02-15 12:53:32 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
client.AuthenticationMechanisms.Clear();
|
|
|
|
|
var saslMechanism = GetSASLAuthenticationMethodName(authMethod);
|
|
|
|
|
client.AuthenticationMechanisms.Add(saslMechanism);
|
|
|
|
|
await client.AuthenticateAsync(SaslMechanism.Create(saslMechanism, cred), cancellationToken).ConfigureAwait(false);
|
2025-02-15 12:53:32 +01:00
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
else
|
2025-02-16 11:43:30 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
await client.AuthenticateAsync(cred, cancellationToken).ConfigureAwait(false);
|
2025-02-16 11:43:30 +01:00
|
|
|
}
|
2025-02-16 11:35:43 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
// Try post-auth ID if needed
|
|
|
|
|
if (client.Capabilities.HasFlag(ImapCapabilities.Id))
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await client.IdentifyAsync(_implementation, cancellationToken).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
catch { /* Ignore */ }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Enable QRESYNC if supported
|
|
|
|
|
if (client.Capabilities.HasFlag(ImapCapabilities.QuickResync))
|
|
|
|
|
{
|
|
|
|
|
await client.EnableQuickResyncAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
client.IsQResyncEnabled = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private WinoImapClient CreateNewClient()
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
var client = new WinoImapClient();
|
2024-09-14 21:51:43 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
if (!string.IsNullOrEmpty(_customServerInformation.ProxyServer))
|
2025-02-26 23:11:16 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
client.ProxyClient = new HttpProxyClient(
|
|
|
|
|
_customServerInformation.ProxyServer,
|
|
|
|
|
int.Parse(_customServerInformation.ProxyServerPort));
|
2025-02-26 23:11:16 +01:00
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
_logger.Debug("Created new ImapClient. Current pool size: {Count}", _clientStates.Count);
|
|
|
|
|
return client;
|
|
|
|
|
}
|
2025-02-26 23:11:16 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private void DisposeClient(IImapClient client)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (client.IsConnected)
|
|
|
|
|
{
|
|
|
|
|
lock (client.SyncRoot)
|
|
|
|
|
{
|
|
|
|
|
client.Disconnect(quit: true);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
client.Dispose();
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
catch (Exception ex)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_logger.Debug(ex, "Error disposing client");
|
2025-02-16 11:35:43 +01:00
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2024-04-18 01:44:37 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
private SecureSocketOptions GetSocketOptions(ImapConnectionSecurity connectionSecurity) => connectionSecurity switch
|
|
|
|
|
{
|
|
|
|
|
ImapConnectionSecurity.Auto => SecureSocketOptions.Auto,
|
|
|
|
|
ImapConnectionSecurity.None => SecureSocketOptions.None,
|
|
|
|
|
ImapConnectionSecurity.StartTls => SecureSocketOptions.StartTlsWhenAvailable,
|
|
|
|
|
ImapConnectionSecurity.SslTls => SecureSocketOptions.SslOnConnect,
|
|
|
|
|
_ => SecureSocketOptions.None
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
private string GetSASLAuthenticationMethodName(ImapAuthenticationMethod method) => method switch
|
|
|
|
|
{
|
|
|
|
|
ImapAuthenticationMethod.NormalPassword => "PLAIN",
|
|
|
|
|
ImapAuthenticationMethod.EncryptedPassword => "LOGIN",
|
|
|
|
|
ImapAuthenticationMethod.Ntlm => "NTLM",
|
|
|
|
|
ImapAuthenticationMethod.CramMd5 => "CRAM-MD5",
|
|
|
|
|
ImapAuthenticationMethod.DigestMd5 => "DIGEST-MD5",
|
|
|
|
|
_ => "PLAIN"
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
private bool MyServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
|
2025-02-16 11:54:23 +01:00
|
|
|
{
|
|
|
|
|
if (sslPolicyErrors == SslPolicyErrors.None) return true;
|
|
|
|
|
|
|
|
|
|
if (ThrowOnSSLHandshakeCallback)
|
2025-02-16 11:43:30 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
throw new ImapTestSSLCertificateException(
|
|
|
|
|
certificate.Issuer,
|
|
|
|
|
certificate.GetExpirationDateString(),
|
|
|
|
|
certificate.GetEffectiveDateString());
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2024-06-21 01:13:25 +02:00
|
|
|
|
2025-02-16 11:54:23 +01:00
|
|
|
return true;
|
|
|
|
|
}
|
2024-06-21 01:13:25 +02:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
public string GetProtocolLogContent()
|
|
|
|
|
{
|
|
|
|
|
if (_protocolLogStream == null) return default;
|
|
|
|
|
|
|
|
|
|
if (_protocolLogStream.CanSeek)
|
|
|
|
|
_protocolLogStream.Seek(0, SeekOrigin.Begin);
|
|
|
|
|
|
|
|
|
|
using var reader = new StreamReader(_protocolLogStream, Encoding.UTF8, true, 1024, leaveOpen: true);
|
|
|
|
|
return reader.ReadToEnd();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Legacy compatibility methods
|
|
|
|
|
public Task<bool> EnsureConnectedAsync(IImapClient client) =>
|
|
|
|
|
Task.FromResult(client.IsConnected);
|
|
|
|
|
|
|
|
|
|
public Task EnsureAuthenticatedAsync(IImapClient client) =>
|
|
|
|
|
Task.CompletedTask;
|
|
|
|
|
|
2025-02-16 11:54:23 +01:00
|
|
|
protected virtual void Dispose(bool disposing)
|
|
|
|
|
{
|
|
|
|
|
if (!_disposedValue)
|
|
|
|
|
{
|
|
|
|
|
if (disposing)
|
2024-06-21 04:27:44 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
_maintenanceCts.Cancel();
|
|
|
|
|
_maintenanceTask?.Wait(TimeSpan.FromSeconds(5));
|
|
|
|
|
_maintenanceCts.Dispose();
|
|
|
|
|
|
|
|
|
|
_availableClients.Writer.Complete();
|
2025-02-26 23:11:16 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
foreach (var kvp in _clientStates)
|
|
|
|
|
{
|
|
|
|
|
DisposeClient(kvp.Key);
|
|
|
|
|
}
|
|
|
|
|
_clientStates.Clear();
|
2025-02-26 23:11:16 +01:00
|
|
|
|
2026-02-06 01:18:12 +01:00
|
|
|
lock (_idleClientLock)
|
2024-06-21 04:27:44 +02:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
if (_dedicatedIdleClient != null)
|
2025-02-16 11:43:30 +01:00
|
|
|
{
|
2026-02-06 01:18:12 +01:00
|
|
|
DisposeClient(_dedicatedIdleClient);
|
|
|
|
|
_dedicatedIdleClient = null;
|
2025-02-16 11:54:23 +01:00
|
|
|
}
|
2026-02-06 01:18:12 +01:00
|
|
|
}
|
2025-02-16 11:43:30 +01:00
|
|
|
}
|
2025-02-16 11:35:43 +01:00
|
|
|
|
2025-02-16 11:54:23 +01:00
|
|
|
_disposedValue = true;
|
2025-02-16 11:43:30 +01:00
|
|
|
}
|
2025-02-16 11:35:43 +01:00
|
|
|
}
|
2025-02-16 11:54:23 +01:00
|
|
|
|
|
|
|
|
public void Dispose()
|
|
|
|
|
{
|
|
|
|
|
Dispose(disposing: true);
|
|
|
|
|
GC.SuppressFinalize(this);
|
|
|
|
|
}
|
2024-04-18 01:44:37 +02:00
|
|
|
}
|