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