mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-11-25 06:53:49 +00:00
Upgraded MailKit and MimeKit to v5.0 (#1226)
This commit is contained in:
1 parent
d121ec3b47
commit
f6a4348820
15 files changed
+242
-85
No files matched your search
@@ -39,6 +39,13 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
/// </summary>
|
||||
public const long MAX_TEXT_PART_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// The longest single header field which is read, in bytes. MimeKit reads 16 KB by default, and the
|
||||
/// IMAP client hands over a mail with a longer one with an empty header block. A mail to a few
|
||||
/// hundred people has such a To field, and so has a long thread its References field.
|
||||
/// </summary>
|
||||
internal const int MAX_HEADER_FIELD_BYTES = 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// How many UIDs go into one FETCH. A long list of scattered UIDs makes a long command line, and
|
||||
/// some servers refuse lines beyond a few kilobytes.
|
||||
@@ -67,6 +74,15 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
/// </summary>
|
||||
private static readonly TimeSpan DISCONNECT_TIMEOUT = TimeSpan.FromSeconds(5);
|
||||
|
||||
static ImapMailboxConnector()
|
||||
{
|
||||
//
|
||||
// The IMAP client reads every header block with the default options of MimeKit and takes no
|
||||
// options of its own. Raised here, the limit holds before the first mail is fetched:
|
||||
//
|
||||
ParserOptions.Default.MaxHeaderLength = Math.Max(ParserOptions.Default.MaxHeaderLength, MAX_HEADER_FIELD_BYTES);
|
||||
}
|
||||
|
||||
private readonly ImapClient client = new()
|
||||
{
|
||||
Timeout = (int)COMMAND_TIMEOUT.TotalMilliseconds,
|
||||
@@ -88,7 +104,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
/// Whether the server tells which mails changed since a point it handed out before (CONDSTORE).
|
||||
/// Without it, the flags of every mail have to be fetched to find the changed ones.
|
||||
/// </summary>
|
||||
public bool SupportsChangeTracking => this.client.Capabilities.HasFlag(ImapCapabilities.CondStore);
|
||||
public bool SupportsChangeTracking => this.client.Capabilities.Contains(ImapCapability.CondStore);
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the IMAP server of the mailbox and signs in.
|
||||
@@ -292,10 +308,10 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
public async Task<IReadOnlyList<IMessageSummary>> FetchSummariesAsync(IReadOnlyCollection<long> uids, CancellationToken token)
|
||||
{
|
||||
var items = MessageSummaryItems.UniqueId | MessageSummaryItems.Flags | MessageSummaryItems.InternalDate | MessageSummaryItems.Size | MessageSummaryItems.BodyStructure | MessageSummaryItems.Headers;
|
||||
if (this.client.Capabilities.HasFlag(ImapCapabilities.ObjectID))
|
||||
if (this.client.Capabilities.Contains(ImapCapability.ObjectID))
|
||||
items |= MessageSummaryItems.EmailId;
|
||||
|
||||
if (this.client.Capabilities.HasFlag(ImapCapabilities.GMailExt1))
|
||||
if (this.client.Capabilities.Contains(ImapCapability.GMailExt1))
|
||||
items |= MessageSummaryItems.GMailMessageId;
|
||||
|
||||
return await this.FetchAsync(uids, new FetchRequest(items), token);
|
||||
@@ -449,7 +465,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
return summaries;
|
||||
}
|
||||
|
||||
private static async Task<Stream> FetchAttachmentPieceAsync(IMailFolder folder, UniqueId uid, string section, int offset, CancellationToken token)
|
||||
private static async Task<Stream> FetchAttachmentPieceAsync(IMailFolder folder, UniqueId uid, string section, long offset, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -478,7 +494,7 @@ public sealed class ImapMailboxConnector : IAsyncDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.client.Capabilities.HasFlag(ImapCapabilities.LoginDisabled))
|
||||
if (this.client.Capabilities.Contains(ImapCapability.LoginDisabled))
|
||||
throw new MailboxConnectionException(MailboxConnectionFailure.SERVER_ERROR, "The IMAP server offers no way to sign in with a password.");
|
||||
|
||||
//
|
||||
|
||||
@@ -25,8 +25,8 @@ public static class MailAttachmentPieces
|
||||
/// The largest attachment, as it travels, which can be fetched at all.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The IMAP client addresses a piece by an offset of type int. With Base64, this allows for files
|
||||
/// of about 1.5 GB, whereas mail servers rarely accept a mail a tenth as large.
|
||||
/// With Base64, this allows for files of about 1.5 GB, whereas mail servers rarely accept a mail a
|
||||
/// tenth as large. The limit also ends the fetching when a server keeps delivering full pieces.
|
||||
/// </remarks>
|
||||
public const long MAX_OCTETS = int.MaxValue;
|
||||
|
||||
@@ -41,7 +41,7 @@ public static class MailAttachmentPieces
|
||||
/// <param name="pieceBytes">How large a piece is, cf. PIECE_BYTES.</param>
|
||||
/// <param name="token">The cancellation token.</param>
|
||||
/// <exception cref="InvalidDataException">The transfer encoding is unknown, or the server delivered more than it was asked for.</exception>
|
||||
public static async Task WriteDecodedAsync(Func<int, CancellationToken, Task<Stream>> fetchPieceAsync, string? transferEncoding, Stream destination, int pieceBytes, CancellationToken token)
|
||||
public static async Task WriteDecodedAsync(Func<long, CancellationToken, Task<Stream>> fetchPieceAsync, string? transferEncoding, Stream destination, int pieceBytes, CancellationToken token)
|
||||
{
|
||||
var encoding = GetEncoding(transferEncoding);
|
||||
await using var decoded = new FilteredStream(destination);
|
||||
@@ -52,7 +52,7 @@ public static class MailAttachmentPieces
|
||||
for (var offset = 0L; offset <= MAX_OCTETS; offset += pieceBytes)
|
||||
{
|
||||
var pieceLength = 0L;
|
||||
await using (var piece = await fetchPieceAsync((int)offset, token))
|
||||
await using (var piece = await fetchPieceAsync(offset, token))
|
||||
{
|
||||
int read;
|
||||
while ((read = await piece.ReadAsync(buffer, token)) > 0)
|
||||
@@ -80,7 +80,7 @@ public static class MailAttachmentPieces
|
||||
{
|
||||
// Without a transfer encoding, the content travels as it is, cf. RFC 2045, section 6.1:
|
||||
if (string.IsNullOrWhiteSpace(transferEncoding))
|
||||
return ContentEncoding.Default;
|
||||
return ContentEncoding.Unspecified;
|
||||
|
||||
if (MimeUtils.TryParse(transferEncoding, out ContentEncoding encoding))
|
||||
return encoding;
|
||||
|
||||
@@ -36,17 +36,49 @@ public static class MailEncryptionDetection
|
||||
/// <summary>
|
||||
/// Reads the encryption from the structure the server describes.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The structure is walked with a stack of its own rather than by recursion: the IMAP client reads
|
||||
/// a structure of any depth, and a mail nested deeply enough on purpose would otherwise end AI
|
||||
/// Studio with a stack overflow, which no catch block stops. The parts are visited in their order,
|
||||
/// so the first encrypted part decides, as for a parsed mail.
|
||||
/// </remarks>
|
||||
/// <param name="bodyStructure">The BODYSTRUCTURE of the mail, or null when the server sent none.</param>
|
||||
/// <returns>How the content is encrypted, NONE when it is readable as far as the structure tells.</returns>
|
||||
public static MailEncryptionKind Detect(BodyPart? bodyStructure) => bodyStructure switch
|
||||
public static MailEncryptionKind Detect(BodyPart? bodyStructure)
|
||||
{
|
||||
// An attached mail keeps its protection to itself:
|
||||
BodyPartMessage => MailEncryptionKind.NONE,
|
||||
var pending = new Stack<BodyPart>();
|
||||
if (bodyStructure is not null)
|
||||
pending.Push(bodyStructure);
|
||||
|
||||
BodyPartMultipart multipart => DetectMultipart(multipart.ContentType, multipart.BodyParts.Select(Detect)),
|
||||
BodyPartBasic part => DetectPart(part.ContentType, part.FileName),
|
||||
_ => MailEncryptionKind.NONE,
|
||||
};
|
||||
while (pending.TryPop(out var current))
|
||||
{
|
||||
switch (current)
|
||||
{
|
||||
// An attached mail keeps its protection to itself:
|
||||
case BodyPartMessage:
|
||||
continue;
|
||||
|
||||
case BodyPartMultipart multipart when IsPgpMime(multipart.ContentType):
|
||||
return MailEncryptionKind.PGP_MIME;
|
||||
|
||||
case BodyPartMultipart multipart:
|
||||
// Pushed in reverse, so that the first part comes off the stack first:
|
||||
for (var index = multipart.BodyParts.Count - 1; index >= 0; index--)
|
||||
pending.Push(multipart.BodyParts[index]);
|
||||
|
||||
continue;
|
||||
|
||||
case BodyPartBasic part:
|
||||
var kind = DetectPart(part.ContentType, part.FileName);
|
||||
if (kind is not MailEncryptionKind.NONE)
|
||||
return kind;
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return MailEncryptionKind.NONE;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the encryption from the MIME tree of a parsed mail.
|
||||
@@ -73,13 +105,17 @@ public static class MailEncryptionDetection
|
||||
|
||||
private static MailEncryptionKind DetectMultipart(ContentType contentType, IEnumerable<MailEncryptionKind> partKinds)
|
||||
{
|
||||
// RFC 1847 knows no other use of multipart/encrypted than PGP/MIME in practice:
|
||||
if (contentType.IsMimeType("multipart", "encrypted"))
|
||||
if (IsPgpMime(contentType))
|
||||
return MailEncryptionKind.PGP_MIME;
|
||||
|
||||
return partKinds.FirstOrDefault(kind => kind is not MailEncryptionKind.NONE);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a multipart is encrypted. RFC 1847 knows no other use of multipart/encrypted than PGP/MIME in practice.
|
||||
/// </summary>
|
||||
private static bool IsPgpMime(ContentType contentType) => contentType.IsMimeType("multipart", "encrypted");
|
||||
|
||||
private static MailEncryptionKind DetectPart(ContentType contentType, string? fileName)
|
||||
{
|
||||
if (contentType.IsMimeType("application", "pkcs7-mime") || contentType.IsMimeType("application", "x-pkcs7-mime"))
|
||||
|
||||
@@ -35,6 +35,19 @@ public static class MailHeaders
|
||||
return mailboxes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the address of a mailbox, with an internationalized domain in Unicode, e.g. "müller.example"
|
||||
/// rather than "xn--mller-kva.example".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// MimeKit decoded such a domain by itself up to version 4, and the index keeps every address in
|
||||
/// this form. The key of a mail depends on it, too, see MailContentKey: in another form, every mail
|
||||
/// from such a domain would be embedded anew.
|
||||
/// </remarks>
|
||||
/// <param name="mailbox">The mailbox, as parsed from a header.</param>
|
||||
/// <returns>The address.</returns>
|
||||
public static string ReadAddress(MailboxAddress mailbox) => mailbox.GetAddress(idnEncode: false);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the Message-IDs of a header, without their angle brackets.
|
||||
/// </summary>
|
||||
|
||||
@@ -33,7 +33,7 @@ public static class MailSummaryReader
|
||||
summary.GMailMessageId,
|
||||
headers[HeaderId.MessageId],
|
||||
MailHeaders.ReadDate(headers),
|
||||
MailHeaders.ReadMailboxes(headers, HeaderId.From).Select(mailbox => mailbox.Address).ToList(),
|
||||
MailHeaders.ReadMailboxes(headers, HeaderId.From).Select(MailHeaders.ReadAddress).ToList(),
|
||||
headers[HeaderId.Subject],
|
||||
summary.Size ?? 0);
|
||||
}
|
||||
@@ -83,7 +83,7 @@ public static class MailSummaryReader
|
||||
return roles
|
||||
.SelectMany(role => MailHeaders.ReadMailboxes(headers, role.HeaderId).Select(mailbox => new MailAddressRecord(
|
||||
role.Role,
|
||||
MailTextNormalization.NormalizeHeaderValue(mailbox.Address),
|
||||
MailTextNormalization.NormalizeHeaderValue(MailHeaders.ReadAddress(mailbox)),
|
||||
MailTextNormalization.NormalizeHeaderValue(mailbox.Name))))
|
||||
.Where(address => address.Address.Length > 0)
|
||||
.ToList();
|
||||
@@ -135,5 +135,18 @@ public static class MailSummaryReader
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(source)));
|
||||
}
|
||||
|
||||
private static HeaderList GetHeaders(IMessageSummary summary) => summary.Headers ?? throw new InvalidOperationException("The mail was fetched without its header block.");
|
||||
/// <summary>
|
||||
/// Reads the header block the server delivered with a mail.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The IMAP client hands over an empty header block when it cannot parse the one the server sent,
|
||||
/// e.g. because a field is longer than ImapMailboxConnector.MAX_HEADER_FIELD_BYTES. Every mail has a
|
||||
/// header, so an empty one counts as missing: a mail read from it would have neither sender, nor
|
||||
/// subject, nor date, and its key would rest on its size alone.
|
||||
/// </remarks>
|
||||
/// <param name="summary">The summary of the mail.</param>
|
||||
/// <returns>The header block, or null when the mail was fetched without one, or with one which could not be read.</returns>
|
||||
public static HeaderList? ReadHeaders(IMessageSummary summary) => summary.Headers is { Count: > 0 } headers ? headers : null;
|
||||
|
||||
private static HeaderList GetHeaders(IMessageSummary summary) => ReadHeaders(summary) ?? throw new InvalidOperationException("The mail was fetched without a header block which could be read.");
|
||||
}
|
||||
@@ -111,7 +111,7 @@ public static class MailTextBuilder
|
||||
|
||||
private static string FormatAddress(MailboxAddress mailbox)
|
||||
{
|
||||
var address = MailTextNormalization.NormalizeHeaderValue(mailbox.Address);
|
||||
var address = MailTextNormalization.NormalizeHeaderValue(MailHeaders.ReadAddress(mailbox));
|
||||
var name = MailTextNormalization.NormalizeHeaderValue(mailbox.Name);
|
||||
if (name.Length is 0 || name.Equals(address, StringComparison.OrdinalIgnoreCase))
|
||||
return address;
|
||||
|
||||
Reference in new issue
Block a user