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