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