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