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
27 changes: 26 additions & 1 deletion backend/src/connectors/email/smtp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,18 @@ export async function sendSmtp(cfg: SmtpConfig, msg: SmtpMessage): Promise<void>
});
expired.catch(() => {}); // observed through the race below, or not at all
let socket: Awaited<ReturnType<typeof Bun.connect>> | null = null;

// Bun's socket.write hands the kernel only what fits in its send buffer and
// returns that many bytes; it keeps nothing back. The bytes it did not take
// wait here and go out on each `drain`, so a long message reaches the relay
// whole instead of losing its tail and the "." that ends it.
let unsent = new Uint8Array(0);
const flush = (): void => {
if (!socket || unsent.byteLength === 0) return;
const written = socket.write(unsent);
if (written > 0) unsent = unsent.subarray(written);
};

const deadline = cfg.timeoutMs
? setTimeout(() => {
const error = new Error("SMTP timeout");
Expand All @@ -73,6 +85,9 @@ export async function sendSmtp(cfg: SmtpConfig, msg: SmtpMessage): Promise<void>
onData = null;
wake?.();
},
drain() {
flush();
},
error(_s, error) {
fail(error instanceof Error ? error : new Error("SMTP socket error"));
},
Expand Down Expand Up @@ -120,8 +135,18 @@ export async function sendSmtp(cfg: SmtpConfig, msg: SmtpMessage): Promise<void>
}
};

const encoder = new TextEncoder();
const write = (line: string): void => {
live.write(`${line}\r\n`);
const bytes = encoder.encode(`${line}\r\n`);
if (unsent.byteLength === 0) {
unsent = bytes;
} else {
const queued = new Uint8Array(unsent.byteLength + bytes.byteLength);
queued.set(unsent);
queued.set(bytes, unsent.byteLength);
unsent = queued;
}
flush();
};
const expect = async (family: number): Promise<void> => {
const reply = await readReply();
Expand Down
50 changes: 50 additions & 0 deletions backend/test/smtp-message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,54 @@ describe("smtp message form", () => {
expect(wire).toContain('Content-Type: text/plain; charset="utf-8"\r\n\r\nplain\r\n.\r\n');
expect(wire).not.toContain("multipart");
});

test("a message larger than the socket's send buffer reaches the relay whole", async () => {
// Far more than one socket write hands the kernel (Linux's default send
// buffer tops out at 4 MiB), in multibyte text so a partial write can end
// inside a character.
const line = "Grüße, 東京 🙂 the agent's long answer goes on\n";
const text = line.repeat(Math.ceil((16 * 1024 * 1024) / Buffer.byteLength(line)));
const chunks: Uint8Array[] = [];
let inData = false;
let tail = "";
const server = Bun.listen({
hostname: "127.0.0.1",
port: 0,
socket: {
open(s) {
s.write("220 test\r\n");
},
data(s, chunk) {
if (inData) {
chunks.push(new Uint8Array(chunk));
tail = (tail + chunk.toString("latin1")).slice(-5);
if (tail === "\r\n.\r\n") {
inData = false;
s.write("250 queued\r\n");
}
return;
}
const command = chunk.toString();
if (command.startsWith("DATA")) {
inData = true;
s.write("354 go\r\n");
} else if (command.startsWith("QUIT")) s.write("221 bye\r\n");
else if (command.startsWith("EHLO")) s.write("250-test\r\n250 OK\r\n");
else s.write("250 OK\r\n");
},
},
});
try {
await sendSmtp(
{ host: "127.0.0.1", port: server.port, secure: false, timeoutMs: 10_000 },
{ from: "noreply@example.test", to: ["new@example.test"], subject: "hi", text },
);
} finally {
server.stop(true);
}
const wire = Buffer.concat(chunks).toString("utf8");
const body = `${text.replace(/\n/g, "\r\n")}\r\n.\r\n`;
expect(wire.endsWith(body)).toBe(true);
expect(wire.slice(0, -body.length)).toEndWith('Content-Type: text/plain; charset="utf-8"\r\n\r\n');
});
});
Loading