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