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