]> code.citadel.org Git - citadel.git/blob - citadel/server/modules/smtp/serv_smtp.c
Remove preprocessor tests for OpenSSL. It's a requirement.
[citadel.git] / citadel / server / modules / smtp / serv_smtp.c
1 // This module is an SMTP and ESMTP server for the Citadel system.
2 // It is compliant with all of the following:
3 //
4 // RFC  821 - Simple Mail Transfer Protocol
5 // RFC  876 - Survey of SMTP Implementations
6 // RFC 1047 - Duplicate messages and SMTP
7 // RFC 1652 - 8 bit MIME
8 // RFC 1869 - Extended Simple Mail Transfer Protocol
9 // RFC 1870 - SMTP Service Extension for Message Size Declaration
10 // RFC 2033 - Local Mail Transfer Protocol
11 // RFC 2197 - SMTP Service Extension for Command Pipelining
12 // RFC 2476 - Message Submission
13 // RFC 2487 - SMTP Service Extension for Secure SMTP over TLS
14 // RFC 2554 - SMTP Service Extension for Authentication
15 // RFC 2821 - Simple Mail Transfer Protocol
16 // RFC 2822 - Internet Message Format
17 // RFC 2920 - SMTP Service Extension for Command Pipelining
18 //  
19 // The VRFY and EXPN commands have been removed from this implementation
20 // because nobody uses these commands anymore, except for spammers.
21 //
22 // Copyright (c) 1998-2023 by the citadel.org team
23 //
24 // This program is open source software; you can redistribute it and/or modify
25 // it under the terms of the GNU General Public License version 3.
26 //  
27 // This program is distributed in the hope that it will be useful,
28 // but WITHOUT ANY WARRANTY; without even the implied warranty of
29 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30 // GNU General Public License for more details.
31
32 #include "../../sysdep.h"
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <stdio.h>
36 #include <termios.h>
37 #include <fcntl.h>
38 #include <signal.h>
39 #include <pwd.h>
40 #include <errno.h>
41 #include <sys/types.h>
42 #include <syslog.h>
43 #include <time.h>
44 #include <sys/wait.h>
45 #include <ctype.h>
46 #include <string.h>
47 #include <limits.h>
48 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
51 #include <assert.h>
52 #include <libcitadel.h>
53 #include "../../citadel_defs.h"
54 #include "../../server.h"
55 #include "../../citserver.h"
56 #include "../../support.h"
57 #include "../../config.h"
58 #include "../../control.h"
59 #include "../../user_ops.h"
60 #include "../../room_ops.h"
61 #include "../../database.h"
62 #include "../../msgbase.h"
63 #include "../../internet_addressing.h"
64 #include "../../genstamp.h"
65 #include "../../domain.h"
66 #include "../../clientsocket.h"
67 #include "../../locate_host.h"
68 #include "../../citadel_dirs.h"
69 #include "../../ctdl_module.h"
70
71 #include "smtp_util.h"
72
73 enum {                          // Command states for login authentication
74         smtp_command,
75         smtp_user,
76         smtp_password,
77         smtp_plain
78 };
79
80 enum SMTP_FLAGS {
81         HELO,
82         EHLO,
83         LHLO
84 };
85
86
87 // Here's where our SMTP session begins its happy day.
88 void smtp_greeting(int is_msa) {
89         char message_to_spammer[1024];
90
91         strcpy(CC->cs_clientname, "SMTP session");
92         CC->internal_pgm = 1;
93         CC->cs_flags |= CS_STEALTH;
94         CC->session_specific_data = malloc(sizeof(struct citsmtp));
95         memset(SMTP, 0, sizeof(struct citsmtp));
96         SMTP->is_msa = is_msa;
97         SMTP->Cmd = NewStrBufPlain(NULL, SIZ);
98         SMTP->helo_node = NewStrBuf();
99         SMTP->from = NewStrBufPlain(NULL, SIZ);
100         SMTP->recipients = NewStrBufPlain(NULL, SIZ);
101         SMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
102         SMTP->preferred_sender_email = NULL;
103         SMTP->preferred_sender_name = NULL;
104
105         // If this config option is set, reject connections from problem
106         // addresses immediately instead of after they execute a RCPT
107         if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (SMTP->is_msa == 0) ) {
108                 if (rbl_check(CC->cs_addr, message_to_spammer)) {
109                         if (server_shutting_down)
110                                 cprintf("421 %s\r\n", message_to_spammer);
111                         else
112                                 cprintf("550 %s\r\n", message_to_spammer);
113                         CC->kill_me = KILLME_SPAMMER;
114                         // no need to free_recipients(valid), it's not allocated yet
115                         return;
116                 }
117         }
118
119         // Otherwise we're either clean or we check later.
120
121         if (CC->nologin==1) {
122                 cprintf("451 Too many connections are already open; please try again later.\r\n");
123                 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
124                 // no need to free_recipients(valid), it's not allocated yet
125                 return;
126         }
127
128         // Note: the FQDN *must* appear as the first thing after the 220 code.
129         // Some clients (including citmail.c) depend on it being there.
130         cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
131 }
132
133
134 // SMTPS is just like SMTP, except it goes crypto right away.
135 void smtps_greeting(void) {
136         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
137         if (!CC->redirect_ssl) {
138                 CC->kill_me = KILLME_NO_CRYPTO;         // kill session if no crypto
139         }
140         smtp_greeting(0);
141 }
142
143
144 // SMTP MSA port requires authentication.
145 void smtp_msa_greeting(void) {
146         smtp_greeting(1);
147 }
148
149
150 // LMTP is like SMTP but with some extra bonus footage added.
151 void lmtp_greeting(void) {
152
153         smtp_greeting(0);
154         SMTP->is_lmtp = 1;
155 }
156
157
158 // Generic SMTP MTA greeting
159 void smtp_mta_greeting(void) {
160         smtp_greeting(0);
161 }
162
163
164 // We also have an unfiltered LMTP socket that bypasses spam filters.
165 void lmtp_unfiltered_greeting(void) {
166         smtp_greeting(0);
167         SMTP->is_lmtp = 1;
168         SMTP->is_unfiltered = 1;
169 }
170
171
172 // Login greeting common to all auth methods
173 void smtp_auth_greeting(void) {
174         cprintf("235 Hello, %s\r\n", CC->user.fullname);
175         syslog(LOG_INFO, "serv_smtp: SMTP authenticated %s", CC->user.fullname);
176         CC->internal_pgm = 0;
177         CC->cs_flags &= ~CS_STEALTH;
178 }
179
180
181 // Implement HELO and EHLO commands.
182 // which_command:  0=HELO, 1=EHLO, 2=LHLO
183 void smtp_hello(int which_command) {
184
185         if (StrLength(SMTP->Cmd) >= 6) {
186                 FlushStrBuf(SMTP->helo_node);
187                 StrBufAppendBuf(SMTP->helo_node, SMTP->Cmd, 5);
188         }
189
190         if ( (which_command != LHLO) && (SMTP->is_lmtp) ) {
191                 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
192                 return;
193         }
194
195         if ( (which_command == LHLO) && (SMTP->is_lmtp == 0) ) {
196                 cprintf("500 LHLO is only allowed when running LMTP\r\n");
197                 return;
198         }
199
200         if (which_command == HELO) {
201                 cprintf("250 Hello %s (%s [%s])\r\n",
202                         ChrPtr(SMTP->helo_node),
203                         CC->cs_host,
204                         CC->cs_addr
205                 );
206         }
207         else {
208                 if (which_command == EHLO) {
209                         cprintf("250-Hello %s (%s [%s])\r\n", ChrPtr(SMTP->helo_node), CC->cs_host, CC->cs_addr);
210                 }
211                 else {
212                         cprintf("250-Greetings and joyous salutations.\r\n");
213                 }
214                 cprintf("250-HELP\r\n");
215                 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
216
217                 // Offer the STARTTLS option...
218                 if (    (!CC->redirect_ssl)                                                     // not if we're already TLS
219                         && (    (SMTP->is_msa)                                                  // Always on port 587
220                                 || (CtdlGetConfigInt("smtp_advertise_starttls") != 0)           // On port 25 only if enabled
221                         )
222                 ) {
223                         cprintf("250-STARTTLS\r\n");
224                 }
225
226                 cprintf("250-AUTH LOGIN PLAIN\r\n"
227                         "250-AUTH=LOGIN PLAIN\r\n"
228                         "250 8BITMIME\r\n"
229                 );
230         }
231 }
232
233
234 // Backend function for smtp_webcit_preferences_hack().
235 // Look at a message and determine if it's the preferences file.
236 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
237         struct CtdlMessage *msg;
238         char **webcit_conf = (char **) userdata;
239
240         if (*webcit_conf) {
241                 return;         // already got it
242         }
243
244         msg = CtdlFetchMessage(msgnum, 1);
245         if (msg == NULL) {
246                 return;
247         }
248
249         if ( !CM_IsEmpty(msg, eMsgSubject) && (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __"))) {
250                 // This is it!  Change ownership of the message text so it doesn't get freed.
251                 *webcit_conf = (char *)msg->cm_fields[eMessageText];
252                 msg->cm_fields[eMessageText] = NULL;
253         }
254         CM_Free(msg);
255 }
256
257
258 // The configuration item for the user's preferred display name for outgoing email is, unfortunately,
259 // stored in the account's WebCit configuration.  We have to fetch it now.
260 void smtp_webcit_preferences_hack(void) {
261         char config_roomname[ROOMNAMELEN];
262         char *webcit_conf = NULL;
263
264         snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CC->user.usernum, USERCONFIGROOM);
265         if (CtdlGetRoom(&CC->room, config_roomname) != 0) {
266                 return;
267         }
268
269         // Find the WebCit configuration message
270         CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
271
272         if (!webcit_conf) {
273                 return;
274         }
275
276         // Parse the webcit configuration and attempt to do something useful with it
277         char *str = webcit_conf;
278         char *saveptr = str;
279         char *this_line = NULL;
280         while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
281                 str = NULL;
282                 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
283                         SMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
284                 }
285                 if (!strncasecmp(this_line, "defaultname|", 12)) {
286                         SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
287                 }
288                 if ((!strncasecmp(this_line, "defaultname|", 12)) && (SMTP->preferred_sender_name == NULL)) {
289                         SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
290                 }
291
292         }
293         free(webcit_conf);
294 }
295
296
297 // Implement HELP command.
298 void smtp_help(void) {
299         cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
300 }
301
302
303 void smtp_get_user(int offset) {
304         char buf[SIZ];
305
306         StrBuf *UserName = NewStrBufDup(SMTP->Cmd);
307         StrBufCutLeft(UserName, offset);
308         StrBufDecodeBase64(UserName);
309
310         if (CtdlLoginExistingUser(ChrPtr(UserName)) == login_ok) {
311                 size_t len = CtdlEncodeBase64(buf, "Password:", 9, BASE64_NO_LINEBREAKS);
312
313                 if (buf[len - 1] == '\n') {
314                         buf[len - 1] = '\0';
315                 }
316                 cprintf("334 %s\r\n", buf);
317                 SMTP->command_state = smtp_password;
318         }
319         else {
320                 cprintf("500 No such user.\r\n");
321                 SMTP->command_state = smtp_command;
322         }
323         FreeStrBuf(&UserName);
324 }
325
326
327 void smtp_get_pass(void) {
328         char password[SIZ];
329
330         memset(password, 0, sizeof(password));
331         StrBufDecodeBase64(SMTP->Cmd);
332         syslog(LOG_DEBUG, "serv_smtp: trying <%s>", password);
333         if (CtdlTryPassword(SKEY(SMTP->Cmd)) == pass_ok) {
334                 smtp_auth_greeting();
335         }
336         else {
337                 cprintf("535 Authentication failed.\r\n");
338         }
339         SMTP->command_state = smtp_command;
340 }
341
342
343 // Back end for PLAIN auth method (either inline or multistate)
344 void smtp_try_plain(void) {
345         const char*decoded_authstring;
346         char ident[256] = "";
347         char user[256] = "";
348         char pass[256] = "";
349         int result;
350
351         long decoded_len;
352         long len = 0;
353         long plen = 0;
354
355         memset(pass, 0, sizeof(pass));
356         decoded_len = StrBufDecodeBase64(SMTP->Cmd);
357
358         if (decoded_len > 0) {
359                 decoded_authstring = ChrPtr(SMTP->Cmd);
360
361                 len = safestrncpy(ident, decoded_authstring, sizeof ident);
362
363                 decoded_len -= len - 1;
364                 decoded_authstring += len + 1;
365
366                 if (decoded_len > 0) {
367                         len = safestrncpy(user, decoded_authstring, sizeof user);
368
369                         decoded_authstring += len + 1;
370                         decoded_len -= len - 1;
371                 }
372
373                 if (decoded_len > 0) {
374                         plen = safestrncpy(pass, decoded_authstring, sizeof pass);
375
376                         if (plen < 0)
377                                 plen = sizeof(pass) - 1;
378                 }
379         }
380
381         SMTP->command_state = smtp_command;
382
383         if (!IsEmptyStr(ident)) {
384                 result = CtdlLoginExistingUser(ident);
385         }
386         else {
387                 result = CtdlLoginExistingUser(user);
388         }
389
390         if (result == login_ok) {
391                 if (CtdlTryPassword(pass, plen) == pass_ok) {
392                         smtp_webcit_preferences_hack();
393                         smtp_auth_greeting();
394                         return;
395                 }
396         }
397         cprintf("504 Authentication failed.\r\n");
398 }
399
400
401 // Attempt to perform authenticated SMTP
402 void smtp_auth(void) {
403         char username_prompt[64];
404         char method[64];
405         char encoded_authstring[1024];
406
407         if (CC->logged_in) {
408                 cprintf("504 Already logged in.\r\n");
409                 return;
410         }
411
412         if (StrLength(SMTP->Cmd) < 6) {
413                 cprintf("501 Syntax error\r\n");
414                 return;
415         }
416
417         extract_token(method, ChrPtr(SMTP->Cmd) + 5, 0, ' ', sizeof method);
418
419         if (!strncasecmp(method, "login", 5) ) {
420                 if (StrLength(SMTP->Cmd) >= 12) {
421                         syslog(LOG_DEBUG, "serv_smtp: username <%s> supplied inline", ChrPtr(SMTP->Cmd)+11);
422                         smtp_get_user(11);
423                 }
424                 else {
425                         size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, BASE64_NO_LINEBREAKS);
426                         if (username_prompt[len - 1] == '\n') {
427                                 username_prompt[len - 1] = '\0';
428                         }
429                         cprintf("334 %s\r\n", username_prompt);
430                         SMTP->command_state = smtp_user;
431                 }
432                 return;
433         }
434
435         if (!strncasecmp(method, "plain", 5) ) {
436                 long len;
437                 if (num_tokens(ChrPtr(SMTP->Cmd) + 5, ' ') < 2) {
438                         cprintf("334 \r\n");
439                         SMTP->command_state = smtp_plain;
440                         return;
441                 }
442
443                 len = extract_token(encoded_authstring, ChrPtr(SMTP->Cmd) + 5, 1, ' ', sizeof encoded_authstring);
444                 StrBufPlain(SMTP->Cmd, encoded_authstring, len);
445                 smtp_try_plain();
446                 return;
447         }
448
449         cprintf("504 Unknown authentication method.\r\n");
450         return;
451 }
452
453
454 // Implements the RSET (reset state) command.
455 // Currently this just zeroes out the state buffer.  If pointers to data
456 // allocated with malloc() are ever placed in the state buffer, we have to
457 // be sure to free() them first!
458 //
459 // Set do_response to nonzero to output the SMTP RSET response code.
460 void smtp_rset(int do_response) {
461         FlushStrBuf(SMTP->Cmd);
462         FlushStrBuf(SMTP->helo_node);
463         FlushStrBuf(SMTP->from);
464         FlushStrBuf(SMTP->recipients);
465         FlushStrBuf(SMTP->OneRcpt);
466
467         SMTP->command_state = 0;
468         SMTP->number_of_recipients = 0;
469         SMTP->delivery_mode = 0;
470         SMTP->message_originated_locally = 0;
471         SMTP->is_msa = 0;
472         // is_lmtp and is_unfiltered should not be cleared. 
473
474         if (do_response) {
475                 cprintf("250 Zap!\r\n");
476         }
477 }
478
479
480 // Clear out the portions of the state buffer that need to be cleared out
481 // after the DATA command finishes.
482 void smtp_data_clear(void) {
483         FlushStrBuf(SMTP->from);
484         FlushStrBuf(SMTP->recipients);
485         FlushStrBuf(SMTP->OneRcpt);
486         SMTP->number_of_recipients = 0;
487         SMTP->delivery_mode = 0;
488         SMTP->message_originated_locally = 0;
489 }
490
491
492 // Implements the "MAIL FROM:" command
493 void smtp_mail(void) {
494         char user[SIZ];
495         char node[SIZ];
496         char name[SIZ];
497
498         if (StrLength(SMTP->from) > 0) {
499                 cprintf("503 Only one sender permitted\r\n");
500                 return;
501         }
502
503         if (StrLength(SMTP->Cmd) < 6) {
504                 cprintf("501 Syntax error\r\n");
505                 return;
506         }
507
508         if (strncasecmp(ChrPtr(SMTP->Cmd) + 5, "From:", 5)) {
509                 cprintf("501 Syntax error\r\n");
510                 return;
511         }
512
513         StrBufAppendBuf(SMTP->from, SMTP->Cmd, 5);
514         StrBufTrim(SMTP->from);
515         if (strchr(ChrPtr(SMTP->from), '<') != NULL) {
516                 StrBufStripAllBut(SMTP->from, '<', '>');
517         }
518
519         // We used to reject empty sender names, until it was brought to our
520         // attention that RFC1123 5.2.9 requires that this be allowed.  So now
521         // we allow it, but replace the empty string with a fake
522         // address so we don't have to contend with the empty string causing
523         // other code to fail when it's expecting something there.
524         if (StrLength(SMTP->from) == 0) {
525                 StrBufPlain(SMTP->from, HKEY("someone@example.com"));
526         }
527
528         // If this SMTP connection is from a logged-in user, force the 'from'
529         // to be the user's Internet e-mail address as Citadel knows it.
530         if (CC->logged_in) {
531                 StrBufPlain(SMTP->from, CC->cs_inet_email, -1);
532                 cprintf("250 Sender ok <%s>\r\n", ChrPtr(SMTP->from));
533                 SMTP->message_originated_locally = 1;
534                 return;
535         }
536
537         else if (SMTP->is_lmtp) {
538                 // Bypass forgery checking for LMTP
539         }
540
541         // Otherwise, make sure outsiders aren't trying to forge mail from
542         // this system (unless, of course, c_allow_spoofing is enabled)
543         else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
544                 process_rfc822_addr(ChrPtr(SMTP->from), user, node, name);
545                 syslog(LOG_DEBUG, "serv_smtp: claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
546                         ChrPtr(SMTP->from), user, node, name
547                 );
548                 if (CtdlHostAlias(node) != hostalias_nomatch) {
549                         cprintf("550 You must log in to send mail from %s\r\n", node);
550                         FlushStrBuf(SMTP->from);
551                         syslog(LOG_DEBUG, "serv_smtp: rejecting unauthenticated mail from %s", node);
552                         return;
553                 }
554         }
555
556         cprintf("250 Sender ok\r\n");
557 }
558
559
560 // Implements the "RCPT To:" command
561 void smtp_rcpt(void) {
562         char message_to_spammer[SIZ];
563         struct recptypes *valid = NULL;
564
565         if (StrLength(SMTP->from) == 0) {
566                 cprintf("503 Need MAIL before RCPT\r\n");
567                 return;
568         }
569         
570         if (StrLength(SMTP->Cmd) < 6) {
571                 cprintf("501 Syntax error\r\n");
572                 return;
573         }
574
575         if (strncasecmp(ChrPtr(SMTP->Cmd) + 5, "To:", 3)) {
576                 cprintf("501 Syntax error\r\n");
577                 return;
578         }
579
580         if ( (SMTP->is_msa) && (!CC->logged_in) ) {
581                 cprintf("550 You must log in to send mail on this port.\r\n");
582                 FlushStrBuf(SMTP->from);
583                 return;
584         }
585
586         FlushStrBuf(SMTP->OneRcpt);
587         StrBufAppendBuf(SMTP->OneRcpt, SMTP->Cmd, 8);
588         StrBufTrim(SMTP->OneRcpt);
589         StrBufStripAllBut(SMTP->OneRcpt, '<', '>');
590
591         if ( (StrLength(SMTP->OneRcpt) + StrLength(SMTP->recipients)) >= SIZ) {
592                 cprintf("452 Too many recipients\r\n");
593                 return;
594         }
595
596         // RBL check
597         if (
598                 (!CC->logged_in)                                                // Don't RBL authenticated users
599                 && (!SMTP->is_lmtp)                                             // Don't RBL LMTP clients
600                 && (CtdlGetConfigInt("c_rbl_at_greeting") == 0)                 // Don't RBL if we did it at connection time
601                 && (rbl_check(CC->cs_addr, message_to_spammer))
602         ) {
603                 cprintf("550 %s\r\n", message_to_spammer);
604                 return;                                                         // no need to free_recipients(valid)
605         }                                                                       // because it hasn't been allocated yet
606
607         // This is a *preliminary* call to validate_recipients() to evaluate one recipient.
608         valid = validate_recipients(
609                 (char *)ChrPtr(SMTP->OneRcpt), 
610                 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
611         );
612
613         // Any type of error thrown by validate_recipients() will make the SMTP transaction fail at this point.
614         if (valid->num_error != 0) {
615                 cprintf("550 %s\r\n", valid->errormsg);
616                 free_recipients(valid);
617                 return;
618         }
619
620         if (
621                 (valid->num_internet > 0)                                       // If it's outbound Internet mail...
622                 && (CC->logged_in)                                              // ...and we're a logged-in user...
623                 && (CtdlCheckInternetMailPermission(&CC->user)==0)              // ...who does not have Internet mail rights...
624         ) {
625                 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n", ChrPtr(SMTP->OneRcpt));
626                 free_recipients(valid);
627                 return;
628         }
629
630         if (
631                 (valid->num_internet > 0)                                       // If it's outbound Internet mail...
632                 && (SMTP->message_originated_locally == 0)                      // ...and also inbound Internet mail...
633                 && (SMTP->is_lmtp == 0)                                         /// ...and didn't arrive via LMTP...
634         ) {
635                 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(SMTP->OneRcpt));
636                 free_recipients(valid);
637                 return;
638         }
639
640         if (
641                 (valid->num_room > 0)                                           // If it's mail to a room (mailing list)...
642                 && (SMTP->message_originated_locally == 0)                      // ...and also inbound Internet mail...
643                 && (is_email_subscribed_to_list((char *)ChrPtr(SMTP->from), valid->recp_room) == 0)     // ...and not a subscriber
644         ) {
645                 cprintf("551 <%s> - The message is not from a list member\r\n", ChrPtr(SMTP->OneRcpt));
646                 free_recipients(valid);
647                 return;
648         }
649
650         cprintf("250 RCPT ok <%s>\r\n", ChrPtr(SMTP->OneRcpt));
651         if (StrLength(SMTP->recipients) > 0) {
652                 StrBufAppendBufPlain(SMTP->recipients, HKEY(","), 0);
653         }
654         StrBufAppendBuf(SMTP->recipients, SMTP->OneRcpt, 0);
655         SMTP->number_of_recipients ++;
656         if (valid != NULL)  {
657                 free_recipients(valid);
658         }
659 }
660
661
662 // Implements the DATA command
663 void smtp_data(void) {
664         StrBuf *body;
665         StrBuf *defbody; 
666         struct CtdlMessage *msg = NULL;
667         long msgnum = (-1L);
668         char nowstamp[SIZ];
669         struct recptypes *valid;
670         int scan_errors;
671         int i;
672
673         if (StrLength(SMTP->from) == 0) {
674                 cprintf("503 Need MAIL command first.\r\n");
675                 return;
676         }
677
678         if (SMTP->number_of_recipients < 1) {
679                 cprintf("503 Need RCPT command first.\r\n");
680                 return;
681         }
682
683         cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
684         
685         datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
686         defbody = NewStrBufPlain(NULL, SIZ);
687
688         if (defbody != NULL) {
689                 if (SMTP->is_lmtp && (CC->cs_UDSclientUID != -1)) {
690                         StrBufPrintf(
691                                 defbody,
692                                 "Received: from %s (Citadel from userid %ld)\n"
693                                 "       by %s; %s\n",
694                                 ChrPtr(SMTP->helo_node),
695                                 (long int) CC->cs_UDSclientUID,
696                                 CtdlGetConfigStr("c_fqdn"),
697                                 nowstamp);
698                 }
699                 else {
700                         StrBufPrintf(
701                                 defbody,
702                                 "Received: from %s (%s [%s])\n"
703                                 "       by %s; %s\n",
704                                 ChrPtr(SMTP->helo_node),
705                                 CC->cs_host,
706                                 CC->cs_addr,
707                                 CtdlGetConfigStr("c_fqdn"),
708                                 nowstamp);
709                 }
710         }
711         body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1);
712         FreeStrBuf(&defbody);
713         if (body == NULL) {
714                 cprintf("550 Unable to save message: internal error.\r\n");
715                 return;
716         }
717
718         syslog(LOG_DEBUG, "serv_smtp: converting message...");
719         msg = convert_internet_message_buf(&body);
720
721         // If the user is locally authenticated, FORCE the From: header to
722         // show up as the real sender.  Yes, this violates the RFC standard,
723         // but IT MAKES SENSE.  If you prefer strict RFC adherence over
724         // common sense, you can disable this in the configuration.
725         //
726         // We also set the "message room name" ('O' field) to MAILROOM
727         // (which is Mail> on most systems) to prevent it from getting set
728         // to something ugly like "0000058008.Sent Items>" when the message
729         // is read with a Citadel client.
730
731         if ( (CC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
732                 int validemail = 0;
733                 
734                 if (!CM_IsEmpty(msg, erFc822Addr)       &&
735                     ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) || 
736                      (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)    )  )
737                 {
738                         if (!IsEmptyStr(CC->cs_inet_email)) {
739                                 validemail = strcmp(CC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
740                         }
741                         if ((!validemail) && (!IsEmptyStr(CC->cs_inet_other_emails))) {
742                                 int num_secondary_emails = 0;
743                                 int i;
744                                 num_secondary_emails = num_tokens(CC->cs_inet_other_emails, '|');
745                                 for (i=0; i < num_secondary_emails && !validemail; ++i) {
746                                         char buf[256];
747                                         extract_token(buf, CC->cs_inet_other_emails,i,'|',sizeof CC->cs_inet_other_emails);
748                                         validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
749                                 }
750                         }
751                 }
752
753                 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
754                         syslog(LOG_ERR, "serv_smtp: invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
755                         cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
756                         return;
757                 }
758
759                 CM_SetField(msg, eOriginalRoom, MAILROOM);
760                 if (SMTP->preferred_sender_name != NULL)
761                         CM_SetField(msg, eAuthor, ChrPtr(SMTP->preferred_sender_name));
762                 else 
763                         CM_SetField(msg, eAuthor, CC->user.fullname);
764
765                 if (!validemail) {
766                         if (SMTP->preferred_sender_email != NULL) {
767                                 CM_SetField(msg, erFc822Addr, ChrPtr(SMTP->preferred_sender_email));
768                         }
769                         else {
770                                 CM_SetField(msg, erFc822Addr, CC->cs_inet_email);
771                         }
772                 }
773         }
774
775         // Set the "envelope from" address
776         CM_SetField(msg, eMessagePath, ChrPtr(SMTP->from));
777
778         // Set the "envelope to" address
779         CM_SetField(msg, eenVelopeTo, ChrPtr(SMTP->recipients));
780
781         // Submit the message into the Citadel system.
782         valid = validate_recipients(
783                 (char *)ChrPtr(SMTP->recipients),
784                 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
785         );
786
787         // If there are modules that want to scan this message before final
788         // submission (such as virus checkers or spam filters), call them now
789         // and give them an opportunity to reject the message.
790         if (SMTP->is_unfiltered) {
791                 scan_errors = 0;
792         }
793         else {
794                 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
795         }
796
797         if (scan_errors > 0) {  // We don't want this message!
798
799                 if (CM_IsEmpty(msg, eErrorMsg)) {
800                         CM_SetField(msg, eErrorMsg, "Message rejected by filter");
801                 }
802
803                 StrBufPrintf(SMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
804         }
805         
806         else {                  // Ok, we'll accept this message.
807                 msgnum = CtdlSubmitMsg(msg, valid, "");
808                 if (msgnum > 0L) {
809                         StrBufPrintf(SMTP->OneRcpt, "250 Message accepted.\r\n");
810                 }
811                 else {
812                         StrBufPrintf(SMTP->OneRcpt, "550 Internal delivery error\r\n");
813                 }
814         }
815
816         // For SMTP and ESMTP, just print the result message.  For LMTP, we
817         // have to print one result message for each recipient.  Since there
818         // is nothing in Citadel which would cause different recipients to
819         // have different results, we can get away with just spitting out the
820         // same message once for each recipient.
821         if (SMTP->is_lmtp) {
822                 for (i=0; i<SMTP->number_of_recipients; ++i) {
823                         cputbuf(SMTP->OneRcpt);
824                 }
825         }
826         else {
827                 cputbuf(SMTP->OneRcpt);
828         }
829
830         // Write something to the syslog(which may or may not be where the
831         // rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
832         syslog((LOG_MAIL | LOG_INFO),
833                     "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
834                     msgnum,
835                     ChrPtr(SMTP->from),
836                     SMTP->number_of_recipients,
837                     CC->cs_host,
838                     CC->cs_addr,
839                     ChrPtr(SMTP->OneRcpt)
840         );
841
842         // Clean up
843         CM_Free(msg);
844         free_recipients(valid);
845         smtp_data_clear();      // clear out the buffers now
846 }
847
848
849 // Implements the STARTTLS command
850 void smtp_starttls(void) {
851         char ok_response[SIZ];
852         char nosup_response[SIZ];
853         char error_response[SIZ];
854
855         sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
856         sprintf(nosup_response, "554 TLS not supported here\r\n");
857         sprintf(error_response, "554 Internal error\r\n");
858         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
859         smtp_rset(0);
860 }
861
862
863 // Implements the NOOP (NO OPeration) command
864 void smtp_noop(void) {
865         cprintf("250 NOOP\r\n");
866 }
867
868
869 // Implements the QUIT command
870 void smtp_quit(void) {
871         cprintf("221 Goodbye...\r\n");
872         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
873 }
874
875
876 // Main command loop for SMTP server sessions.
877 void smtp_command_loop(void) {
878         static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
879
880         assert(SMTP != NULL);
881
882         time(&CC->lastcmd);
883         if (CtdlClientGetLine(SMTP->Cmd) < 1) {
884                 syslog(LOG_INFO, "SMTP: client disconnected: ending session.");
885                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
886                 return;
887         }
888
889         if (SMTP->command_state == smtp_user) {
890                 if (!strncmp(ChrPtr(SMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len)) {
891                         smtp_try_plain();
892                 }
893                 else {
894                         smtp_get_user(0);
895                 }
896                 return;
897         }
898
899         else if (SMTP->command_state == smtp_password) {
900                 smtp_get_pass();
901                 return;
902         }
903
904         else if (SMTP->command_state == smtp_plain) {
905                 smtp_try_plain();
906                 return;
907         }
908
909         syslog(LOG_DEBUG, "serv_smtp: client sent command <%s>", ChrPtr(SMTP->Cmd));
910
911         if (!strncasecmp(ChrPtr(SMTP->Cmd), "NOOP", 4)) {
912                 smtp_noop();
913                 return;
914         }
915
916         if (!strncasecmp(ChrPtr(SMTP->Cmd), "QUIT", 4)) {
917                 smtp_quit();
918                 return;
919         }
920
921         if (!strncasecmp(ChrPtr(SMTP->Cmd), "HELO", 4)) {
922                 smtp_hello(HELO);
923                 return;
924         }
925
926         if (!strncasecmp(ChrPtr(SMTP->Cmd), "EHLO", 4)) {
927                 smtp_hello(EHLO);
928                 return;
929         }
930
931         if (!strncasecmp(ChrPtr(SMTP->Cmd), "LHLO", 4)) {
932                 smtp_hello(LHLO);
933                 return;
934         }
935
936         if (!strncasecmp(ChrPtr(SMTP->Cmd), "RSET", 4)) {
937                 smtp_rset(1);
938                 return;
939         }
940
941         if (!strncasecmp(ChrPtr(SMTP->Cmd), "AUTH", 4)) {
942                 smtp_auth();
943                 return;
944         }
945
946         if (!strncasecmp(ChrPtr(SMTP->Cmd), "DATA", 4)) {
947                 smtp_data();
948                 return;
949         }
950
951         if (!strncasecmp(ChrPtr(SMTP->Cmd), "HELP", 4)) {
952                 smtp_help();
953                 return;
954         }
955
956         if (!strncasecmp(ChrPtr(SMTP->Cmd), "MAIL", 4)) {
957                 smtp_mail();
958                 return;
959         }
960         
961         if (!strncasecmp(ChrPtr(SMTP->Cmd), "RCPT", 4)) {
962                 smtp_rcpt();
963                 return;
964         }
965         if (!strncasecmp(ChrPtr(SMTP->Cmd), "STARTTLS", 8)) {
966                 smtp_starttls();
967                 return;
968         }
969
970         cprintf("502 I'm afraid I can't do that.\r\n");
971 }
972
973
974 // *****************************************************************************
975 // *                      MODULE INITIALIZATION STUFF                          *
976 // *****************************************************************************
977
978 // This cleanup function blows away the temporary memory used by
979 // the SMTP server.
980 void smtp_cleanup_function(void) {
981         // Don't do this stuff if this is not an SMTP session!
982         if (CC->h_command_function != smtp_command_loop) return;
983
984         syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
985
986         FreeStrBuf(&SMTP->Cmd);
987         FreeStrBuf(&SMTP->helo_node);
988         FreeStrBuf(&SMTP->from);
989         FreeStrBuf(&SMTP->recipients);
990         FreeStrBuf(&SMTP->OneRcpt);
991         FreeStrBuf(&SMTP->preferred_sender_email);
992         FreeStrBuf(&SMTP->preferred_sender_name);
993
994         free(SMTP);
995 }
996
997 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
998 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
999 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1000 const char *CitadelServiceSMTP_LMTP="LMTP";
1001 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1002
1003
1004 // Initialization function, called from modules_init.c
1005 char *ctdl_module_init_smtp(void) {
1006         if (!threading) {
1007                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"),        // SMTP MTA
1008                                         NULL,
1009                                         smtp_mta_greeting,
1010                                         smtp_command_loop,
1011                                         NULL, 
1012                                         CitadelServiceSMTP_MTA);
1013
1014                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"),       // SMTPS MTA
1015                                         NULL,
1016                                         smtps_greeting,
1017                                         smtp_command_loop,
1018                                         NULL,
1019                                         CitadelServiceSMTPS_MTA);
1020
1021                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"),         // SMTP MSA
1022                                         NULL,
1023                                         smtp_msa_greeting,
1024                                         smtp_command_loop,
1025                                         NULL,
1026                                         CitadelServiceSMTP_MSA);
1027
1028                 CtdlRegisterServiceHook(0,                                      // local LMTP
1029                                         file_lmtp_socket,
1030                                         lmtp_greeting,
1031                                         smtp_command_loop,
1032                                         NULL,
1033                                         CitadelServiceSMTP_LMTP);
1034
1035                 CtdlRegisterServiceHook(0,                                      // local LMTP
1036                                         file_lmtp_unfiltered_socket,
1037                                         lmtp_unfiltered_greeting,
1038                                         smtp_command_loop,
1039                                         NULL,
1040                                         CitadelServiceSMTP_LMTP_UNF);
1041
1042                 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1043         }
1044         
1045         // return our module name for the log
1046         return "smtp";
1047 }