Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/MindWork AI Studio/MindWork AI Studio.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
<PackageReference Include="CodeBeam.MudBlazor.Extensions" Version="9.2.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
<PackageReference Include="HtmlAgilityPack" Version="1.12.4" />
<PackageReference Include="MailKit" Version="4.18.2" />
<PackageReference Include="MailKit" Version="5.0.0" />
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />

Expand Down
26 changes: 21 additions & 5 deletions app/MindWork AI Studio/Tools/Mail/ImapMailboxConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -292,10 +308,10 @@ public async Task<IReadOnlyDictionary<long, MailFlags>> FetchFlagsAsync(IReadOnl
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);
Expand Down Expand Up @@ -449,7 +465,7 @@ private async Task<IReadOnlyList<IMessageSummary>> FetchAsync(IReadOnlyCollectio
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
{
Expand Down Expand Up @@ -478,7 +494,7 @@ private async Task SignInAsync(string username, string password, CancellationTok
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.");

//
Expand Down
10 changes: 5 additions & 5 deletions app/MindWork AI Studio/Tools/Mail/MailAttachmentPieces.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
Expand All @@ -52,7 +52,7 @@ public static async Task WriteDecodedAsync(Func<int, CancellationToken, Task<Str
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)
Expand Down Expand Up @@ -80,7 +80,7 @@ private static ContentEncoding GetEncoding(string? transferEncoding)
{
// 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;
Expand Down
54 changes: 45 additions & 9 deletions app/MindWork AI Studio/Tools/Mail/MailEncryptionDetection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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"))
Expand Down
13 changes: 13 additions & 0 deletions app/MindWork AI Studio/Tools/Mail/MailHeaders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ public static IReadOnlyList<MailboxAddress> ReadMailboxes(HeaderList headers, He
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>
Expand Down
19 changes: 16 additions & 3 deletions app/MindWork AI Studio/Tools/Mail/MailSummaryReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static MailIdentity ReadIdentity(IMessageSummary summary)
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);
}
Expand Down Expand Up @@ -83,7 +83,7 @@ public static IReadOnlyList<MailAddressRecord> ReadAddresses(HeaderList headers)
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();
Expand Down Expand Up @@ -135,5 +135,18 @@ public static string ComputeMailHash(IMessageSummary summary)
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.");
}
2 changes: 1 addition & 1 deletion app/MindWork AI Studio/Tools/Mail/MailTextBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ private static string FormatAddresses(HeaderList headers, HeaderId headerId) =>

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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ internal sealed partial class MailboxIndexer
/// </summary>
private async Task SyncNewMailAsync(IndexedRunContext context, DataSourceMailbox mailbox, ImapMailboxConnector connector, string folderPath, IMessageSummary summary, DocumentRunProgress progress, ISet<string> encounteredKeys, CancellationToken token)
{
if (summary.Headers is not { } headers)
if (MailSummaryReader.ReadHeaders(summary) is not { } headers)
{
logger.LogWarning("The server delivered a mail of mailbox '{MailboxId}' without its header block. The mail is skipped.", mailbox.Id);
logger.LogWarning("The server delivered a mail of mailbox '{MailboxId}' without a header block which could be read. The mail is skipped.", mailbox.Id);
return;
}

Expand Down Expand Up @@ -219,7 +219,7 @@ private EmbeddingDocument CreateMailDocument(IndexedRunContext context, DataSour
/// <returns>The mail as the index keeps it.</returns>
internal static MailRecord CreateMailRecord(string mailId, IMessageSummary summary, MailText text, IReadOnlyList<MailAttachmentText> attachments, string mailHash, MailLocationRecord location, DateTimeOffset foundAtUtc)
{
var headers = summary.Headers ?? throw new ArgumentException("The mail was fetched without its header block.", nameof(summary));
var headers = MailSummaryReader.ReadHeaders(summary) ?? throw new ArgumentException("The mail was fetched without a header block which could be read.", nameof(summary));
var (sentAtUtc, receivedAtUtc) = ReadDates(summary, foundAtUtc);

//
Expand Down Expand Up @@ -276,7 +276,7 @@ internal static MailRecord CreateMailRecord(string mailId, IMessageSummary summa
/// </remarks>
private static (DateTimeOffset? SentAtUtc, DateTimeOffset ReceivedAtUtc) ReadDates(IMessageSummary summary, DateTimeOffset foundAtUtc)
{
var sentAtUtc = summary.Headers is { } headers ? MailHeaders.ReadDate(headers)?.ToUniversalTime() : null;
var sentAtUtc = MailSummaryReader.ReadHeaders(summary) is { } headers ? MailHeaders.ReadDate(headers)?.ToUniversalTime() : null;
return (sentAtUtc, summary.InternalDate?.ToUniversalTime() ?? sentAtUtc ?? foundAtUtc);
}

Expand Down
Loading
Loading