4a4ac365bc639a63f2bf0f8abfc95a53d9886051
[citadel.git] / citadel / modules / smtp / smtp_util.c
1 /*
2  * Utility functions for the Citadel SMTP implementation
3  *
4  * Copyright (c) 1998-2017 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <termios.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <pwd.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <syslog.h>
26
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
29 # include <time.h>
30 #else
31 # if HAVE_SYS_TIME_H
32 #  include <sys/time.h>
33 # else
34 #  include <time.h>
35 # endif
36 #endif
37
38 #include <sys/wait.h>
39 #include <ctype.h>
40 #include <string.h>
41 #include <limits.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <libcitadel.h>
46 #include "citadel.h"
47 #include "server.h"
48 #include "citserver.h"
49 #include "support.h"
50 #include "config.h"
51 #include "control.h"
52 #include "user_ops.h"
53 #include "database.h"
54 #include "msgbase.h"
55 #include "internet_addressing.h"
56 #include "genstamp.h"
57 #include "domain.h"
58 #include "clientsocket.h"
59 #include "locate_host.h"
60 #include "citadel_dirs.h"
61 #include "ctdl_module.h"
62 #include "smtp_util.h"
63
64 const char *smtp_get_Recipients(void)
65 {
66         citsmtp *sSMTP = SMTP;
67
68         if (sSMTP == NULL)
69                 return NULL;
70         else return ChrPtr(sSMTP->from);
71 }
72
73
74 /*
75  * smtp_do_bounce() is caled by smtp_process_one_msg() to scan a set of delivery
76  * instructions for errors and produce/deliver a "bounce" message (delivery
77  * status notification).
78  *
79  * is_final should be set to:
80  *      SDB_BOUNCE_FATALS       Advise the sender of all 5XX (permanent failures)
81  *      SDB_BOUNCE_ALL          Advise the sender that all deliveries have failed and will not be retried
82  *      SDB_WARN                Warn the sender about all 4XX transient delays
83  */
84 void smtp_do_bounce(const char *instr, int is_final)
85 {
86         int i;
87         int lines;
88         int status;
89         char buf[1024];
90         char key[1024];
91         char addr[1024];
92         char dsn[1024];
93         char bounceto[1024];
94         StrBuf *boundary;
95         int num_bounces = 0;
96         int bounce_this = 0;
97         struct CtdlMessage *bmsg = NULL;
98         recptypes *valid;
99         int successful_bounce = 0;
100         static int seq = 0;
101         StrBuf *BounceMB;
102         long omsgid = (-1);
103
104         syslog(LOG_DEBUG, "smtp_do_bounce() called");
105         strcpy(bounceto, "");
106         boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
107
108         StrBufAppendPrintf(boundary, "%s_%04x%04x", CtdlGetConfigStr("c_fqdn"), getpid(), ++seq);
109
110
111         /* Start building our bounce message */
112
113         bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
114         if (bmsg == NULL) return;
115         memset(bmsg, 0, sizeof(struct CtdlMessage));
116         BounceMB = NewStrBufPlain(NULL, 1024);
117
118         bmsg->cm_magic = CTDLMESSAGE_MAGIC;
119         bmsg->cm_anon_type = MES_NORMAL;
120         bmsg->cm_format_type = FMT_RFC822;
121         CM_SetField(bmsg, eAuthor, HKEY("Citadel"));
122         CM_SetField(bmsg, eOriginalRoom, HKEY(MAILROOM));
123         CM_SetField(bmsg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
124         CM_SetField(bmsg, eMsgSubject, HKEY("Delivery Status Notification (Failure)"));
125         StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
126         StrBufAppendBuf(BounceMB, boundary, 0);
127         StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
128         StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
129         StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
130         StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
131         StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
132         StrBufAppendBuf(BounceMB, boundary, 0);
133         StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
134         StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
135
136         if (is_final == SDB_BOUNCE_ALL)
137         {
138                 StrBufAppendBufPlain(
139                         BounceMB,
140                         HKEY(   "A message you sent could not be delivered "
141                                 "to some or all of its recipients\ndue to "
142                                 "prolonged unavailability of its destination(s).\n"
143                                 "Giving up on the following addresses:\n\n"),
144                         0);
145         }
146         else if (is_final == SDB_BOUNCE_FATALS)
147         {
148                 StrBufAppendBufPlain(
149                         BounceMB,
150                         HKEY(   "A message you sent could not be delivered "
151                                 "to some or all of its recipients.\n"
152                                 "The following addresses were undeliverable:\n\n"),
153                         0);
154         }
155         else if (is_final == SDB_WARN)
156         {
157                 StrBufAppendBufPlain(
158                         BounceMB,
159                         HKEY("A message you sent has not been delivered "
160                                 "to some or all of its recipients.\n"
161                                 "Citadel will continue attempting delivery for five days.\n"
162                                 "The following addresses were undeliverable:\n\n"),
163                         0);
164         }
165         else    // should never get here
166         {
167                 StrBufAppendBufPlain(BounceMB, HKEY("This message should never occur.\n\n"), 0);
168         }
169
170         /*
171          * Now go through the instructions checking for stuff.
172          */
173         lines = num_tokens(instr, '\n');
174         for (i=0; i<lines; ++i) {
175                 long addrlen;
176                 long dsnlen;
177                 extract_token(buf, instr, i, '\n', sizeof buf);
178                 extract_token(key, buf, 0, '|', sizeof key);
179                 addrlen = extract_token(addr, buf, 1, '|', sizeof addr);
180                 status = extract_int(buf, 2);
181                 dsnlen = extract_token(dsn, buf, 3, '|', sizeof dsn);
182                 bounce_this = 0;
183
184                 syslog(LOG_DEBUG, "key=<%s> addr=<%s> status=%d dsn=<%s>", key, addr, status, dsn);
185
186                 if (!strcasecmp(key, "bounceto")) {
187                         strcpy(bounceto, addr);
188                 }
189
190                 if (!strcasecmp(key, "msgid")) {
191                         omsgid = atol(addr);
192                 }
193
194                 if (!strcasecmp(key, "remote")) {
195                         if ((is_final == SDB_BOUNCE_FATALS) && (status == 5)) bounce_this = 1;
196                         if ((is_final == SDB_BOUNCE_ALL) && (status != 2)) bounce_this = 1;
197                         if ((is_final == SDB_WARN) && (status == 4)) bounce_this = 1;
198                 }
199
200                 if (bounce_this) {
201                         ++num_bounces;
202                         StrBufAppendBufPlain(BounceMB, addr, addrlen, 0);
203                         StrBufAppendBufPlain(BounceMB, HKEY(": "), 0);
204                         StrBufAppendBufPlain(BounceMB, dsn, dsnlen, 0);
205                         StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
206                 }
207         }
208
209         /* Attach the original message */
210         if (omsgid >= 0) {
211                 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
212                 StrBufAppendBuf(BounceMB, boundary, 0);
213                 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
214                 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: message/rfc822\r\n"), 0);
215                 StrBufAppendBufPlain(BounceMB, HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
216                 StrBufAppendBufPlain(BounceMB, HKEY("Content-Disposition: inline\r\n"), 0);
217                 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
218
219                 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
220                 CtdlOutputMsg(omsgid,
221                         MT_RFC822,
222                         HEADERS_ALL,
223                         0, 1, NULL, 0,
224                         NULL, NULL, NULL
225                 );
226                 StrBufAppendBuf(BounceMB, CC->redirect_buffer, 0);
227                 FreeStrBuf(&CC->redirect_buffer);
228         }
229
230         /* Close the multipart MIME scope */
231         StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
232         StrBufAppendBuf(BounceMB, boundary, 0);
233         StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
234         CM_SetAsFieldSB(bmsg, eMesageText, &BounceMB);
235
236         /* Deliver the bounce if there's anything worth mentioning */
237         syslog(LOG_DEBUG, "num_bounces = %d", num_bounces);
238         if (num_bounces > 0) {
239
240                 /* First try the user who sent the message */
241                 if (IsEmptyStr(bounceto)) {
242                         syslog(LOG_ERR, "No bounce address specified");
243                 }
244                 else {
245                         syslog(LOG_DEBUG, "bounce to user <%s>", bounceto);
246                 }
247                 /* Can we deliver the bounce to the original sender? */
248                 valid = validate_recipients(bounceto, smtp_get_Recipients (), 0);
249                 if (valid != NULL) {
250                         if (valid->num_error == 0) {
251                                 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
252                                 successful_bounce = 1;
253                         }
254                 }
255
256                 /* If not, post it in the Aide> room */
257                 if (successful_bounce == 0) {
258                         CtdlSubmitMsg(bmsg, NULL, CtdlGetConfigStr("c_aideroom"), QP_EADDR);
259                 }
260
261                 /* Free up the memory we used */
262                 if (valid != NULL) {
263                         free_recipients(valid);
264                 }
265         }
266         FreeStrBuf(&boundary);
267         CM_Free(bmsg);
268         syslog(LOG_DEBUG, "Done processing bounces");
269 }
270
271
272
273
274
275 char *smtpcodes[][2] = {
276         { "211 - System status / system help reply" },
277         { "214", "Help message" },
278         { "220", "Domain service ready" },
279         { "221", "Domain service closing transmission channel" },
280         { "250", "Requested mail action completed and OK" },
281         { "251", "Not Local User, forward email to forward path" },
282         { "252", "Cannot Verify user, will attempt delivery later" },
283         { "253", "Pending messages for node started" },
284         { "354", "Start mail input; end with ." },
285         { "355", "Octet-offset is the transaction offset" },
286         { "421", "Domain service not available, closing transmission channel" },
287         { "432", "Domain service not available, closing transmission channel" },
288         { "450", "Requested mail action not taken: mailbox unavailable. request refused" },
289         { "451", "Requested action aborted: local error in processing Request is unable to be processed, try again" },
290         { "452", "Requested action not taken: insufficient system storage" },
291         { "453", "No mail" },
292         { "454", "TLS not available due to temporary reason. Encryption required for requested authentication mechanism" },
293         { "458", "Unable to queue messages for node" },
294         { "459", "Node not allowed: reason" },
295         { "500", "Syntax error, command unrecognized" },
296         { "501", "Syntax error in parameters or arguments" },
297         { "502", "Command not implemented" },
298         { "503", "Bad sequence of commands" },
299         { "504", "Command parameter not implemented" },
300         { "510", "Check the recipient address" },
301         { "512", "Domain can not be found. Unknown host." },
302         { "515", "Destination mailbox address invalid" },
303         { "517", "Problem with senders mail attribute, check properties" },
304         { "521", "Domain does not accept mail" },
305         { "522", "Recipient has exceeded mailbox limit" },
306         { "523", "Server limit exceeded. Message too large" },
307         { "530", "Access Denied. Authentication required" },
308         { "531", "Mail system Full" },
309         { "533", "Remote server has insufficient disk space to hold email" },
310         { "534", "Authentication mechanism is too weak. Message too big" },
311         { "535", "Multiple servers using same IP. Required Authentication" },
312         { "538", "Encryption required for requested authentication mechanism" },
313         { "540", "Email address has no DNS Server" },
314         { "541", "No response from host" },
315         { "542", "Bad Connection" },
316         { "543", "Routing server failure. No available route" },
317         { "546", "Email looping" },
318         { "547", "Delivery time-out" },
319         { "550", "Requested action not taken: mailbox unavailable or relaying denied" },
320         { "551", "User not local; please try forward path" },
321         { "552", "Requested mail action aborted: exceeded storage allocation" },
322         { "553", "Requested action not taken: mailbox name not allowed" },
323         { "554", "Transaction failed" }
324 };
325
326
327
328 char *smtpstatus(int code) {
329         int i;
330
331         for (i=0; i<(sizeof(smtpcodes)/sizeof(char *)/2); ++i) {
332                 if (atoi(smtpcodes[i][0]) == code) {
333                         return(smtpcodes[i][1]);
334                 }
335         }
336         
337         return("Unknown or other SMTP status");
338 }
339