2 * Transmit outbound SMTP mail to the big wide world of the Internet
4 * This is the new, exciting, clever version that makes libcurl do all the work :)
6 * Copyright (c) 1997-2021 by the citadel.org team
8 * This program is open source software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License as published
10 * by the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
22 #include <sysconfig.h>
27 #include <sys/types.h>
29 #include <libcitadel.h>
30 #include <curl/curl.h>
33 #include "citserver.h"
36 #include "ctdl_module.h"
37 #include "clientsocket.h"
40 #include "internet_addressing.h"
41 #include "citadel_dirs.h"
42 #include "modules/smtp/smtp_util.h"
44 struct smtpmsgsrc { // Data passed in and out of libcurl for message upload
50 static int doing_smtpclient = 0;
51 long *smtpq = NULL; // array of msgnums containing queue instructions
52 int smtpq_count = 0; // number of queue messages in smtpq
53 int smtpq_alloc = 0; // current allocation size for smtpq
57 * Initialize the SMTP outbound queue
59 void smtp_init_spoolout(void) {
60 struct ctdlroom qrbuf;
63 * Create the room. This will silently fail if the room already
64 * exists, and that's perfectly ok, because we want it to exist.
66 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
69 * Make sure it's set to be a "system room" so it doesn't show up
70 * in the <K>nown rooms list for administrators.
72 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
73 qrbuf.QRflags2 |= QR2_SYSTEM;
74 CtdlPutRoomLock(&qrbuf);
79 /* For internet mail, generate delivery instructions.
80 * Yes, this is recursive. Deal with it. Infinite recursion does
81 * not happen because the delivery instructions message does not
82 * contain a recipient.
84 int smtp_aftersave(struct CtdlMessage *msg, struct recptypes *recps) {
85 if ((recps != NULL) && (recps->num_internet > 0)) {
86 struct CtdlMessage *imsg = NULL;
88 StrBuf *SpoolMsg = NewStrBuf();
92 syslog(LOG_DEBUG, "smtpclient: generating delivery instructions");
94 StrBufPrintf(SpoolMsg,
95 "Content-type: " SPOOLMIME "\n"
98 "submitted|%ld\n" "bounceto|%s\n", msg->cm_fields[eVltMsgNum], (long) time(NULL), recps->bounce_to);
100 if (recps->envelope_from != NULL) {
101 StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
102 StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
103 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
105 if (recps->sending_room != NULL) {
106 StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
107 StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
108 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
111 nTokens = num_tokens(recps->recp_internet, '|');
112 for (i = 0; i < nTokens; i++) {
114 len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
116 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
117 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
118 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
122 imsg = malloc(sizeof(struct CtdlMessage));
123 memset(imsg, 0, sizeof(struct CtdlMessage));
124 imsg->cm_magic = CTDLMESSAGE_MAGIC;
125 imsg->cm_anon_type = MES_NORMAL;
126 imsg->cm_format_type = FMT_RFC822;
127 CM_SetField(imsg, eMsgSubject, HKEY("QMSG"));
128 CM_SetField(imsg, eAuthor, HKEY("Citadel"));
129 CM_SetField(imsg, eJournal, HKEY("do not journal"));
130 CM_SetAsFieldSB(imsg, eMesageText, &SpoolMsg);
131 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
139 * Callback for smtp_attempt_delivery() to supply libcurl with upload data.
141 static size_t upload_source(void *ptr, size_t size, size_t nmemb, void *userp) {
142 struct smtpmsgsrc *s = (struct smtpmsgsrc *) userp;
144 const char *send_this = NULL;
146 sendbytes = (size * nmemb);
148 if (s->bytes_sent >= s->bytes_total) {
149 return (0); // no data remaining; we are done
152 if (sendbytes > (s->bytes_total - s->bytes_sent)) {
153 sendbytes = s->bytes_total - s->bytes_sent; // can't send more than we have
156 send_this = ChrPtr(s->TheMessage);
157 send_this += s->bytes_sent; // start where we last left off
159 memcpy(ptr, send_this, sendbytes);
160 s->bytes_sent += sendbytes;
161 return (sendbytes); // return the number of bytes _actually_ copied
166 * The libcurl API doesn't provide a way to capture the actual SMTP result message returned
167 * by the remote server. This is an ugly way to extract it, by capturing debug data from
168 * the library and filtering on the lines we want.
170 int ctdl_libcurl_smtp_debug_callback(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) {
171 if (type != CURLINFO_HEADER_IN)
175 char *debugbuf = (char *) userptr;
177 int len = strlen(debugbuf);
178 if (len + size > SIZ)
181 memcpy(&debugbuf[len], data, size);
182 debugbuf[len + size] = 0;
188 * Go through the debug output of an SMTP transaction, and boil it down to just the final success or error response message.
190 void trim_response(long response_code, char *response) {
191 if ((response_code < 100) || (response_code > 999) || (IsEmptyStr(response))) {
195 char *t = malloc(strlen(response));
202 for (p = response; *p != 0; ++p) {
203 if ( (*p != '\n') && (!isprint(*p)) ) { // expunge any nonprintables except for newlines
208 char response_code_str[4];
209 snprintf(response_code_str, sizeof response_code_str, "%ld", response_code);
210 char *respstart = strstr(response, response_code_str);
211 if (respstart == NULL) { // If we have a response code but no response text,
212 strcpy(response, smtpstatus(response_code)); // use one of our canned messages.
215 strcpy(response, respstart);
217 p = strstr(response, "\n");
225 * Attempt a delivery to one recipient.
226 * Returns a three-digit SMTP status code.
228 int smtp_attempt_delivery(long msgid, char *recp, char *envelope_from, char *response) {
230 char *fromaddr = NULL;
232 CURLcode res = CURLE_OK;
233 struct curl_slist *recipients = NULL;
234 long response_code = 421;
240 char try_this_mx[256];
244 syslog(LOG_DEBUG, "smtpclient: smtp_attempt_delivery(%ld, %s)", msgid, recp);
246 process_rfc822_addr(recp, user, node, name); // split recipient address into username, hostname, displayname
247 num_mx = getmx(mxes, node);
252 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
253 CtdlOutputMsg(msgid, MT_RFC822, HEADERS_ALL, 0, 1, NULL, 0, NULL, &fromaddr, NULL);
254 s.TheMessage = CC->redirect_buffer;
255 s.bytes_total = StrLength(CC->redirect_buffer);
257 CC->redirect_buffer = NULL;
260 for (i = 0; ((i < num_mx) && ((response_code / 100) == 4)); ++i) { // keep trying MXes until one works or we run out
261 response_code = 421; // default 421 makes non-protocol errors transient
262 s.bytes_sent = 0; // rewind our buffer in case we try multiple MXes
264 curl = curl_easy_init();
268 if (!IsEmptyStr(envelope_from)) {
269 curl_easy_setopt(curl, CURLOPT_MAIL_FROM, envelope_from);
271 curl_easy_setopt(curl, CURLOPT_MAIL_FROM, fromaddr);
274 recipients = curl_slist_append(recipients, recp);
275 curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
276 curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_source);
277 curl_easy_setopt(curl, CURLOPT_READDATA, &s);
278 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1); // tell libcurl we are uploading
279 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L); // Time out after 20 seconds
280 if (CtdlGetConfigInt("c_smtpclient_disable_starttls") == 0) {
281 curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY); // Attempt STARTTLS if offered
283 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
284 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
285 curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, ctdl_libcurl_smtp_debug_callback);
286 curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *) response);
287 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
289 // Construct an SMTP URL in the form of:
290 // smtp[s]://target_host/source_host
291 // This looks weird but libcurl uses that last part to set our name for EHLO or HELO.
292 // We check for "smtp://" and "smtps://" because the admin may have put those prefixes in a smart-host entry.
293 // If there is no prefix we add "smtp://"
294 extract_token(try_this_mx, mxes, i, '|', (sizeof try_this_mx - 7));
295 snprintf(smtp_url, sizeof smtp_url, "%s%s/%s", (((!strncasecmp(try_this_mx, HKEY("smtp://")))
299 HKEY("smtps://")))) ? "" : "smtp://"),
300 try_this_mx, CtdlGetConfigStr("c_fqdn")
302 curl_easy_setopt(curl, CURLOPT_URL, smtp_url);
303 syslog(LOG_DEBUG, "smtpclient: trying MX %d of %d <%s>", i+1, num_mx, smtp_url); // send the message
304 res = curl_easy_perform(curl);
305 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
307 "smtpclient: libcurl returned %d (%s) , SMTP response %ld",
308 res, curl_easy_strerror(res), response_code);
310 if ((res != CURLE_OK) && (response_code == 0)) { // check for errors
314 curl_slist_free_all(recipients);
315 recipients = NULL; // this gets reused; avoid double-free
316 curl_easy_cleanup(curl);
317 curl = NULL; // this gets reused; avoid double-free
319 /* Trim the error message buffer down to just the actual message */
320 trim_response(response_code, response);
324 FreeStrBuf(&s.TheMessage);
327 return ((int) response_code);
332 * Process one outbound message.
334 void smtp_process_one_msg(long qmsgnum) {
335 struct CtdlMessage *msg = NULL;
342 int delete_this_queue = 0;
343 char server_response[SIZ];
345 msg = CtdlFetchMessage(qmsgnum, 1);
347 syslog(LOG_WARNING, "smtpclient: %ld does not exist", qmsgnum);
351 instr = msg->cm_fields[eMesageText];
352 msg->cm_fields[eMesageText] = NULL;
355 // if the queue message has any CRLF's convert them to LF's
357 while (crlf = strstr(instr, "\r\n"), crlf != NULL) {
358 strcpy(crlf, crlf + 1);
361 // Strip out the headers and we are now left with just the instructions.
362 char *soi = strstr(instr, "\n\n");
364 strcpy(instr, soi + 2);
368 time_t submitted = time(NULL);
369 time_t attempted = 0;
370 char *bounceto = NULL;
371 char *envelope_from = NULL;
374 for (i = 0; i < num_tokens(instr, '\n'); ++i) {
375 extract_token(cfgline, instr, i, '\n', sizeof cfgline);
376 if (!strncasecmp(cfgline, HKEY("msgid|")))
377 msgid = atol(&cfgline[6]);
378 if (!strncasecmp(cfgline, HKEY("submitted|")))
379 submitted = atol(&cfgline[10]);
380 if (!strncasecmp(cfgline, HKEY("attempted|")))
381 attempted = atol(&cfgline[10]);
382 if (!strncasecmp(cfgline, HKEY("bounceto|")))
383 bounceto = strdup(&cfgline[9]);
384 if (!strncasecmp(cfgline, HKEY("envelope_from|")))
385 envelope_from = strdup(&cfgline[14]);
388 int should_try_now = 0;
389 if (attempted < submitted) { // If no attempts have been made yet, try now
391 } else if ((attempted - submitted) <= 14400) {
392 if ((time(NULL) - attempted) > 1800) { // First four hours, retry every 30 minutes
396 if ((time(NULL) - attempted) > 14400) { // After that, retry once every 4 hours
401 if (should_try_now) {
402 syslog(LOG_DEBUG, "smtpclient: attempting delivery of message <%ld> now", qmsgnum);
403 StrBuf *NewInstr = NewStrBuf();
404 StrBufAppendPrintf(NewInstr, "Content-type: " SPOOLMIME "\n\n");
405 StrBufAppendPrintf(NewInstr, "msgid|%ld\n", msgid);
406 StrBufAppendPrintf(NewInstr, "submitted|%ld\n", submitted);
408 StrBufAppendPrintf(NewInstr, "bounceto|%s\n", bounceto);
410 StrBufAppendPrintf(NewInstr, "envelope_from|%s\n", envelope_from);
412 for (i = 0; i < num_tokens(instr, '\n'); ++i) {
413 extract_token(cfgline, instr, i, '\n', sizeof cfgline);
414 if (!strncasecmp(cfgline, HKEY("remote|"))) {
416 int previous_result = extract_int(cfgline, 2);
417 if ((previous_result == 0)
418 || (previous_result == 4)) {
419 int new_result = 421;
420 extract_token(recp, cfgline, 1, '|', sizeof recp);
421 new_result = smtp_attempt_delivery(msgid, recp, envelope_from, server_response);
423 "smtpclient: recp: <%s> , result: %d (%s)", recp, new_result, server_response);
424 if ((new_result / 100) == 2) {
427 if ((new_result / 100) == 5) {
434 "remote|%s|%ld|%ld (%s)\n",
435 recp, (new_result / 100), new_result, server_response);
441 StrBufAppendPrintf(NewInstr, "attempted|%ld\n", time(NULL));
443 // All deliveries have now been attempted. Now determine the disposition of this queue entry.
445 time_t age = time(NULL) - submitted;
447 "smtpclient: submission age: %ldd%ldh%ldm%lds",
448 (age / 86400), ((age % 86400) / 3600), ((age % 3600) / 60), (age % 60));
449 syslog(LOG_DEBUG, "smtpclient: num_success=%d , num_fail=%d , num_delayed=%d", num_success, num_fail, num_delayed);
451 // If there are permanent fails on this attempt, deliver a bounce to the user.
452 // The 5XX fails will be recorded in the rewritten queue, but they will be removed before the next attempt.
454 smtp_do_bounce(ChrPtr(NewInstr), SDB_BOUNCE_FATALS);
456 // If all deliveries have either succeeded or failed, we are finished with this queue entry.
458 if (num_delayed == 0) {
459 delete_this_queue = 1;
461 // If it's been more than five days, give up and tell the sender that delivery failed
463 else if ((time(NULL) - submitted) > SMTP_DELIVER_FAIL) {
464 smtp_do_bounce(ChrPtr(NewInstr), SDB_BOUNCE_ALL);
465 delete_this_queue = 1;
467 // If it's been more than four hours but less than five days, warn the sender that delivery is delayed
469 else if (((attempted - submitted) < SMTP_DELIVER_WARN)
470 && ((time(NULL) - submitted) >= SMTP_DELIVER_WARN)) {
471 smtp_do_bounce(ChrPtr(NewInstr), SDB_WARN);
474 if (delete_this_queue) {
475 syslog(LOG_DEBUG, "smtpclient: %ld deleting", qmsgnum);
476 deletes[0] = qmsgnum;
478 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, deletes, 2, "");
479 FreeStrBuf(&NewInstr); // We have to free NewInstr here, no longer needed
481 // replace the old queue entry with the new one
482 syslog(LOG_DEBUG, "smtpclient: %ld rewriting", qmsgnum);
483 msg = convert_internet_message_buf(&NewInstr); // This function will free NewInstr for us
484 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
486 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &qmsgnum, 1, "");
489 syslog(LOG_DEBUG, "smtpclient: %ld retry time not reached", qmsgnum);
492 if (bounceto != NULL)
494 if (envelope_from != NULL)
501 * Callback for smtp_do_queue()
503 void smtp_add_msg(long msgnum, void *userdata) {
508 smtpq = malloc(smtpq_alloc * sizeof(long));
511 if (smtpq_alloc >= smtpq_count) {
513 smtpq = realloc(smtpq, (smtpq_alloc * sizeof(long)));
516 smtpq[smtpq_count++] = msgnum;
521 * Run through the queue sending out messages.
523 void smtp_do_queue(void) {
527 * This is a simple concurrency check to make sure only one smtpclient
528 * run is done at a time. We could do this with a mutex, but since we
529 * don't really require extremely fine granularity here, we'll do it
530 * with a static variable instead.
532 if (doing_smtpclient)
534 doing_smtpclient = 1;
536 syslog(LOG_DEBUG, "smtpclient: start queue run");
538 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
539 syslog(LOG_WARNING, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
540 doing_smtpclient = 0;
543 // Put the queue in memory so we can close the db cursor
544 CtdlForEachMessage(MSGS_ALL, 0L, NULL, SPOOLMIME, NULL, smtp_add_msg, NULL);
546 // We are ready to run through the queue now.
547 for (i = 0; i < smtpq_count; ++i) {
548 smtp_process_one_msg(smtpq[i]);
551 smtpq_count = 0; // don't free it, we will use this memory on the next run
552 doing_smtpclient = 0;
553 syslog(LOG_DEBUG, "smtpclient: end queue run");
560 CTDL_MODULE_INIT(smtpclient)
563 CtdlRegisterMessageHook(smtp_aftersave, EVT_AFTERSAVE);
564 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER, PRIO_AGGR + 51);
565 smtp_init_spoolout();
568 /* return our module id for the log */