1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
|
import { Mail, MailDeliverContext, MailDeliverer } from "./mail.ts";
// https://doc.dovecot.org/main/core/man/dovecot-lda.1.html
const ldaExitCodeMessageMap = new Map<number, string>();
ldaExitCodeMessageMap.set(67, "recipient user not known");
ldaExitCodeMessageMap.set(75, "temporary error");
type CommandResult = {
kind: "exit-success" | "exit-failure";
status: Deno.CommandStatus;
logMessage: string;
} | { kind: "throw"; cause: unknown; logMessage: string };
async function runCommand(
bin: string,
options: {
args: string[];
stdin?: Uint8Array;
suppressResultLog?: boolean;
errorCodeMessageMap?: Map<number, string>;
},
): Promise<CommandResult> {
const { args, stdin, suppressResultLog, errorCodeMessageMap } = options;
console.info(`Run external command ${bin} ${args.join(" ")}`);
try {
// Create and spawn process.
const command = new Deno.Command(bin, {
args,
stdin: stdin == null ? "null" : "piped",
});
const process = command.spawn();
// Write stdin if any.
if (stdin != null) {
const writer = process.stdin.getWriter();
await writer.write(stdin);
writer.close();
}
// Wait for process to exit.
const status = await process.status;
// Build log message string.
let message = `External command exited with code ${status.code}`;
if (status.signal != null) message += ` (signal: ${status.signal})`;
if (errorCodeMessageMap != null && errorCodeMessageMap.has(status.code)) {
message += `, ${errorCodeMessageMap.get(status.code)}`;
}
message += ".";
suppressResultLog || console.log(message);
// Return result.
return {
kind: status.success ? "exit-success" : "exit-failure",
status,
logMessage: message,
};
} catch (cause) {
const message = `A JS error was thrown when invoking external command:`;
suppressResultLog || console.log(message, cause);
return { kind: "throw", cause, logMessage: message + " " + cause };
}
}
export class DovecotMailDeliverer extends MailDeliverer {
readonly name = "dovecot";
readonly #ldaPath;
readonly #doveadmPath;
constructor(
ldaPath: string,
doveadmPath: string,
) {
super();
this.#ldaPath = ldaPath;
this.#doveadmPath = doveadmPath;
}
protected override async doDeliver(
mail: Mail,
context: MailDeliverContext,
): Promise<void> {
const utf8Bytes = mail.toUtf8Bytes();
const recipients = [...context.recipients];
if (recipients.length === 0) {
throw new Error(
"Failed to deliver to dovecot, no recipients are specified.",
);
}
for (const recipient of recipients) {
const result = await runCommand(
this.#ldaPath,
{
args: ["-d", recipient],
stdin: utf8Bytes,
suppressResultLog: true,
errorCodeMessageMap: ldaExitCodeMessageMap,
},
);
if (result.kind === "exit-success") {
context.result.recipients.set(recipient, {
kind: "success",
message: result.logMessage,
});
} else {
context.result.recipients.set(recipient, {
kind: "failure",
message: result.logMessage,
});
}
}
}
#queryArgs(mailbox: string, messageId: string) {
return ["mailbox", mailbox, "header", "Message-ID", `<${messageId}>`];
}
async #deleteMail(
user: string,
mailbox: string,
messageId: string,
): Promise<void> {
await runCommand(this.#doveadmPath, {
args: ["expunge", "-u", user, ...this.#queryArgs(mailbox, messageId)],
});
}
async #saveMail(user: string, mailbox: string, mail: Uint8Array) {
await runCommand(this.#doveadmPath, {
args: ["save", "-u", user, "-m", mailbox],
stdin: mail,
});
}
async #markAsRead(user: string, mailbox: string, messageId: string) {
await runCommand(this.#doveadmPath, {
args: [
"flags",
"add",
"-u",
user,
"\\Seen",
...this.#queryArgs(mailbox, messageId),
],
});
}
async saveNewSent(mail: Mail, messageIdToDelete: string) {
console.info("Save sent mails and delete ones with old message id.");
// Try to get from and recipients from headers.
const { messageId, from, recipients } = mail.parsed;
if (from == null) {
console.warn("Failed to get sender (from) in headers, skip saving.");
return;
}
if (recipients.has(from)) {
// So the mail should lie in the Inbox.
console.info(
"One recipient of the mail is the sender itself, skip saving.",
);
return;
}
await this.#saveMail(from, "Sent", mail.toUtf8Bytes());
if (messageId != null) {
await this.#markAsRead(from, "Sent", messageId);
} else {
console.warn(
"Message id of the mail is not found, skip marking as read.",
);
}
console.info("Schedule deletion of old mails at 15,30,60 seconds later.");
[15, 30, 60].forEach((seconds) =>
setTimeout(() => {
void this.#deleteMail(from, "Sent", messageIdToDelete);
}, 1000 * seconds)
);
}
}
|