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