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