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