gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb3d8a80bb3d8a80bDP69 brief, RV48 mergedmreb3d8a80b/plugins/smtp/smtp.zig

52.7 KB

  1. // hl:smtp plugin — an SMTP submission client (libsmtp.so, dlopen'd by the runtime)
  2. //
  3. // Mission 137. Sending mail, and nothing else: there is no receiving (IMAP/POP),
  4. // no DKIM signing and no queue-with-retry here — see plugins/smtp/README.md for
  5. // why each of those is somewhere else's job.
  6. //
  7. // SHAPE
  8. // hl_smtp_open(host, port, options) → Number mailer id
  9. // hl_smtp_send(id, message) → Number job id, or an hl_error REFUSAL
  10. // hl_smtp_results(id) → the result source (iterator + wake fd)
  11. // hl_smtp_close(id) → null
  12. //
  13. // THE SPLIT BETWEEN THE THREADS is the whole design:
  14. //
  15. // • `send()` runs on the Hybriel thread and does everything that can FAIL
  16. // LOCALLY — validating the addresses, refusing a header injection, rendering
  17. // the RFC 5322 message. Those are located errors at the caller's own line,
  18. // which they can only be if they happen before the job leaves.
  19. // • the WORKER thread does the conversation (connect, EHLO, STARTTLS, AUTH,
  20. // MAIL/RCPT/DATA, QUIT). Nothing on the Hybriel thread waits for it: the
  21. // result goes onto a queue and the queue's eventfd is rung, which is mission
  22. // 125's bell — the event loop is parked in one `epoll_wait` over every
  23. // source's fd and comes back with the answer.
  24. //
  25. // So a server that sends a mail keeps serving while the mail is in flight, and a
  26. // script that only sends mail drains the same source with `for (r of m.results())`.
  27. // One source, the two consumptions the runtime already gives every plugin source
  28. // (`hl:http1`'s server iterator has been both since mission 012/052).
  29. //
  30. // TLS rides plugins/http/tls_common.zig — the SAME OpenSSL layer the servers use,
  31. // through the client half mission 137 added to it. There is no second TLS here.
  32. const std = @import("std");
  33. const api = @import("plugin_api");
  34. const http = @import("http_common");
  35. const tls = @import("tls_common");
  36. const HlValue = api.HlValue;
  37. const HlObject = api.HlObject;
  38. const HlField = api.HlField;
  39. const HlIterator = api.HlIterator;
  40. const HlString = api.HlString;
  41. const linux = std.os.linux;
  42. const c = std.c;
  43. const PthreadMutex = c.pthread_mutex_t;
  44. const PthreadCond = c.pthread_cond_t;
  45. // per-mailer state is touched by two threads: the plugins' allocator (plugin_api.zig)
  46. const allocator = api.allocator;
  47. fn mutexLock(m: *PthreadMutex) void {
  48. _ = c.pthread_mutex_lock(m);
  49. }
  50. fn mutexUnlock(m: *PthreadMutex) void {
  51. _ = c.pthread_mutex_unlock(m);
  52. }
  53. fn condSignal(cnd: *PthreadCond) void {
  54. _ = c.pthread_cond_signal(cnd);
  55. }
  56. fn condBroadcast(cnd: *PthreadCond) void {
  57. _ = c.pthread_cond_broadcast(cnd);
  58. }
  59. fn condWait(cnd: *PthreadCond, m: *PthreadMutex) void {
  60. _ = c.pthread_cond_wait(cnd, m);
  61. }
  62. /// Direct syscall for stderr — std.debug.print pulls in std.Progress, whose
  63. /// global state is ABI-incompatible when a .so is loaded into a differently
  64. /// built binary (the same reason tls_common.zig has its own).
  65. fn logMsg(msg: []const u8) void {
  66. _ = linux.write(2, msg.ptr, msg.len);
  67. }
  68. // ── REFUSALS ────────────────────────────────────────────────────────────────
  69. //
  70. // An hl_error returned at the top level of a plugin call becomes a LOCATED
  71. // runtime error at the `__native` call site and is offered to `on Error(e)`
  72. // first (plugin_loader / native_bridge). That is the channel every local refusal
  73. // here uses, so `m.send(…)` with a newline in the subject points at the line the
  74. // author wrote and is catchable exactly like any other plugin failure.
  75. //
  76. // The text is rendered into a module buffer: a plugin call never yields, and the
  77. // runtime dupes the string into its own tracker the instant the call returns.
  78. var err_buf: [1024]u8 = undefined;
  79. fn refuse(comptime fmt: []const u8, args: anytype) HlValue {
  80. const s = std.fmt.bufPrint(&err_buf, fmt, args) catch "hl:smtp refused the message";
  81. return api.makeError(s);
  82. }
  83. // ── ARGUMENT READING ────────────────────────────────────────────────────────
  84. fn fieldOf(v: HlValue, key: []const u8) ?HlValue {
  85. if (v.type != .hl_object) return null;
  86. const obj = v.data.object;
  87. for (obj.fields[0..obj.field_count]) |f| {
  88. if (std.mem.eql(u8, f.key.ptr[0..f.key.len], key)) return f.value;
  89. }
  90. return null;
  91. }
  92. fn strField(v: HlValue, key: []const u8) ?[]const u8 {
  93. const f = fieldOf(v, key) orelse return null;
  94. if (f.type != .hl_string) return null;
  95. return f.data.string.ptr[0..f.data.string.len];
  96. }
  97. fn boolField(v: HlValue, key: []const u8, dflt: bool) bool {
  98. const f = fieldOf(v, key) orelse return dflt;
  99. return switch (f.type) {
  100. .hl_bool => f.data.boolean,
  101. else => dflt,
  102. };
  103. }
  104. fn numField(v: HlValue, key: []const u8, dflt: f64) f64 {
  105. const f = fieldOf(v, key) orelse return dflt;
  106. if (f.type != .hl_number) return dflt;
  107. return f.data.number;
  108. }
  109. /// THE SENDER'S ADDRESS, under either name.
  110. ///
  111. /// `from` is a RESERVED WORD in Hybriel (`import X from './x.hl'`), so
  112. /// `{ from = "a@b" }` does not parse and `msg.from` is not a member access.
  113. /// Rather than force every caller to write the quoted-key form, both spellings
  114. /// are read here: `"from" = …` (the quoted key, which parses fine and is what
  115. /// mission 137's brief names) and `sender = …` (the bare-identifier form, for a
  116. /// caller who would rather not quote). Same field, one meaning; the quoted one
  117. /// wins if a message somehow carries both.
  118. fn senderField(v: HlValue) ?[]const u8 {
  119. if (strField(v, "from")) |s| return s;
  120. return strField(v, "sender");
  121. }
  122. fn dupOpt(s: ?[]const u8) ?[]u8 {
  123. const src = s orelse return null;
  124. if (src.len == 0) return null;
  125. return allocator.dupe(u8, src) catch null;
  126. }
  127. // ── CONFIGURATION ───────────────────────────────────────────────────────────
  128. const TlsMode = enum { starttls, implicit, none };
  129. const AuthMode = enum { auto, plain, login, none };
  130. // ── THE JOB AND ITS RESULT ──────────────────────────────────────────────────
  131. const Job = struct {
  132. id: u32,
  133. from: []u8,
  134. /// Envelope recipients — every RCPT TO the conversation issues.
  135. rcpt: [][]u8,
  136. /// The rendered RFC 5322 message: CRLF line endings, dot-stuffed, WITHOUT
  137. /// the terminating ".". Built on the Hybriel thread by `send`.
  138. data: []u8,
  139. fn deinit(self: *Job) void {
  140. allocator.free(self.from);
  141. for (self.rcpt) |r| allocator.free(r);
  142. allocator.free(self.rcpt);
  143. allocator.free(self.data);
  144. }
  145. };
  146. const Result = struct {
  147. id: u32,
  148. ok: bool,
  149. /// The last SMTP reply code the conversation saw (0 = never got one).
  150. code: u16,
  151. /// Which step answered: "connect", "greeting", "ehlo", "starttls", "auth",
  152. /// "mail", "rcpt", "data", "body", "quit", "done".
  153. stage: []const u8,
  154. /// The server's own text, or this plugin's reason for giving up.
  155. message: []u8,
  156. /// Did the conversation run inside TLS by the time DATA was sent?
  157. secure: bool,
  158. rcpt: [][]u8,
  159. };
  160. // ── THE MAILER ──────────────────────────────────────────────────────────────
  161. const Mailer = struct {
  162. id: u32,
  163. host: []u8,
  164. port: u16,
  165. user: ?[]u8,
  166. pass: ?[]u8,
  167. from: []u8,
  168. helo: []u8,
  169. tls_mode: TlsMode,
  170. auth_mode: AuthMode,
  171. ca_file: ?[]u8,
  172. verify: bool,
  173. /// Send AUTH over a connection that never became TLS. OFF by default: the
  174. /// credentials would be on the wire in the clear, and a default that leaks
  175. /// them is not a default, it is a bug with a setting.
  176. allow_insecure_auth: bool,
  177. timeout_ms: u32,
  178. mutex: PthreadMutex,
  179. /// The worker parks here for the next job; the drain parks here for the next
  180. /// result. One lock covers both queues and `outstanding`, which is what makes
  181. /// "no results and nothing outstanding" a single consistent observation.
  182. condvar: PthreadCond,
  183. jobs: std.ArrayListUnmanaged(Job) = .empty,
  184. results: std.ArrayListUnmanaged(Result) = .empty,
  185. /// Jobs accepted and not yet answered. The blocking drain ends when this is
  186. /// zero and the result queue is empty — that is what lets a script that only
  187. /// sends mail terminate.
  188. outstanding: usize = 0,
  189. next_job: u32 = 1,
  190. stop: bool = false,
  191. /// Mission 125's bell for the event loop. Rung whenever a result becomes
  192. /// visible; over-ringing is free, a missed ring is the only bug there is.
  193. wake_fd: i32 = -1,
  194. worker: ?std.Thread = null,
  195. /// The source object is made ONCE: two iterators over one queue would each
  196. /// steal half the results.
  197. source: ?*HlIterator = null,
  198. registered: bool = false,
  199. fn enqueue(self: *Mailer, job: Job) void {
  200. mutexLock(&self.mutex);
  201. defer mutexUnlock(&self.mutex);
  202. self.jobs.append(allocator, job) catch return;
  203. self.outstanding += 1;
  204. condBroadcast(&self.condvar);
  205. }
  206. fn takeJob(self: *Mailer) ?Job {
  207. mutexLock(&self.mutex);
  208. defer mutexUnlock(&self.mutex);
  209. while (self.jobs.items.len == 0 and !self.stop) {
  210. condWait(&self.condvar, &self.mutex);
  211. }
  212. if (self.jobs.items.len == 0) return null;
  213. return self.jobs.orderedRemove(0);
  214. }
  215. fn publish(self: *Mailer, result: Result) void {
  216. mutexLock(&self.mutex);
  217. self.results.append(allocator, result) catch {};
  218. if (self.outstanding > 0) self.outstanding -= 1;
  219. condBroadcast(&self.condvar);
  220. // Rung while the append is still under the lock — the loop drains the
  221. // eventfd counter only immediately AFTER a wake, never before blocking,
  222. // so a bell rung any time after that drain leaves the level up and the
  223. // next epoll_wait returns at once (native/src/loop_wait.zig).
  224. http.ringWake(self.wake_fd);
  225. mutexUnlock(&self.mutex);
  226. }
  227. fn tryTake(self: *Mailer) ?Result {
  228. mutexLock(&self.mutex);
  229. defer mutexUnlock(&self.mutex);
  230. if (self.results.items.len == 0) return null;
  231. const result = self.results.orderedRemove(0);
  232. if (self.results.items.len > 0) http.ringWake(self.wake_fd);
  233. return result;
  234. }
  235. /// Blocking take for the drain form. `null` means DONE, not "nothing yet":
  236. /// every accepted job has been answered and its answer taken.
  237. fn take(self: *Mailer) ?Result {
  238. mutexLock(&self.mutex);
  239. defer mutexUnlock(&self.mutex);
  240. while (self.results.items.len == 0 and self.outstanding > 0 and !self.stop) {
  241. condWait(&self.condvar, &self.mutex);
  242. }
  243. if (self.results.items.len == 0) return null;
  244. const result = self.results.orderedRemove(0);
  245. if (self.results.items.len > 0) http.ringWake(self.wake_fd);
  246. return result;
  247. }
  248. };
  249. var mailers: std.ArrayListUnmanaged(*Mailer) = .empty;
  250. var mailers_mutex: PthreadMutex = c.PTHREAD_MUTEX_INITIALIZER;
  251. var next_mailer_id: u32 = 1;
  252. fn mailerById(id: u32) ?*Mailer {
  253. mutexLock(&mailers_mutex);
  254. defer mutexUnlock(&mailers_mutex);
  255. for (mailers.items) |m| {
  256. if (m.id == id) return m;
  257. }
  258. return null;
  259. }
  260. // ── HEADER INJECTION IS A REFUSAL, NOT AN ESCAPE ────────────────────────────
  261. //
  262. // A CR or an LF inside a `to`, a `from` or a `subject` ends the header and
  263. // starts a new one — that is the whole of SMTP header injection, and it is how a
  264. // contact form becomes an open relay (`subject = "hi\r\nBcc: everyone@…"`).
  265. // Stripping the characters silently would deliver a mail the author did not
  266. // write; escaping them is not defined for a header field. So it is a located
  267. // refusal, at the caller's line, naming the field and the character.
  268. fn checkHeaderValue(field: []const u8, value: []const u8) ?HlValue {
  269. for (value, 0..) |ch, i| {
  270. if (ch == '\r' or ch == '\n') {
  271. return refuse(
  272. "hl:smtp refused the message: {s} contains a {s} at byte {d} — a line break in a header field is how mail headers are injected, so it is never sent and never stripped",
  273. .{ field, if (ch == '\r') "carriage return" else "line feed", i },
  274. );
  275. }
  276. if (ch == 0) {
  277. return refuse(
  278. "hl:smtp refused the message: {s} contains a NUL byte at byte {d}",
  279. .{ field, i },
  280. );
  281. }
  282. }
  283. return null;
  284. }
  285. /// An envelope address additionally may not carry the delimiters the envelope
  286. /// itself is made of: `MAIL FROM:<a@b>` is a command, and a `<`, `>` or a space
  287. /// inside the address would rewrite it.
  288. fn checkAddress(field: []const u8, value: []const u8) ?HlValue {
  289. if (checkHeaderValue(field, value)) |e| return e;
  290. if (value.len == 0) {
  291. return refuse("hl:smtp refused the message: {s} is empty", .{field});
  292. }
  293. for (value) |ch| {
  294. if (ch == '<' or ch == '>' or ch == ' ' or ch == '\t') {
  295. return refuse(
  296. "hl:smtp refused the message: the address '{s}' in {s} contains '{c}' — an envelope address is written between angle brackets and may not carry them, or whitespace",
  297. .{ value, field, ch },
  298. );
  299. }
  300. }
  301. if (std.mem.indexOfScalar(u8, value, '@') == null) {
  302. return refuse(
  303. "hl:smtp refused the message: the address '{s}' in {s} has no '@'",
  304. .{ value, field },
  305. );
  306. }
  307. return null;
  308. }
  309. // ── MESSAGE RENDERING ───────────────────────────────────────────────────────
  310. const b64 = std.base64.standard.Encoder;
  311. fn b64Alloc(src: []const u8) ![]u8 {
  312. const out = try allocator.alloc(u8, b64.calcSize(src.len));
  313. _ = b64.encode(out, src);
  314. return out;
  315. }
  316. fn isAscii(s: []const u8) bool {
  317. for (s) |ch| {
  318. if (ch >= 0x80) return false;
  319. }
  320. return true;
  321. }
  322. const day_names = [_][]const u8{ "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed" };
  323. const month_names = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  324. /// RFC 5322 §3.3 date-time, always +0000. A mail without a Date is not a mail —
  325. /// receivers add their own and it reads as a forgery.
  326. fn writeDate(w: *std.ArrayListUnmanaged(u8)) !void {
  327. var ts: linux.timespec = undefined;
  328. _ = linux.clock_gettime(linux.CLOCK.REALTIME, &ts);
  329. const secs: u64 = @intCast(@max(@as(i64, ts.sec), 0));
  330. const es = std.time.epoch.EpochSeconds{ .secs = secs };
  331. const yd = es.getEpochDay().calculateYearDay();
  332. const md = yd.calculateMonthDay();
  333. const ds = es.getDaySeconds();
  334. // 1970-01-01 was a Thursday, which is why day_names starts there.
  335. const dow = day_names[@intCast(es.getEpochDay().day % 7)];
  336. var buf: [64]u8 = undefined;
  337. const line = try std.fmt.bufPrint(&buf, "Date: {s}, {d:0>2} {s} {d} {d:0>2}:{d:0>2}:{d:0>2} +0000\r\n", .{
  338. dow,
  339. @as(u32, md.day_index) + 1,
  340. month_names[md.month.numeric() - 1],
  341. yd.year,
  342. ds.getHoursIntoDay(),
  343. ds.getMinutesIntoHour(),
  344. ds.getSecondsIntoMinute(),
  345. });
  346. try w.appendSlice(allocator, line);
  347. }
  348. fn randomHex(out: []u8) void {
  349. var raw: [32]u8 = undefined;
  350. const need = (out.len + 1) / 2;
  351. if (linux.getrandom(&raw, need, 0) != need) {
  352. @memset(out, '0');
  353. return;
  354. }
  355. const hex = "0123456789abcdef";
  356. for (out, 0..) |*ch, i| {
  357. const byte = raw[i / 2];
  358. const nib: u8 = if (i % 2 == 0) (byte >> 4) else (byte & 0x0f);
  359. ch.* = hex[nib];
  360. }
  361. }
  362. /// A header value that is not pure ASCII becomes an RFC 2047 encoded-word.
  363. /// Writing raw UTF-8 into a header is only legal with SMTPUTF8 negotiated, which
  364. /// this client does not do — so an umlaut in a subject would arrive as mojibake.
  365. fn appendHeader(w: *std.ArrayListUnmanaged(u8), name: []const u8, value: []const u8) !void {
  366. try w.appendSlice(allocator, name);
  367. try w.appendSlice(allocator, ": ");
  368. if (isAscii(value)) {
  369. try w.appendSlice(allocator, value);
  370. } else {
  371. const enc = try b64Alloc(value);
  372. defer allocator.free(enc);
  373. try w.appendSlice(allocator, "=?UTF-8?B?");
  374. try w.appendSlice(allocator, enc);
  375. try w.appendSlice(allocator, "?=");
  376. }
  377. try w.appendSlice(allocator, "\r\n");
  378. }
  379. /// CRLF DISCIPLINE AND DOT-STUFFING, in one pass over the assembled message.
  380. ///
  381. /// SMTP's line terminator is CRLF and its end-of-data marker is a line holding
  382. /// exactly ".", so a body line that legitimately begins with "." must be sent as
  383. /// ".." (RFC 5321 §4.5.2) or it truncates the mail — and a lone LF, which every
  384. /// text a program builds is full of, is not a line ending at all on the wire.
  385. fn appendDotStuffed(w: *std.ArrayListUnmanaged(u8), body: []const u8) !void {
  386. var at_line_start = true;
  387. var i: usize = 0;
  388. while (i < body.len) : (i += 1) {
  389. const ch = body[i];
  390. if (ch == '\r') {
  391. // Normalise CR and CRLF alike to one CRLF; a bare CR is a line
  392. // ending in nothing that talks SMTP.
  393. if (i + 1 < body.len and body[i + 1] == '\n') i += 1;
  394. try w.appendSlice(allocator, "\r\n");
  395. at_line_start = true;
  396. continue;
  397. }
  398. if (ch == '\n') {
  399. try w.appendSlice(allocator, "\r\n");
  400. at_line_start = true;
  401. continue;
  402. }
  403. if (at_line_start and ch == '.') try w.append(allocator, '.');
  404. try w.append(allocator, ch);
  405. at_line_start = false;
  406. }
  407. if (!at_line_start) try w.appendSlice(allocator, "\r\n");
  408. }
  409. // ── THE CONNECTION ──────────────────────────────────────────────────────────
  410. const Conn = struct {
  411. fd: i32 = -1,
  412. ssl: ?*tls.SSL = null,
  413. ctx: ?tls.TlsContext = null,
  414. buf: [4096]u8 = undefined,
  415. len: usize = 0,
  416. pos: usize = 0,
  417. fn writeAll(self: *Conn, bytes: []const u8) bool {
  418. if (self.ssl) |ssl| {
  419. const ctx = &(self.ctx orelse return false);
  420. return ctx.writeAll(ssl, bytes) == bytes.len;
  421. }
  422. var off: usize = 0;
  423. while (off < bytes.len) {
  424. const rc = linux.write(self.fd, bytes.ptr + off, bytes.len - off);
  425. const n: isize = @bitCast(rc);
  426. if (n <= 0) return false;
  427. off += @intCast(n);
  428. }
  429. return true;
  430. }
  431. fn fill(self: *Conn) bool {
  432. if (self.ssl) |ssl| {
  433. const ctx = &(self.ctx orelse return false);
  434. const n = ctx.read(ssl, self.buf[0..]);
  435. if (n <= 0) return false;
  436. self.len = @intCast(n);
  437. self.pos = 0;
  438. return true;
  439. }
  440. const rc = linux.read(self.fd, &self.buf, self.buf.len);
  441. const n: isize = @bitCast(rc);
  442. if (n <= 0) return false;
  443. self.len = @intCast(n);
  444. self.pos = 0;
  445. return true;
  446. }
  447. /// One CRLF-terminated reply line, without its terminator, appended into
  448. /// `out` (which is cleared first). `false` = the peer went away or timed out.
  449. fn readLine(self: *Conn, out: *std.ArrayListUnmanaged(u8)) bool {
  450. out.clearRetainingCapacity();
  451. while (true) {
  452. if (self.pos >= self.len) {
  453. if (!self.fill()) return false;
  454. }
  455. const ch = self.buf[self.pos];
  456. self.pos += 1;
  457. if (ch == '\n') {
  458. if (out.items.len > 0 and out.items[out.items.len - 1] == '\r') {
  459. _ = out.pop();
  460. }
  461. return true;
  462. }
  463. out.append(allocator, ch) catch return false;
  464. if (out.items.len > 65536) return false;
  465. }
  466. }
  467. fn close(self: *Conn) void {
  468. if (self.ssl) |ssl| {
  469. if (self.ctx) |*ctx| ctx.shutdownAndFree(ssl);
  470. self.ssl = null;
  471. }
  472. if (self.ctx) |*ctx| {
  473. ctx.deinit();
  474. self.ctx = null;
  475. }
  476. if (self.fd >= 0) {
  477. _ = linux.close(self.fd);
  478. self.fd = -1;
  479. }
  480. }
  481. };
  482. /// A complete SMTP reply: the code, and every line's text joined with "; ".
  483. const Reply = struct {
  484. code: u16 = 0,
  485. text: std.ArrayListUnmanaged(u8) = .empty,
  486. fn deinit(self: *Reply) void {
  487. self.text.deinit(allocator);
  488. }
  489. };
  490. /// Read a reply, following RFC 5321 §4.2's multiline form (`250-…` continues,
  491. /// `250 …` ends). Returns false if the connection died mid-reply.
  492. fn readReply(conn: *Conn, reply: *Reply) bool {
  493. reply.text.clearRetainingCapacity();
  494. reply.code = 0;
  495. var line: std.ArrayListUnmanaged(u8) = .empty;
  496. defer line.deinit(allocator);
  497. var first = true;
  498. while (true) {
  499. if (!conn.readLine(&line)) return false;
  500. const s = line.items;
  501. if (s.len < 3) return false;
  502. const code = std.fmt.parseInt(u16, s[0..3], 10) catch return false;
  503. if (first) {
  504. reply.code = code;
  505. first = false;
  506. }
  507. const rest = if (s.len > 4) s[4..] else "";
  508. if (reply.text.items.len > 0) reply.text.appendSlice(allocator, "; ") catch {};
  509. reply.text.appendSlice(allocator, rest) catch {};
  510. if (s.len == 3 or s[3] != '-') return true;
  511. }
  512. }
  513. fn command(conn: *Conn, reply: *Reply, parts: []const []const u8) bool {
  514. for (parts) |p| {
  515. if (!conn.writeAll(p)) return false;
  516. }
  517. if (!conn.writeAll("\r\n")) return false;
  518. return readReply(conn, reply);
  519. }
  520. /// Does the EHLO capability list advertise `name`? Case-insensitive, and
  521. /// anchored on a word boundary so "AUTH" does not match "AUTHOR".
  522. fn advertises(caps: []const u8, name: []const u8) bool {
  523. var i: usize = 0;
  524. while (i + name.len <= caps.len) : (i += 1) {
  525. if (std.ascii.eqlIgnoreCase(caps[i .. i + name.len], name)) {
  526. const before_ok = i == 0 or !std.ascii.isAlphanumeric(caps[i - 1]);
  527. const after = i + name.len;
  528. const after_ok = after >= caps.len or !std.ascii.isAlphanumeric(caps[after]);
  529. if (before_ok and after_ok) return true;
  530. }
  531. }
  532. return false;
  533. }
  534. // ── DIALLING ────────────────────────────────────────────────────────────────
  535. /// Connect to host:port with `timeout_ms` bounding BOTH the connect and every
  536. /// later read/write. A blocking connect(2) ignores SO_SNDTIMEO, so the connect
  537. /// is made non-blocking and polled; the socket goes back to blocking afterwards
  538. /// and the two socket timeouts carry the rest of the conversation.
  539. fn dial(host: []const u8, port: u16, timeout_ms: u32, reason: *std.ArrayListUnmanaged(u8)) ?i32 {
  540. // libc's resolver, not a hand-rolled one: /etc/hosts, /etc/resolv.conf,
  541. // nsswitch and IPv6 are the host's configuration, and a mail client that
  542. // answers differently from every other program on the machine is a bug.
  543. var host_z_buf: [256]u8 = undefined;
  544. if (host.len >= host_z_buf.len) {
  545. reason.appendSlice(allocator, "the host name is too long") catch {};
  546. return null;
  547. }
  548. @memcpy(host_z_buf[0..host.len], host);
  549. host_z_buf[host.len] = 0;
  550. var port_buf: [8]u8 = undefined;
  551. const port_s = std.fmt.bufPrintZ(&port_buf, "{d}", .{port}) catch {
  552. reason.appendSlice(allocator, "bad port") catch {};
  553. return null;
  554. };
  555. const hints = c.addrinfo{
  556. .flags = .{},
  557. .family = c.AF.UNSPEC,
  558. .socktype = c.SOCK.STREAM,
  559. .protocol = 0,
  560. .addrlen = 0,
  561. .canonname = null,
  562. .addr = null,
  563. .next = null,
  564. };
  565. var res: ?*c.addrinfo = null;
  566. const rc_ai = c.getaddrinfo(@ptrCast(&host_z_buf), port_s.ptr, &hints, &res);
  567. if (rc_ai != @as(c.EAI, @enumFromInt(0)) or res == null) {
  568. reason.appendSlice(allocator, "could not resolve the host") catch {};
  569. return null;
  570. }
  571. defer c.freeaddrinfo(res.?);
  572. var last: []const u8 = "connection refused";
  573. var cursor: ?*c.addrinfo = res;
  574. while (cursor) |ai| : (cursor = ai.next) {
  575. const sa = ai.addr orelse continue;
  576. const rc = linux.socket(@intCast(ai.family), linux.SOCK.STREAM | linux.SOCK.CLOEXEC, 0);
  577. const fd: i32 = @intCast(@as(isize, @bitCast(rc)));
  578. if (fd < 0) continue;
  579. const flags_rc = linux.fcntl(fd, linux.F.GETFL, @as(usize, 0));
  580. var oflags: linux.O = @bitCast(@as(u32, @truncate(flags_rc)));
  581. oflags.NONBLOCK = true;
  582. _ = linux.fcntl(fd, linux.F.SETFL, @as(usize, @as(u32, @bitCast(oflags))));
  583. const crc = linux.connect(fd, @ptrCast(sa), ai.addrlen);
  584. const cerr: isize = @bitCast(crc);
  585. var connected = cerr == 0;
  586. if (!connected) {
  587. // A negative return is -errno; INPROGRESS is the non-blocking
  588. // connect's ordinary answer, not a failure.
  589. const e: linux.E = @enumFromInt(@as(u16, @intCast(-cerr)));
  590. if (e != .INPROGRESS and e != .INTR) {
  591. last = "connection refused";
  592. _ = linux.close(fd);
  593. continue;
  594. }
  595. var pfd = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.OUT, .revents = 0 }};
  596. const prc = linux.poll(&pfd, 1, @intCast(timeout_ms));
  597. const pn: isize = @bitCast(prc);
  598. if (pn <= 0) {
  599. last = "the connection attempt timed out";
  600. _ = linux.close(fd);
  601. continue;
  602. }
  603. var soerr: i32 = 0;
  604. var slen: linux.socklen_t = @sizeOf(i32);
  605. _ = linux.getsockopt(fd, linux.SOL.SOCKET, linux.SO.ERROR, @ptrCast(&soerr), &slen);
  606. if (soerr != 0) {
  607. last = "connection refused";
  608. _ = linux.close(fd);
  609. continue;
  610. }
  611. connected = true;
  612. }
  613. oflags.NONBLOCK = false;
  614. _ = linux.fcntl(fd, linux.F.SETFL, @as(usize, @as(u32, @bitCast(oflags))));
  615. const tv = linux.timeval{
  616. .sec = @intCast(timeout_ms / 1000),
  617. .usec = @intCast((timeout_ms % 1000) * 1000),
  618. };
  619. _ = linux.setsockopt(fd, linux.SOL.SOCKET, linux.SO.RCVTIMEO, @ptrCast(&tv), @sizeOf(linux.timeval));
  620. _ = linux.setsockopt(fd, linux.SOL.SOCKET, linux.SO.SNDTIMEO, @ptrCast(&tv), @sizeOf(linux.timeval));
  621. return fd;
  622. }
  623. reason.appendSlice(allocator, last) catch {};
  624. return null;
  625. }
  626. // ── THE CONVERSATION ────────────────────────────────────────────────────────
  627. const Outcome = struct {
  628. ok: bool,
  629. code: u16,
  630. stage: []const u8,
  631. message: []u8,
  632. secure: bool,
  633. };
  634. fn own(text: []const u8) []u8 {
  635. return allocator.dupe(u8, text) catch allocator.alloc(u8, 0) catch unreachable;
  636. }
  637. fn fail(stage: []const u8, code: u16, secure: bool, text: []const u8) Outcome {
  638. return .{ .ok = false, .code = code, .stage = stage, .message = own(text), .secure = secure };
  639. }
  640. fn runJob(m: *Mailer, job: *const Job) Outcome {
  641. var conn = Conn{};
  642. defer conn.close();
  643. var reason: std.ArrayListUnmanaged(u8) = .empty;
  644. defer reason.deinit(allocator);
  645. const fd = dial(m.host, m.port, m.timeout_ms, &reason) orelse
  646. return fail("connect", 0, false, reason.items);
  647. conn.fd = fd;
  648. var secure = false;
  649. if (m.tls_mode == .implicit) {
  650. const ctx = tls.TlsContext.initClient(.{
  651. .ca_file = if (m.ca_file) |ca| ca else null,
  652. .verify = m.verify,
  653. .tag = "smtp",
  654. }) orelse return fail("connect", 0, false, "TLS is unavailable (no usable libssl on this host, or the CA file could not be loaded)");
  655. conn.ctx = ctx;
  656. conn.ssl = conn.ctx.?.connect(fd, m.host, "smtp") orelse
  657. return fail("connect", 0, false, "the implicit TLS handshake failed (see the smtp: lines on stderr)");
  658. secure = true;
  659. }
  660. var reply = Reply{};
  661. defer reply.deinit();
  662. if (!readReply(&conn, &reply)) return fail("greeting", 0, secure, "the server sent no greeting");
  663. if (reply.code != 220) return fail("greeting", reply.code, secure, reply.text.items);
  664. // EHLO, and keep the capability list — STARTTLS and AUTH are both read off it.
  665. var caps: std.ArrayListUnmanaged(u8) = .empty;
  666. defer caps.deinit(allocator);
  667. if (!command(&conn, &reply, &.{ "EHLO ", m.helo })) return fail("ehlo", 0, secure, "the connection closed during EHLO");
  668. if (reply.code != 250) return fail("ehlo", reply.code, secure, reply.text.items);
  669. caps.appendSlice(allocator, reply.text.items) catch {};
  670. if (m.tls_mode == .starttls and !secure) {
  671. if (!advertises(caps.items, "STARTTLS")) {
  672. return fail("starttls", 0, secure, "the server does not advertise STARTTLS (set tls = \"none\" to accept a plaintext session deliberately)");
  673. }
  674. if (!command(&conn, &reply, &.{"STARTTLS"})) return fail("starttls", 0, secure, "the connection closed during STARTTLS");
  675. if (reply.code != 220) return fail("starttls", reply.code, secure, reply.text.items);
  676. const ctx = tls.TlsContext.initClient(.{
  677. .ca_file = if (m.ca_file) |ca| ca else null,
  678. .verify = m.verify,
  679. .tag = "smtp",
  680. }) orelse return fail("starttls", 0, secure, "TLS is unavailable (no usable libssl on this host, or the CA file could not be loaded)");
  681. conn.ctx = ctx;
  682. // The SAME socket, mid-protocol: this is what STARTTLS is, and the
  683. // client half of tls_common.zig takes it as it stands.
  684. conn.ssl = conn.ctx.?.connect(fd, m.host, "smtp") orelse
  685. return fail("starttls", 0, secure, "the STARTTLS handshake failed (see the smtp: lines on stderr)");
  686. secure = true;
  687. conn.len = 0;
  688. conn.pos = 0;
  689. // RFC 3207 §4.2: everything learned before the upgrade is discarded and
  690. // EHLO is re-issued inside TLS — a capability list from the plaintext
  691. // half is exactly what an attacker in the middle would have written.
  692. caps.clearRetainingCapacity();
  693. if (!command(&conn, &reply, &.{ "EHLO ", m.helo })) return fail("ehlo", 0, secure, "the connection closed during the post-STARTTLS EHLO");
  694. if (reply.code != 250) return fail("ehlo", reply.code, secure, reply.text.items);
  695. caps.appendSlice(allocator, reply.text.items) catch {};
  696. }
  697. // AUTH
  698. if (m.user != null and m.pass != null and m.auth_mode != .none) {
  699. if (!secure and !m.allow_insecure_auth) {
  700. return fail("auth", 0, secure, "refusing to send credentials over a plaintext connection — use tls = \"starttls\" (the default) or \"implicit\", or set allowInsecureAuth = true to say the clear text is intended");
  701. }
  702. const wants_login = switch (m.auth_mode) {
  703. .login => true,
  704. .plain => false,
  705. else => !advertises(caps.items, "PLAIN") and advertises(caps.items, "LOGIN"),
  706. };
  707. const outcome = if (wants_login) authLogin(m, &conn, &reply, secure) else authPlain(m, &conn, &reply, secure);
  708. if (outcome) |o| return o;
  709. }
  710. if (!command(&conn, &reply, &.{ "MAIL FROM:<", job.from, ">" })) return fail("mail", 0, secure, "the connection closed during MAIL FROM");
  711. if (reply.code != 250) return fail("mail", reply.code, secure, reply.text.items);
  712. for (job.rcpt) |r| {
  713. if (!command(&conn, &reply, &.{ "RCPT TO:<", r, ">" })) return fail("rcpt", 0, secure, "the connection closed during RCPT TO");
  714. // 251 = "will forward"; anything else non-2xx is a rejected recipient,
  715. // and one rejected recipient fails the whole send rather than silently
  716. // delivering to the rest (the app decides what to do about it).
  717. if (reply.code != 250 and reply.code != 251) return fail("rcpt", reply.code, secure, reply.text.items);
  718. }
  719. if (!command(&conn, &reply, &.{"DATA"})) return fail("data", 0, secure, "the connection closed during DATA");
  720. if (reply.code != 354) return fail("data", reply.code, secure, reply.text.items);
  721. if (!conn.writeAll(job.data)) return fail("body", 0, secure, "the connection closed while the message was being written");
  722. if (!conn.writeAll(".\r\n")) return fail("body", 0, secure, "the connection closed at the end-of-data marker");
  723. if (!readReply(&conn, &reply)) return fail("body", 0, secure, "the server never acknowledged the message");
  724. if (reply.code != 250) return fail("body", reply.code, secure, reply.text.items);
  725. const accepted = own(reply.text.items);
  726. // QUIT is courtesy: the message is accepted the moment DATA answered 250, so
  727. // a server that drops the socket instead of saying 221 has not lost it.
  728. _ = command(&conn, &reply, &.{"QUIT"});
  729. return .{ .ok = true, .code = 250, .stage = "done", .message = accepted, .secure = secure };
  730. }
  731. /// AUTH PLAIN — RFC 4616: base64 of "\0user\0pass", in the command itself.
  732. fn authPlain(m: *Mailer, conn: *Conn, reply: *Reply, secure: bool) ?Outcome {
  733. const user = m.user.?;
  734. const pass = m.pass.?;
  735. const raw = allocator.alloc(u8, 2 + user.len + pass.len) catch return fail("auth", 0, secure, "out of memory");
  736. defer allocator.free(raw);
  737. raw[0] = 0;
  738. @memcpy(raw[1 .. 1 + user.len], user);
  739. raw[1 + user.len] = 0;
  740. @memcpy(raw[2 + user.len ..], pass);
  741. const enc = b64Alloc(raw) catch return fail("auth", 0, secure, "out of memory");
  742. defer allocator.free(enc);
  743. if (!command(conn, reply, &.{ "AUTH PLAIN ", enc })) return fail("auth", 0, secure, "the connection closed during AUTH PLAIN");
  744. if (reply.code != 235) return fail("auth", reply.code, secure, reply.text.items);
  745. return null;
  746. }
  747. /// AUTH LOGIN — the de-facto challenge/response form: base64 username, then
  748. /// base64 password, each answering a 334.
  749. fn authLogin(m: *Mailer, conn: *Conn, reply: *Reply, secure: bool) ?Outcome {
  750. if (!command(conn, reply, &.{"AUTH LOGIN"})) return fail("auth", 0, secure, "the connection closed during AUTH LOGIN");
  751. if (reply.code != 334) return fail("auth", reply.code, secure, reply.text.items);
  752. const user_enc = b64Alloc(m.user.?) catch return fail("auth", 0, secure, "out of memory");
  753. defer allocator.free(user_enc);
  754. if (!command(conn, reply, &.{user_enc})) return fail("auth", 0, secure, "the connection closed after the username");
  755. if (reply.code != 334) return fail("auth", reply.code, secure, reply.text.items);
  756. const pass_enc = b64Alloc(m.pass.?) catch return fail("auth", 0, secure, "out of memory");
  757. defer allocator.free(pass_enc);
  758. if (!command(conn, reply, &.{pass_enc})) return fail("auth", 0, secure, "the connection closed after the password");
  759. if (reply.code != 235) return fail("auth", reply.code, secure, reply.text.items);
  760. return null;
  761. }
  762. fn workerLoop(m: *Mailer) void {
  763. while (true) {
  764. var job = m.takeJob() orelse break;
  765. const outcome = runJob(m, &job);
  766. const rcpt: [][]u8 = allocator.alloc([]u8, job.rcpt.len) catch &.{};
  767. for (job.rcpt, 0..) |r, i| {
  768. if (i < rcpt.len) rcpt[i] = allocator.dupe(u8, r) catch own("");
  769. }
  770. m.publish(.{
  771. .id = job.id,
  772. .ok = outcome.ok,
  773. .code = outcome.code,
  774. .stage = outcome.stage,
  775. .message = outcome.message,
  776. .secure = outcome.secure,
  777. .rcpt = rcpt,
  778. });
  779. job.deinit();
  780. }
  781. }
  782. // ── THE RESULT SOURCE ───────────────────────────────────────────────────────
  783. /// The loader converts a nested `hl_object` by recursing and running THAT
  784. /// object's own `deinit_fn` before it runs this one, so the `to` list is already
  785. /// gone by the time this is called — touching it here is a double free (measured,
  786. /// mission 137). Only the string values this object owns are freed here.
  787. fn resultObjDeinit(obj: *HlObject) callconv(.c) void {
  788. const fields = obj.fields[0..obj.field_count];
  789. for (fields) |f| {
  790. if (f.value.type == .hl_string) {
  791. allocator.free(@constCast(f.value.data.string.ptr[0..f.value.data.string.len]));
  792. }
  793. }
  794. allocator.free(fields);
  795. allocator.destroy(obj);
  796. }
  797. fn rcptObjDeinit(obj: *HlObject) callconv(.c) void {
  798. const fields = obj.fields[0..obj.field_count];
  799. for (fields) |f| {
  800. allocator.free(@constCast(f.key.ptr[0..f.key.len]));
  801. if (f.value.type == .hl_string) {
  802. allocator.free(@constCast(f.value.data.string.ptr[0..f.value.data.string.len]));
  803. }
  804. }
  805. allocator.free(fields);
  806. allocator.destroy(obj);
  807. }
  808. /// Contiguous "0".."n-1" keys is how the loader recognises an ordered hybrid, so
  809. /// `res.to` arrives in Hybriel as a list however many recipients there were.
  810. fn rcptValue(rcpt: [][]u8) HlValue {
  811. const fields = allocator.alloc(HlField, rcpt.len) catch return api.makeNull();
  812. var built: usize = 0;
  813. for (rcpt, 0..) |r, i| {
  814. var key_buf: [24]u8 = undefined;
  815. const key_src = std.fmt.bufPrint(&key_buf, "{d}", .{i}) catch break;
  816. const key = allocator.dupe(u8, key_src) catch break;
  817. fields[built] = .{ .key = .{ .ptr = key.ptr, .len = key.len }, .value = api.makeString(r) };
  818. built += 1;
  819. }
  820. const obj = allocator.create(HlObject) catch return api.makeNull();
  821. obj.* = .{ .fields = fields.ptr, .field_count = built, .deinit_fn = &rcptObjDeinit };
  822. return api.makeObject(obj);
  823. }
  824. fn resultValue(r: Result) HlValue {
  825. const fields = allocator.alloc(HlField, 7) catch return api.makeNull();
  826. fields[0] = .{ .key = http.hlStr("id"), .value = api.makeNumber(@floatFromInt(r.id)) };
  827. fields[1] = .{ .key = http.hlStr("ok"), .value = api.makeBool(r.ok) };
  828. fields[2] = .{ .key = http.hlStr("code"), .value = api.makeNumber(@floatFromInt(r.code)) };
  829. // `stage` names a compile-time constant, so it is DUPED here: the deinit
  830. // below frees every string field it finds, and handing it a `.rodata`
  831. // pointer is a segfault (measured, mission 137). One rule for all fields
  832. // beats a per-field exception nobody will remember.
  833. fields[3] = .{ .key = http.hlStr("stage"), .value = api.makeString(own(r.stage)) };
  834. fields[4] = .{ .key = http.hlStr("message"), .value = api.makeString(r.message) };
  835. fields[5] = .{ .key = http.hlStr("secure"), .value = api.makeBool(r.secure) };
  836. fields[6] = .{ .key = http.hlStr("to"), .value = rcptValue(r.rcpt) };
  837. const obj = allocator.create(HlObject) catch return api.makeNull();
  838. obj.* = .{ .fields = fields.ptr, .field_count = 7, .deinit_fn = &resultObjDeinit };
  839. allocator.free(r.rcpt);
  840. return api.makeObject(obj);
  841. }
  842. fn resultsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  843. const m: *Mailer = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  844. const r = m.tryTake() orelse return api.makeNull();
  845. return resultValue(r);
  846. }
  847. fn resultsNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  848. const m: *Mailer = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  849. const r = m.take() orelse return api.makeNull();
  850. return resultValue(r);
  851. }
  852. fn resultsDeinit(_: ?*anyopaque) callconv(.c) void {}
  853. // ── EXPORTS ─────────────────────────────────────────────────────────────────
  854. /// __native("smtp.open", host, port, options) → Number mailer id
  855. export fn hl_smtp_open(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  856. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_number) {
  857. return refuse("hl:smtp open: host must be a String and port a Number", .{});
  858. }
  859. const host = argv[0].data.string.ptr[0..argv[0].data.string.len];
  860. const port_f = argv[1].data.number;
  861. if (port_f < 1 or port_f > 65535) {
  862. return refuse("hl:smtp open: {d} is not a port number", .{port_f});
  863. }
  864. const opts: HlValue = if (argc >= 3) argv[2] else api.makeNull();
  865. const tls_name = strField(opts, "tls") orelse "starttls";
  866. const tls_mode: TlsMode = if (std.ascii.eqlIgnoreCase(tls_name, "starttls"))
  867. .starttls
  868. else if (std.ascii.eqlIgnoreCase(tls_name, "implicit"))
  869. .implicit
  870. else if (std.ascii.eqlIgnoreCase(tls_name, "none"))
  871. .none
  872. else
  873. return refuse("hl:smtp open: tls = \"{s}\" is not one of \"starttls\", \"implicit\", \"none\"", .{tls_name});
  874. const auth_name = strField(opts, "auth") orelse "auto";
  875. const auth_mode: AuthMode = if (std.ascii.eqlIgnoreCase(auth_name, "auto"))
  876. .auto
  877. else if (std.ascii.eqlIgnoreCase(auth_name, "plain"))
  878. .plain
  879. else if (std.ascii.eqlIgnoreCase(auth_name, "login"))
  880. .login
  881. else if (std.ascii.eqlIgnoreCase(auth_name, "none"))
  882. .none
  883. else
  884. return refuse("hl:smtp open: auth = \"{s}\" is not one of \"auto\", \"plain\", \"login\", \"none\"", .{auth_name});
  885. // A MAILER WITHOUT A SENDER OPENS (ticket #13): an app that never sends
  886. // must not abort at load for want of one. A message that ends up with no
  887. // sender at all is refused at send(), located at that call.
  888. const from = senderField(opts) orelse "";
  889. if (from.len > 0) {
  890. if (checkAddress("the mailer's \"from\" (or sender)", from)) |e| return e;
  891. }
  892. const helo = strField(opts, "helo") orelse "localhost";
  893. if (checkHeaderValue("helo", helo)) |e| return e;
  894. const m = allocator.create(Mailer) catch return refuse("hl:smtp open: out of memory", .{});
  895. m.* = .{
  896. .id = 0,
  897. .host = allocator.dupe(u8, host) catch return refuse("hl:smtp open: out of memory", .{}),
  898. .port = @intFromFloat(port_f),
  899. .user = dupOpt(strField(opts, "user")),
  900. .pass = dupOpt(strField(opts, "pass")),
  901. .from = allocator.dupe(u8, from) catch return refuse("hl:smtp open: out of memory", .{}),
  902. .helo = allocator.dupe(u8, helo) catch return refuse("hl:smtp open: out of memory", .{}),
  903. .tls_mode = tls_mode,
  904. .auth_mode = auth_mode,
  905. .ca_file = dupOpt(strField(opts, "caFile")),
  906. .verify = boolField(opts, "verify", true),
  907. .allow_insecure_auth = boolField(opts, "allowInsecureAuth", false),
  908. .timeout_ms = @intFromFloat(@max(1000, numField(opts, "timeout", 30000))),
  909. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  910. .condvar = c.PTHREAD_COND_INITIALIZER,
  911. .wake_fd = http.makeWakeFd(),
  912. };
  913. mutexLock(&mailers_mutex);
  914. m.id = next_mailer_id;
  915. next_mailer_id += 1;
  916. mailers.append(allocator, m) catch {};
  917. mutexUnlock(&mailers_mutex);
  918. m.worker = std.Thread.spawn(.{}, workerLoop, .{m}) catch {
  919. return refuse("hl:smtp open: could not start the sender thread", .{});
  920. };
  921. return api.makeNumber(@floatFromInt(m.id));
  922. }
  923. /// __native("smtp.send", id, message) → Number job id, or a located refusal.
  924. ///
  925. /// Everything this function does happens on the HYBRIEL thread, before the job
  926. /// exists: that is deliberate, because a refusal is only located if it is raised
  927. /// at the call site and a worker thread has no call site.
  928. export fn hl_smtp_send(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  929. if (argc < 2 or argv[0].type != .hl_number) {
  930. return refuse("hl:smtp send: expected a mailer id and a message", .{});
  931. }
  932. const m = mailerById(@intFromFloat(argv[0].data.number)) orelse
  933. return refuse("hl:smtp send: this Mailer is closed", .{});
  934. const msg = argv[1];
  935. if (msg.type != .hl_object) {
  936. return refuse("hl:smtp send: the message must be a hybrid with to, subject and text (or html)", .{});
  937. }
  938. const from = senderField(msg) orelse m.from;
  939. if (from.len == 0) {
  940. return refuse("hl:smtp refused the message: it has no \"from\" and neither has the mailer — give one in the message or in the Mailer's options", .{});
  941. }
  942. if (checkAddress("\"from\"", from)) |e| return e;
  943. // `to` is one address or a list of them. A single String is the common case
  944. // and a list is the same message with more RCPT TO lines — never several
  945. // messages, so every recipient sees the same To: header.
  946. var rcpt: std.ArrayListUnmanaged([]u8) = .empty;
  947. var rcpt_failed = false;
  948. defer if (rcpt_failed) {
  949. for (rcpt.items) |r| allocator.free(r);
  950. rcpt.deinit(allocator);
  951. };
  952. const to_field = fieldOf(msg, "to") orelse return refuse("hl:smtp send: the message has no 'to'", .{});
  953. switch (to_field.type) {
  954. .hl_string => {
  955. const one = to_field.data.string.ptr[0..to_field.data.string.len];
  956. if (checkAddress("to", one)) |e| {
  957. rcpt_failed = true;
  958. return e;
  959. }
  960. rcpt.append(allocator, allocator.dupe(u8, one) catch "") catch {};
  961. },
  962. .hl_object => {
  963. const list = to_field.data.object;
  964. for (list.fields[0..list.field_count]) |f| {
  965. if (f.value.type != .hl_string) continue;
  966. const one = f.value.data.string.ptr[0..f.value.data.string.len];
  967. if (checkAddress("to", one)) |e| {
  968. rcpt_failed = true;
  969. return e;
  970. }
  971. rcpt.append(allocator, allocator.dupe(u8, one) catch "") catch {};
  972. }
  973. },
  974. else => return refuse("hl:smtp send: 'to' must be a String or a list of Strings", .{}),
  975. }
  976. if (rcpt.items.len == 0) {
  977. rcpt_failed = true;
  978. return refuse("hl:smtp send: 'to' names no recipient", .{});
  979. }
  980. const subject = strField(msg, "subject") orelse "";
  981. if (checkHeaderValue("subject", subject)) |e| {
  982. rcpt_failed = true;
  983. return e;
  984. }
  985. const text = strField(msg, "text");
  986. const html = strField(msg, "html");
  987. if (text == null and html == null) {
  988. rcpt_failed = true;
  989. return refuse("hl:smtp send: the message has neither 'text' nor 'html'", .{});
  990. }
  991. var body: std.ArrayListUnmanaged(u8) = .empty;
  992. var body_failed = false;
  993. defer if (body_failed) body.deinit(allocator);
  994. renderMessage(&body, m, from, rcpt.items, subject, text, html) catch {
  995. body_failed = true;
  996. rcpt_failed = true;
  997. return refuse("hl:smtp send: out of memory rendering the message", .{});
  998. };
  999. mutexLock(&m.mutex);
  1000. const job_id = m.next_job;
  1001. m.next_job += 1;
  1002. mutexUnlock(&m.mutex);
  1003. m.enqueue(.{
  1004. .id = job_id,
  1005. .from = allocator.dupe(u8, from) catch "",
  1006. .rcpt = rcpt.toOwnedSlice(allocator) catch &[_][]u8{},
  1007. .data = body.toOwnedSlice(allocator) catch &[_]u8{},
  1008. });
  1009. return api.makeNumber(@floatFromInt(job_id));
  1010. }
  1011. fn renderMessage(
  1012. out: *std.ArrayListUnmanaged(u8),
  1013. m: *Mailer,
  1014. from: []const u8,
  1015. rcpt: []const []u8,
  1016. subject: []const u8,
  1017. text: ?[]const u8,
  1018. html: ?[]const u8,
  1019. ) !void {
  1020. var head: std.ArrayListUnmanaged(u8) = .empty;
  1021. defer head.deinit(allocator);
  1022. try appendHeader(&head, "From", from);
  1023. var to_join: std.ArrayListUnmanaged(u8) = .empty;
  1024. defer to_join.deinit(allocator);
  1025. for (rcpt, 0..) |r, i| {
  1026. if (i > 0) try to_join.appendSlice(allocator, ", ");
  1027. try to_join.appendSlice(allocator, r);
  1028. }
  1029. try appendHeader(&head, "To", to_join.items);
  1030. try appendHeader(&head, "Subject", subject);
  1031. try writeDate(&head);
  1032. var mid: [32]u8 = undefined;
  1033. randomHex(&mid);
  1034. try head.appendSlice(allocator, "Message-ID: <");
  1035. try head.appendSlice(allocator, &mid);
  1036. try head.append(allocator, '@');
  1037. try head.appendSlice(allocator, m.helo);
  1038. try head.appendSlice(allocator, ">\r\n");
  1039. try head.appendSlice(allocator, "MIME-Version: 1.0\r\n");
  1040. if (text != null and html != null) {
  1041. var boundary: [24]u8 = undefined;
  1042. randomHex(&boundary);
  1043. try head.appendSlice(allocator, "Content-Type: multipart/alternative; boundary=\"hl-");
  1044. try head.appendSlice(allocator, &boundary);
  1045. try head.appendSlice(allocator, "\"\r\n\r\n");
  1046. // The plain part first: RFC 2046 §5.1.4 orders alternatives worst-first,
  1047. // so a reader that understands HTML picks the LAST one it can render.
  1048. try head.appendSlice(allocator, "--hl-");
  1049. try head.appendSlice(allocator, &boundary);
  1050. try head.appendSlice(allocator, "\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n");
  1051. try out.appendSlice(allocator, head.items);
  1052. try appendDotStuffed(out, text.?);
  1053. try out.appendSlice(allocator, "--hl-");
  1054. try out.appendSlice(allocator, &boundary);
  1055. try out.appendSlice(allocator, "\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n");
  1056. try appendDotStuffed(out, html.?);
  1057. try out.appendSlice(allocator, "--hl-");
  1058. try out.appendSlice(allocator, &boundary);
  1059. try out.appendSlice(allocator, "--\r\n");
  1060. return;
  1061. }
  1062. const single = text orelse html.?;
  1063. const ctype = if (text != null) "text/plain" else "text/html";
  1064. try head.appendSlice(allocator, "Content-Type: ");
  1065. try head.appendSlice(allocator, ctype);
  1066. try head.appendSlice(allocator, "; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n");
  1067. try out.appendSlice(allocator, head.items);
  1068. try appendDotStuffed(out, single);
  1069. }
  1070. /// __native("smtp.results", id) → the mailer's ONE result source.
  1071. export fn hl_smtp_results(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1072. if (argc < 1 or argv[0].type != .hl_number) return api.makeNull();
  1073. const m = mailerById(@intFromFloat(argv[0].data.number)) orelse
  1074. return refuse("hl:smtp results: this Mailer is closed", .{});
  1075. if (m.source == null) {
  1076. const iter = allocator.create(HlIterator) catch return api.makeNull();
  1077. iter.* = .{
  1078. .context = @ptrCast(m),
  1079. .next_fn = &resultsNext,
  1080. .deinit_fn = &resultsDeinit,
  1081. .try_next_fn = &resultsTryNext,
  1082. .wake_fd = m.wake_fd,
  1083. };
  1084. m.source = iter;
  1085. }
  1086. return api.makeIterator(m.source.?);
  1087. }
  1088. /// __native("smtp.mark_registered", id) → refuses a SECOND consumer.
  1089. /// The drain (`for (r of m.results())`) and the event loop take results off the
  1090. /// same queue, so a program doing both would see each result exactly once, in
  1091. /// one of two places, at random. Saying so is cheaper than debugging it.
  1092. export fn hl_smtp_mark_registered(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1093. if (argc < 1 or argv[0].type != .hl_number) return api.makeNull();
  1094. const m = mailerById(@intFromFloat(argv[0].data.number)) orelse
  1095. return refuse("hl:smtp deliver: this Mailer is closed", .{});
  1096. if (m.registered) {
  1097. return refuse("hl:smtp deliver: this Mailer already delivers its results to the event loop", .{});
  1098. }
  1099. m.registered = true;
  1100. return api.makeNull();
  1101. }
  1102. /// __native("smtp.pending", id) → how many sends have not been answered yet.
  1103. export fn hl_smtp_pending(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1104. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  1105. const m = mailerById(@intFromFloat(argv[0].data.number)) orelse return api.makeNumber(0);
  1106. mutexLock(&m.mutex);
  1107. defer mutexUnlock(&m.mutex);
  1108. return api.makeNumber(@floatFromInt(m.outstanding));
  1109. }
  1110. /// __native("smtp.close", id) — stop the worker. Queued jobs still in hand are
  1111. /// dropped; a job already in conversation finishes, because abandoning a socket
  1112. /// between DATA and its 250 is how a message gets delivered twice.
  1113. export fn hl_smtp_close(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1114. if (argc < 1 or argv[0].type != .hl_number) return api.makeNull();
  1115. const m = mailerById(@intFromFloat(argv[0].data.number)) orelse return api.makeNull();
  1116. mutexLock(&m.mutex);
  1117. m.stop = true;
  1118. condBroadcast(&m.condvar);
  1119. mutexUnlock(&m.mutex);
  1120. http.ringWake(m.wake_fd);
  1121. if (m.worker) |t| {
  1122. t.join();
  1123. m.worker = null;
  1124. }
  1125. mutexLock(&mailers_mutex);
  1126. for (mailers.items, 0..) |candidate, i| {
  1127. if (candidate == m) {
  1128. _ = mailers.orderedRemove(i);
  1129. break;
  1130. }
  1131. }
  1132. mutexUnlock(&mailers_mutex);
  1133. return api.makeNull();
  1134. }
  1135. test "wake burst smtp results" {
  1136. const w = @import("wake_test");
  1137. var passed: usize = 0;
  1138. for (0..10) |_| {
  1139. var m: Mailer = undefined;
  1140. m.mutex = c.PTHREAD_MUTEX_INITIALIZER;
  1141. m.condvar = c.PTHREAD_COND_INITIALIZER;
  1142. m.results = .empty;
  1143. m.outstanding = 220;
  1144. m.wake_fd = w.bell();
  1145. defer _ = linux.close(m.wake_fd);
  1146. defer m.results.deinit(allocator);
  1147. for (0..220) |i| m.publish(.{ .id = @intCast(i), .ok = true, .code = 250,
  1148. .stage = "done", .message = try allocator.dupe(u8, "ok"), .secure = false, .rcpt = &.{} });
  1149. if (w.burst(m.wake_fd, &m, &resultsTryNext, 220)) passed += 1;
  1150. }
  1151. try w.result("smtp results", passed);
  1152. try w.require(&.{passed});
  1153. }

Branches

Latest commits

  • b3d8a80bDP69 brief, RV48 mergedmre
  • ce6d7d32Merge rv48: Hybriel day48mre
  • 3da2ea86RV48: report day48 cold starts, gates and cleanupmre
  • 8d9ecdfeRV48: re-vendor Hybriel set day48 (source b6a8f429, bin 660a9524)mre
  • 4a802ae7status: RV48 runningmre
  • 0a5412b6RV48 brief, day48 outmre
  • 56665efelog: CB69 mergedmre
  • 05448a98Merge cb69-imports: appTitle in a dependency-free topicmre
  • e55b379dKeep shared app title independent of the route import graphmre
  • 9a99659blog: hybriel#334, batch waits for day48mre
  • 85fa6c9blog: CB68 result, CB69 startedmre
  • 2f07c1b7log: DP68 boot gate failed, CB68mre
  • 9652782dlog: HM59 merged, DP68 startedmre
  • 29867a75Merge hm59-logic: tracker#59 page logic moved to libmre
  • f7bfe90bMove remaining page builders into their topicsmre
  • 7c3991f9log: day46 from Antonmre
  • ec54fc35Move show page logic into the shows topicmre
  • c1a8d074log: correct timesmre
  • 5827eba9log: HM57 merged, HM59 startedmre
  • d1a91be9Merge hm57-let: tracker#57 let only for reassigned namesmre