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