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