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