Removed an unused parameter from CtdlSubmitMsg(). Why was it even there?
[citadel.git] / citadel / modules / smtp / serv_smtpclient.c
1 /*
2  * Transmit outbound SMTP mail to the big wide world of the Internet
3  *
4  * This is the new, exciting, clever version that makes libcurl do all the work  :)
5  *
6  * Copyright (c) 1997-2020 by the citadel.org team
7  *
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.
12  *
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.
17  */
18
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <stdio.h>
22 #include <sysconfig.h>
23
24 #if TIME_WITH_SYS_TIME
25 #include <sys/time.h>
26 #include <time.h>
27 #else
28 #if HAVE_SYS_TIME_H
29 #include <sys/time.h>
30 #else
31 #include <time.h>
32 #endif
33 #endif
34
35 #include <ctype.h>
36 #include <string.h>
37 #include <errno.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <libcitadel.h>
41 #include <curl/curl.h>
42 #include "citadel.h"
43 #include "server.h"
44 #include "citserver.h"
45 #include "support.h"
46 #include "config.h"
47 #include "ctdl_module.h"
48 #include "clientsocket.h"
49 #include "msgbase.h"
50 #include "domain.h"
51 #include "internet_addressing.h"
52 #include "citadel_dirs.h"
53 #include "modules/smtp/smtp_util.h"
54
55 struct smtpmsgsrc {             // Data passed in and out of libcurl for message upload
56         StrBuf *TheMessage;
57         int bytes_total;
58         int bytes_sent;
59 };
60
61 static int doing_smtpclient = 0;
62 long *smtpq = NULL;             // array of msgnums containing queue instructions
63 int smtpq_count = 0;            // number of queue messages in smtpq
64 int smtpq_alloc = 0;            // current allocation size for smtpq
65
66
67 /*
68  * Initialize the SMTP outbound queue
69  */
70 void smtp_init_spoolout(void)
71 {
72         struct ctdlroom qrbuf;
73
74         /*
75          * Create the room.  This will silently fail if the room already
76          * exists, and that's perfectly ok, because we want it to exist.
77          */
78         CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
79
80         /*
81          * Make sure it's set to be a "system room" so it doesn't show up
82          * in the <K>nown rooms list for administrators.
83          */
84         if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
85                 qrbuf.QRflags2 |= QR2_SYSTEM;
86                 CtdlPutRoomLock(&qrbuf);
87         }
88 }
89
90
91 /* For internet mail, generate delivery instructions.
92  * Yes, this is recursive.  Deal with it.  Infinite recursion does
93  * not happen because the delivery instructions message does not
94  * contain a recipient.
95  */
96 int smtp_aftersave(struct CtdlMessage *msg, recptypes * recps)
97 {
98         if ((recps != NULL) && (recps->num_internet > 0)) {
99                 struct CtdlMessage *imsg = NULL;
100                 char recipient[SIZ];
101                 StrBuf *SpoolMsg = NewStrBuf();
102                 long nTokens;
103                 int i;
104
105                 syslog(LOG_DEBUG, "smtpclient: generating delivery instructions");
106
107                 StrBufPrintf(SpoolMsg,
108                              "Content-type: " SPOOLMIME "\n"
109                              "\n"
110                              "msgid|%s\n"
111                              "submitted|%ld\n" "bounceto|%s\n", msg->cm_fields[eVltMsgNum], (long) time(NULL), recps->bounce_to);
112
113                 if (recps->envelope_from != NULL) {
114                         StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
115                         StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
116                         StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
117                 }
118                 if (recps->sending_room != NULL) {
119                         StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
120                         StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
121                         StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
122                 }
123
124                 nTokens = num_tokens(recps->recp_internet, '|');
125                 for (i = 0; i < nTokens; i++) {
126                         long len;
127                         len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
128                         if (len > 0) {
129                                 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
130                                 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
131                                 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
132                         }
133                 }
134
135                 imsg = malloc(sizeof(struct CtdlMessage));
136                 memset(imsg, 0, sizeof(struct CtdlMessage));
137                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
138                 imsg->cm_anon_type = MES_NORMAL;
139                 imsg->cm_format_type = FMT_RFC822;
140                 CM_SetField(imsg, eMsgSubject, HKEY("QMSG"));
141                 CM_SetField(imsg, eAuthor, HKEY("Citadel"));
142                 CM_SetField(imsg, eJournal, HKEY("do not journal"));
143                 CM_SetAsFieldSB(imsg, eMesageText, &SpoolMsg);
144                 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
145                 CM_Free(imsg);
146         }
147         return 0;
148 }
149
150
151 /*
152  * Callback for smtp_attempt_delivery() to supply libcurl with upload data.
153  */
154 static size_t upload_source(void *ptr, size_t size, size_t nmemb, void *userp)
155 {
156         struct smtpmsgsrc *s = (struct smtpmsgsrc *) userp;
157         int sendbytes = 0;
158         const char *send_this = NULL;
159
160         sendbytes = (size * nmemb);
161
162         if (s->bytes_sent >= s->bytes_total) {
163                 return (0);     // no data remaining; we are done
164         }
165
166         if (sendbytes > (s->bytes_total - s->bytes_sent)) {
167                 sendbytes = s->bytes_total - s->bytes_sent;     // can't send more than we have
168         }
169
170         send_this = ChrPtr(s->TheMessage);
171         send_this += s->bytes_sent;     // start where we last left off
172
173         memcpy(ptr, send_this, sendbytes);
174         s->bytes_sent += sendbytes;
175         return (sendbytes);     // return the number of bytes _actually_ copied
176 }
177
178
179 /*
180  * The libcurl API doesn't provide a way to capture the actual SMTP result message returned
181  * by the remote server.  This is an ugly way to extract it, by capturing debug data from
182  * the library and filtering on the lines we want.
183  */
184 int ctdl_libcurl_smtp_debug_callback(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr)
185 {
186         if (type != CURLINFO_HEADER_IN)
187                 return 0;
188         if (!userptr)
189                 return 0;
190         char *debugbuf = (char *) userptr;
191
192         int len = strlen(debugbuf);
193         if (len + size > SIZ)
194                 return 0;
195
196         memcpy(&debugbuf[len], data, size);
197         debugbuf[len + size] = 0;
198         return 0;
199 }
200
201
202 /*
203  * Go through the debug output of an SMTP transaction, and boil it down to just the final success or error response message.
204  */
205 void trim_response(long response_code, char *response)
206 {
207         if ((response_code < 100) || (response_code > 999) || (IsEmptyStr(response))) {
208                 return;
209         }
210
211         char *t = malloc(strlen(response));
212         if (!t) {
213                 return;
214         }
215         t[0] = 0;
216
217         char *p;
218         for (p = response; *p != 0; ++p) {
219                 if ( (*p != '\n') && (!isprint(*p)) ) {         // expunge any nonprintables except for newlines
220                         *p = ' ';
221                 }
222         }
223
224         char response_code_str[4];
225         snprintf(response_code_str, sizeof response_code_str, "%ld", response_code);
226         char *respstart = strstr(response, response_code_str);
227         if (respstart == NULL) {
228                 strcpy(response, smtpstatus(response_code));
229                 return;
230         }
231         strcpy(response, respstart);
232
233         p = strstr(response, "\n");
234         if (p != NULL) {
235                 *p = 0;
236         }
237 }
238
239
240 /*
241  * Attempt a delivery to one recipient.
242  * Returns a three-digit SMTP status code.
243  */
244 int smtp_attempt_delivery(long msgid, char *recp, char *envelope_from, char *response)
245 {
246         struct smtpmsgsrc s;
247         char *fromaddr = NULL;
248         CURL *curl;
249         CURLcode res = CURLE_OK;
250         struct curl_slist *recipients = NULL;
251         long response_code = 421;
252         int num_mx = 0;
253         char mxes[SIZ];
254         char user[1024];
255         char node[1024];
256         char name[1024];
257         char try_this_mx[256];
258         char smtp_url[512];
259         int i;
260
261         syslog(LOG_DEBUG, "smtpclient: smtp_attempt_delivery(%ld, %s)", msgid, recp);
262
263         process_rfc822_addr(recp, user, node, name);    // split recipient address into username, hostname, displayname
264         num_mx = getmx(mxes, node);
265         if (num_mx < 1) {
266                 return (421);
267         }
268
269         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
270         CtdlOutputMsg(msgid, MT_RFC822, HEADERS_ALL, 0, 1, NULL, 0, NULL, &fromaddr, NULL);
271         s.TheMessage = CC->redirect_buffer;
272         s.bytes_total = StrLength(CC->redirect_buffer);
273         s.bytes_sent = 0;
274         CC->redirect_buffer = NULL;
275         response_code = 421;
276
277         for (i = 0; ((i < num_mx) && ((response_code / 100) == 4)); ++i) {      // keep trying MXes until one works or we run out
278                 response_code = 421;    // default 421 makes non-protocol errors transient
279                 s.bytes_sent = 0;       // rewind our buffer in case we try multiple MXes
280
281                 curl = curl_easy_init();
282                 if (curl) {
283                         response[0] = 0;
284
285                         if (!IsEmptyStr(envelope_from)) {
286                                 curl_easy_setopt(curl, CURLOPT_MAIL_FROM, envelope_from);
287                         } else {
288                                 curl_easy_setopt(curl, CURLOPT_MAIL_FROM, fromaddr);
289                         }
290
291                         recipients = curl_slist_append(recipients, recp);
292                         curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
293                         curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_source);
294                         curl_easy_setopt(curl, CURLOPT_READDATA, &s);
295                         curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);      // tell libcurl we are uploading
296                         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L);   // Time out after 20 seconds
297                         if (CtdlGetConfigInt("c_smtpclient_disable_starttls") == 0) {
298                                 curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);        // Attempt STARTTLS if offered
299                         }
300                         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
301                         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
302                         curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, ctdl_libcurl_smtp_debug_callback);
303                         curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *) response);
304                         curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
305
306                         // Construct an SMTP URL in the form of:
307                         //      smtp[s]://target_host/source_host
308                         // This looks weird but libcurl uses that last part to set our name for EHLO or HELO.
309                         // We check for "smtp://" and "smtps://" because the admin may have put those prefixes in a smart-host entry.
310                         // If there is no prefix we add "smtp://"
311                         extract_token(try_this_mx, mxes, i, '|', (sizeof try_this_mx - 7));
312                         snprintf(smtp_url, sizeof smtp_url, "%s%s/%s", (((!strncasecmp(try_this_mx, HKEY("smtp://")))
313                                                                          ||
314                                                                          (!strncasecmp
315                                                                           (try_this_mx,
316                                                                            HKEY("smtps://")))) ? "" : "smtp://"),
317                                  try_this_mx, CtdlGetConfigStr("c_fqdn")
318                             );
319                         curl_easy_setopt(curl, CURLOPT_URL, smtp_url);
320                         syslog(LOG_DEBUG, "smtpclient: trying %s", smtp_url);   // send the message
321                         res = curl_easy_perform(curl);
322                         curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
323                         syslog(LOG_DEBUG,
324                                "smtpclient: libcurl returned %d (%s) , SMTP response %ld",
325                                res, curl_easy_strerror(res), response_code);
326
327                         if ((res != CURLE_OK) && (response_code == 0)) {        // check for errors
328                                 response_code = 421;
329                         }
330
331                         curl_slist_free_all(recipients);
332                         recipients = NULL;      // this gets reused; avoid double-free
333                         curl_easy_cleanup(curl);
334                         curl = NULL;    // this gets reused; avoid double-free
335
336                         /* Trim the error message buffer down to just the actual message */
337                         trim_response(response_code, response);
338                 }
339         }
340
341         FreeStrBuf(&s.TheMessage);
342         if (fromaddr)
343                 free(fromaddr);
344         return ((int) response_code);
345 }
346
347
348 /*
349  * Process one outbound message.
350  */
351 void smtp_process_one_msg(long qmsgnum)
352 {
353         struct CtdlMessage *msg = NULL;
354         char *instr = NULL;
355         int i;
356         int num_success = 0;
357         int num_fail = 0;
358         int num_delayed = 0;
359         long deletes[2];
360         int delete_this_queue = 0;
361         char server_response[SIZ];
362
363         msg = CtdlFetchMessage(qmsgnum, 1);
364         if (msg == NULL) {
365                 syslog(LOG_WARNING, "smtpclient: %ld does not exist", qmsgnum);
366                 return;
367         }
368
369         instr = msg->cm_fields[eMesageText];
370         msg->cm_fields[eMesageText] = NULL;
371         CM_Free(msg);
372
373         // if the queue message has any CRLF's convert them to LF's
374         char *crlf = NULL;
375         while (crlf = strstr(instr, "\r\n"), crlf != NULL) {
376                 strcpy(crlf, crlf + 1);
377         }
378
379         // Strip out the headers and we are now left with just the instructions.
380         char *soi = strstr(instr, "\n\n");
381         if (soi) {
382                 strcpy(instr, soi + 2);
383         }
384
385         long msgid = 0;
386         time_t submitted = time(NULL);
387         time_t attempted = 0;
388         char *bounceto = NULL;
389         char *envelope_from = NULL;
390
391         char cfgline[SIZ];
392         for (i = 0; i < num_tokens(instr, '\n'); ++i) {
393                 extract_token(cfgline, instr, i, '\n', sizeof cfgline);
394                 if (!strncasecmp(cfgline, HKEY("msgid|")))
395                         msgid = atol(&cfgline[6]);
396                 if (!strncasecmp(cfgline, HKEY("submitted|")))
397                         submitted = atol(&cfgline[10]);
398                 if (!strncasecmp(cfgline, HKEY("attempted|")))
399                         attempted = atol(&cfgline[10]);
400                 if (!strncasecmp(cfgline, HKEY("bounceto|")))
401                         bounceto = strdup(&cfgline[9]);
402                 if (!strncasecmp(cfgline, HKEY("envelope_from|")))
403                         envelope_from = strdup(&cfgline[14]);
404         }
405
406         int should_try_now = 0;
407         if (attempted < submitted) {    // If no attempts have been made yet, try now
408                 should_try_now = 1;
409         } else if ((attempted - submitted) <= 14400) {
410                 if ((time(NULL) - attempted) > 1800) {  // First four hours, retry every 30 minutes
411                         should_try_now = 1;
412                 }
413         } else {
414                 if ((time(NULL) - attempted) > 14400) { // After that, retry once every 4 hours
415                         should_try_now = 1;
416                 }
417         }
418
419         if (should_try_now) {
420                 syslog(LOG_DEBUG, "smtpclient: %ld attempting delivery now", qmsgnum);
421                 StrBuf *NewInstr = NewStrBuf();
422                 StrBufAppendPrintf(NewInstr, "Content-type: " SPOOLMIME "\n\n");
423                 StrBufAppendPrintf(NewInstr, "msgid|%ld\n", msgid);
424                 StrBufAppendPrintf(NewInstr, "submitted|%ld\n", submitted);
425                 if (bounceto)
426                         StrBufAppendPrintf(NewInstr, "bounceto|%s\n", bounceto);
427                 if (envelope_from)
428                         StrBufAppendPrintf(NewInstr, "envelope_from|%s\n", envelope_from);
429
430                 for (i = 0; i < num_tokens(instr, '\n'); ++i) {
431                         extract_token(cfgline, instr, i, '\n', sizeof cfgline);
432                         if (!strncasecmp(cfgline, HKEY("remote|"))) {
433                                 char recp[SIZ];
434                                 int previous_result = extract_int(cfgline, 2);
435                                 if ((previous_result == 0)
436                                     || (previous_result == 4)) {
437                                         int new_result = 421;
438                                         extract_token(recp, cfgline, 1, '|', sizeof recp);
439                                         new_result = smtp_attempt_delivery(msgid, recp, envelope_from, server_response);
440                                         syslog(LOG_DEBUG,
441                                                "smtpclient: recp: <%s> , result: %d (%s)", recp, new_result, server_response);
442                                         if ((new_result / 100) == 2) {
443                                                 ++num_success;
444                                         } else {
445                                                 if ((new_result / 100) == 5) {
446                                                         ++num_fail;
447                                                 } else {
448                                                         ++num_delayed;
449                                                 }
450                                                 StrBufAppendPrintf
451                                                     (NewInstr,
452                                                      "remote|%s|%ld|%ld (%s)\n",
453                                                      recp, (new_result / 100), new_result, server_response);
454                                         }
455                                 }
456                         }
457                 }
458
459                 StrBufAppendPrintf(NewInstr, "attempted|%ld\n", time(NULL));
460
461                 // All deliveries have now been attempted.  Now determine the disposition of this queue entry.
462
463                 time_t age = time(NULL) - submitted;
464                 syslog(LOG_DEBUG,
465                        "smtpclient: submission age: %ldd%ldh%ldm%lds",
466                        (age / 86400), ((age % 86400) / 3600), ((age % 3600) / 60), (age % 60));
467                 syslog(LOG_DEBUG, "smtpclient: num_success=%d , num_fail=%d , num_delayed=%d", num_success, num_fail, num_delayed);
468
469                 // If there are permanent fails on this attempt, deliver a bounce to the user.
470                 // The 5XX fails will be recorded in the rewritten queue, but they will be removed before the next attempt.
471                 if (num_fail > 0) {
472                         smtp_do_bounce(ChrPtr(NewInstr), SDB_BOUNCE_FATALS);
473                 }
474                 // If all deliveries have either succeeded or failed, we are finished with this queue entry.
475                 //
476                 if (num_delayed == 0) {
477                         delete_this_queue = 1;
478                 }
479                 // If it's been more than five days, give up and tell the sender that delivery failed
480                 //
481                 else if ((time(NULL) - submitted) > SMTP_DELIVER_FAIL) {
482                         smtp_do_bounce(ChrPtr(NewInstr), SDB_BOUNCE_ALL);
483                         delete_this_queue = 1;
484                 }
485                 // If it's been more than four hours but less than five days, warn the sender that delivery is delayed
486                 //
487                 else if (((attempted - submitted) < SMTP_DELIVER_WARN)
488                          && ((time(NULL) - submitted) >= SMTP_DELIVER_WARN)) {
489                         smtp_do_bounce(ChrPtr(NewInstr), SDB_WARN);
490                 }
491
492                 if (delete_this_queue) {
493                         syslog(LOG_DEBUG, "smtpclient: %ld deleting", qmsgnum);
494                         deletes[0] = qmsgnum;
495                         deletes[1] = msgid;
496                         CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, deletes, 2, "");
497                         FreeStrBuf(&NewInstr);  // We have to free NewInstr here, no longer needed
498                 } else {
499                         // replace the old queue entry with the new one
500                         syslog(LOG_DEBUG, "smtpclient: %ld rewriting", qmsgnum);
501                         msg = convert_internet_message_buf(&NewInstr);  // This function will free NewInstr for us
502                         CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM);
503                         CM_Free(msg);
504                         CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &qmsgnum, 1, "");
505                 }
506         } else {
507                 syslog(LOG_DEBUG, "smtpclient: %ld retry time not reached", qmsgnum);
508         }
509
510         if (bounceto != NULL)
511                 free(bounceto);
512         if (envelope_from != NULL)
513                 free(envelope_from);
514         free(instr);
515 }
516
517
518 /*
519  * Callback for smtp_do_queue()
520  */
521 void smtp_add_msg(long msgnum, void *userdata)
522 {
523
524         if (smtpq == NULL) {
525                 smtpq_count = 0;
526                 smtpq_alloc = 100;
527                 smtpq = malloc(smtpq_alloc * sizeof(long));
528         }
529
530         if (smtpq_alloc >= smtpq_count) {
531                 smtpq_alloc += 100;
532                 smtpq = realloc(smtpq, (smtpq_alloc * sizeof(long)));
533         }
534
535         smtpq[smtpq_count++] = msgnum;
536 }
537
538
539 /*
540  * Run through the queue sending out messages.
541  */
542 void smtp_do_queue(void)
543 {
544         int i = 0;
545
546         /*
547          * This is a simple concurrency check to make sure only one smtpclient
548          * run is done at a time.  We could do this with a mutex, but since we
549          * don't really require extremely fine granularity here, we'll do it
550          * with a static variable instead.
551          */
552         if (doing_smtpclient)
553                 return;
554         doing_smtpclient = 1;
555
556         syslog(LOG_DEBUG, "smtpclient: start queue run");
557
558         if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
559                 syslog(LOG_WARNING, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
560                 doing_smtpclient = 0;
561                 return;
562         }
563         // Put the queue in memory so we can close the db cursor
564         CtdlForEachMessage(MSGS_ALL, 0L, NULL, SPOOLMIME, NULL, smtp_add_msg, NULL);
565
566         // We are ready to run through the queue now.
567         for (i = 0; i < smtpq_count; ++i) {
568                 smtp_process_one_msg(smtpq[i]);
569         }
570
571         smtpq_count = 0;        // don't free it, we will use this memory on the next run
572         doing_smtpclient = 0;
573         syslog(LOG_DEBUG, "smtpclient: end queue run");
574 }
575
576
577 /*
578  * Module entry point
579  */
580 CTDL_MODULE_INIT(smtpclient)
581 {
582         if (!threading) {
583                 CtdlRegisterMessageHook(smtp_aftersave, EVT_AFTERSAVE);
584                 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER, PRIO_AGGR + 50);
585                 smtp_init_spoolout();
586         }
587
588         /* return our module id for the log */
589         return "smtpclient";
590 }