aboutsummaryrefslogtreecommitdiff
path: root/deno/mail-relay/dovecot.ts
blob: 6d291ee6a404ed942fdf99bc15765d4ed1c51688 (plain)
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
import { basename } from "@std/path";

import { LogFileProvider } from "@crupest/base/log";

import { Mail, MailDeliverContext, MailDeliverer } from "./mail.ts";

export class DovecotMailDeliverer extends MailDeliverer {
  readonly name = "dovecot";
  readonly #logFileProvider;
  readonly #ldaPath;
  readonly #doveadmPath;

  constructor(
    logFileProvider: LogFileProvider,
    ldaPath: string,
    doveadmPath: string,
  ) {
    super();
    this.#logFileProvider = logFileProvider;
    this.#ldaPath = ldaPath;
    this.#doveadmPath = doveadmPath;
  }

  protected override async doDeliver(
    mail: Mail,
    context: MailDeliverContext,
  ): Promise<void> {
    const ldaPath = this.#ldaPath;
    const ldaBinName = basename(ldaPath);
    const utf8Stream = mail.toUtf8Bytes();

    const recipients = [...context.recipients];

    if (recipients.length === 0) {
      context.result.message =
        "Failed to deliver to dovecot, no recipients are specified.";
      return;
    }

    console.info(`Deliver to dovecot users: ${recipients.join(", ")}.`);

    for (const recipient of recipients) {
      try {
        const commandArgs = ["-d", recipient];
        console.info(`Run ${ldaBinName} ${commandArgs.join(" ")}...`);

        const ldaCommand = new Deno.Command(ldaPath, {
          args: commandArgs,
          stdin: "piped",
          stdout: "piped",
          stderr: "piped",
        });

        const ldaProcess = ldaCommand.spawn();
        using logFiles = await this.#logFileProvider
          .createExternalLogStreamsForProgram(
            ldaBinName,
          );
        ldaProcess.stdout.pipeTo(logFiles.stdout);
        ldaProcess.stderr.pipeTo(logFiles.stderr);

        const stdinWriter = ldaProcess.stdin.getWriter();
        await stdinWriter.write(utf8Stream);
        await stdinWriter.close();

        const status = await ldaProcess.status;

        if (status.success) {
          context.result.recipients.set(recipient, {
            kind: "done",
            message: `${ldaBinName} exited with success.`,
          });
        } else {
          let message = `${ldaBinName} exited with error code ${status.code}`;

          if (status.signal != null) {
            message += ` (signal ${status.signal})`;
          }

          // https://doc.dovecot.org/main/core/man/dovecot-lda.1.html
          switch (status.code) {
            case 67:
              message += ", recipient user not known";
              break;
            case 75:
              message += ", temporary error";
              break;
          }

          message += ".";

          context.result.recipients.set(recipient, { kind: "fail", message });
        }
      } catch (cause) {
        context.result.recipients.set(recipient, {
          kind: "fail",
          message: "An error is thrown when running lda: " + cause,
          cause,
        });
      }
    }

    console.info("Done handling all recipients.");
  }

  async #deleteMail(
    user: string,
    mailbox: string,
    messageId: string,
  ): Promise<void> {
    try {
      const args = [
        "expunge",
        "-u",
        user,
        "mailbox",
        mailbox,
        "header",
        "Message-ID",
        `<${messageId}>`,
      ];
      console.info(
        `Run external command ${this.#doveadmPath} ${args.join(" ")} ...`,
      );
      const command = new Deno.Command(this.#doveadmPath, { args });
      const status = await command.spawn().status;
      if (status.success) {
        console.info("Expunged successfully.");
      } else {
        console.warn("Expunging failed with exit code %d.", status.code);
      }
    } catch (cause) {
      console.warn("Expunging failed with an error thrown: ", cause);
    }
  }

  async #saveMail(user: string, mailbox: string, mail: Uint8Array) {
    try {
      const args = ["save", "-u", user, "-m", mailbox];
      console.info(
        `Run external command ${this.#doveadmPath} ${args.join(" ")} ...`,
      );
      const command = new Deno.Command(this.#doveadmPath, {
        args,
        stdin: "piped",
      });
      const process = command.spawn();
      const stdinWriter = process.stdin.getWriter();
      await stdinWriter.write(mail);
      await stdinWriter.close();
      const status = await process.status;

      if (status.success) {
        console.info("Saved successfully.");
      } else {
        console.warn("Saving failed with exit code %d.", status.code);
      }
    } catch (cause) {
      console.warn("Saving failed with an error thrown: ", cause);
    }
  }

  async saveNewSent(originalMessageId: string, mail: Mail) {
    console.info(
      "Try to save mail with new id and delete mail with old id in Sent box.",
    );
    const from = mail.startSimpleParse().sections().headers()
      .from();
    if (from != null) {
      console.info("Parsed sender (from): ", from);
      await this.#saveMail(from, "Sent", mail.toUtf8Bytes());
      setTimeout(() => {
        console.info(
          "Try to delete mail in Sent box that has old message id.",
        );
        this.#deleteMail(from, "Sent", originalMessageId);
      }, 1000 * 15);
    } else {
      console.warn("Failed to determine from.");
    }
  }
}