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