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