2 * This module is an SMTP and ESMTP server for the Citadel system.
3 * It is compliant with all of the following:
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
20 * The VRFY and EXPN commands have been removed from this implementation
21 * because nobody uses these commands anymore, except for spammers.
23 * Copyright (c) 1998-2020 by the citadel.org team
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.
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.
43 #include <sys/types.h>
46 #if TIME_WITH_SYS_TIME
47 # include <sys/time.h>
51 # include <sys/time.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 #include <libcitadel.h>
67 #include "citserver.h"
75 #include "internet_addressing.h"
78 #include "clientsocket.h"
79 #include "locate_host.h"
80 #include "citadel_dirs.h"
81 #include "ctdl_module.h"
83 #include "smtp_util.h"
85 enum { /* Command states for login authentication */
98 typedef void (*smtp_handler)(long offest, long Flags);
100 typedef struct _smtp_handler_hook {
105 int EnableSMTPLog = 0;
107 HashList *SMTPCmds = NULL;
108 #define MaxSMTPCmdLen 10
110 #define RegisterSmtpCMD(First, H, Flags) \
111 registerSmtpCMD(HKEY(First), H, Flags)
112 void registerSmtpCMD(const char *First, long FLen,
116 smtp_handler_hook *h;
118 if (FLen >= MaxSMTPCmdLen)
123 h = (smtp_handler_hook*) malloc(sizeof(smtp_handler_hook));
124 memset(h, 0, sizeof(smtp_handler_hook));
128 Put(SMTPCmds, First, FLen, h, NULL);
132 void smtp_cleanup(void)
134 DeleteHash(&SMTPCmds);
138 * Here's where our SMTP session begins its happy day.
140 void smtp_greeting(int is_msa)
143 char message_to_spammer[1024];
145 strcpy(CC->cs_clientname, "SMTP session");
146 CC->internal_pgm = 1;
147 CC->cs_flags |= CS_STEALTH;
148 CC->session_specific_data = malloc(sizeof(citsmtp));
149 memset(SMTP, 0, sizeof(citsmtp));
151 sSMTP->is_msa = is_msa;
152 sSMTP->Cmd = NewStrBufPlain(NULL, SIZ);
153 sSMTP->helo_node = NewStrBuf();
154 sSMTP->from = NewStrBufPlain(NULL, SIZ);
155 sSMTP->recipients = NewStrBufPlain(NULL, SIZ);
156 sSMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
157 sSMTP->preferred_sender_email = NULL;
158 sSMTP->preferred_sender_name = NULL;
160 /* If this config option is set, reject connections from problem
161 * addresses immediately instead of after they execute a RCPT
163 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (sSMTP->is_msa == 0) ) {
164 if (rbl_check(CC->cs_addr, message_to_spammer)) {
165 if (server_shutting_down)
166 cprintf("421 %s\r\n", message_to_spammer);
168 cprintf("550 %s\r\n", message_to_spammer);
169 CC->kill_me = KILLME_SPAMMER;
170 /* no need to free_recipients(valid), it's not allocated yet */
175 /* Otherwise we're either clean or we check later. */
177 if (CC->nologin==1) {
178 cprintf("451 Too many connections are already open; please try again later.\r\n");
179 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
180 /* no need to free_recipients(valid), it's not allocated yet */
184 /* Note: the FQDN *must* appear as the first thing after the 220 code.
185 * Some clients (including citmail.c) depend on it being there.
187 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
192 * SMTPS is just like SMTP, except it goes crypto right away.
194 void smtps_greeting(void) {
195 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
197 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
204 * SMTP MSA port requires authentication.
206 void smtp_msa_greeting(void) {
212 * LMTP is like SMTP but with some extra bonus footage added.
214 void lmtp_greeting(void) {
222 * Generic SMTP MTA greeting
224 void smtp_mta_greeting(void) {
230 * We also have an unfiltered LMTP socket that bypasses spam filters.
232 void lmtp_unfiltered_greeting(void) {
238 sSMTP->is_unfiltered = 1;
243 * Login greeting common to all auth methods
245 void smtp_auth_greeting(long offset, long Flags) {
246 struct CitContext *CCC = CC;
247 cprintf("235 Hello, %s\r\n", CCC->user.fullname);
248 syslog(LOG_NOTICE, "SMTP authenticated %s", CCC->user.fullname);
249 CCC->internal_pgm = 0;
250 CCC->cs_flags &= ~CS_STEALTH;
255 * Implement HELO and EHLO commands.
257 * which_command: 0=HELO, 1=EHLO, 2=LHLO
259 void smtp_hello(long offset, long which_command)
261 struct CitContext *CCC = CC;
262 citsmtp *sSMTP = SMTP;
264 StrBufAppendBuf (sSMTP->helo_node, sSMTP->Cmd, offset);
266 if ( (which_command != LHLO) && (sSMTP->is_lmtp) ) {
267 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
271 if ( (which_command == LHLO) && (sSMTP->is_lmtp == 0) ) {
272 cprintf("500 LHLO is only allowed when running LMTP\r\n");
276 if (which_command == HELO) {
277 cprintf("250 Hello %s (%s [%s])\r\n",
278 ChrPtr(sSMTP->helo_node),
284 if (which_command == EHLO) {
285 cprintf("250-Hello %s (%s [%s])\r\n",
286 ChrPtr(sSMTP->helo_node),
292 cprintf("250-Greetings and joyous salutations.\r\n");
294 cprintf("250-HELP\r\n");
295 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
299 * Offer TLS, but only if TLS is not already active.
300 * Furthermore, only offer TLS when running on
301 * the SMTP-MSA port, not on the SMTP-MTA port, due to
302 * questionable reliability of TLS in certain sending MTA's.
304 if ( (!CCC->redirect_ssl) && (sSMTP->is_msa) ) {
305 cprintf("250-STARTTLS\r\n");
307 #endif /* HAVE_OPENSSL */
309 cprintf("250-AUTH LOGIN PLAIN\r\n"
310 "250-AUTH=LOGIN PLAIN\r\n"
318 * Backend function for smtp_webcit_preferences_hack().
319 * Look at a message and determine if it's the preferences file.
321 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
322 struct CtdlMessage *msg;
323 char **webcit_conf = (char **) userdata;
326 return; // already got it
329 msg = CtdlFetchMessage(msgnum, 1);
334 if ( !CM_IsEmpty(msg, eMsgSubject) &&
335 (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __")))
337 /* This is it! Change ownership of the message text so it doesn't get freed. */
338 *webcit_conf = (char *)msg->cm_fields[eMesageText];
339 msg->cm_fields[eMesageText] = NULL;
346 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
347 * stored in the account's WebCit configuration. We have to fetch it now.
349 void smtp_webcit_preferences_hack(void) {
350 struct CitContext *CCC = CC;
351 char config_roomname[ROOMNAMELEN];
352 char *webcit_conf = NULL;
353 citsmtp *sSMTP = SMTP;
355 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CCC->user.usernum, USERCONFIGROOM);
356 if (CtdlGetRoom(&CCC->room, config_roomname) != 0) {
361 * Find the WebCit configuration message
364 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
370 /* Parse the webcit configuration and attempt to do something useful with it */
371 char *str = webcit_conf;
373 char *this_line = NULL;
374 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
376 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
377 sSMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
379 if (!strncasecmp(this_line, "defaultname|", 12)) {
380 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
382 if ((!strncasecmp(this_line, "defaultname|", 12)) && (sSMTP->preferred_sender_name == NULL)) {
383 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
393 * Implement HELP command.
395 void smtp_help(long offset, long Flags) {
396 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
403 void smtp_get_user(long offset)
406 citsmtp *sSMTP = SMTP;
408 StrBufDecodeBase64(sSMTP->Cmd);
410 if (CtdlLoginExistingUser(ChrPtr(sSMTP->Cmd)) == login_ok) {
411 size_t len = CtdlEncodeBase64(buf, "Password:", 9, 0);
413 if (buf[len - 1] == '\n') {
416 cprintf("334 %s\r\n", buf);
417 sSMTP->command_state = smtp_password;
420 cprintf("500 No such user.\r\n");
421 sSMTP->command_state = smtp_command;
429 void smtp_get_pass(long offset, long Flags)
431 citsmtp *sSMTP = SMTP;
434 memset(password, 0, sizeof(password));
435 StrBufDecodeBase64(sSMTP->Cmd);
436 syslog(LOG_DEBUG, "Trying <%s>", password);
437 if (CtdlTryPassword(SKEY(sSMTP->Cmd)) == pass_ok) {
438 smtp_auth_greeting(offset, Flags);
441 cprintf("535 Authentication failed.\r\n");
443 sSMTP->command_state = smtp_command;
448 * Back end for PLAIN auth method (either inline or multistate)
450 void smtp_try_plain(long offset, long Flags)
452 citsmtp *sSMTP = SMTP;
453 const char*decoded_authstring;
454 char ident[256] = "";
463 memset(pass, 0, sizeof(pass));
464 decoded_len = StrBufDecodeBase64(sSMTP->Cmd);
468 decoded_authstring = ChrPtr(sSMTP->Cmd);
470 len = safestrncpy(ident, decoded_authstring, sizeof ident);
472 decoded_len -= len - 1;
473 decoded_authstring += len + 1;
477 len = safestrncpy(user, decoded_authstring, sizeof user);
479 decoded_authstring += len + 1;
480 decoded_len -= len - 1;
485 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
488 plen = sizeof(pass) - 1;
492 sSMTP->command_state = smtp_command;
494 if (!IsEmptyStr(ident)) {
495 result = CtdlLoginExistingUser(ident);
498 result = CtdlLoginExistingUser(user);
501 if (result == login_ok) {
502 if (CtdlTryPassword(pass, plen) == pass_ok) {
503 smtp_webcit_preferences_hack();
504 smtp_auth_greeting(offset, Flags);
508 cprintf("504 Authentication failed.\r\n");
513 * Attempt to perform authenticated SMTP
515 void smtp_auth(long offset, long Flags)
517 struct CitContext *CCC = CC;
518 citsmtp *sSMTP = SMTP;
519 char username_prompt[64];
521 char encoded_authstring[1024];
523 if (CCC->logged_in) {
524 cprintf("504 Already logged in.\r\n");
528 extract_token(method, ChrPtr(sSMTP->Cmd) + offset, 0, ' ', sizeof method);
530 if (!strncasecmp(method, "login", 5) ) {
531 if (StrLength(sSMTP->Cmd) - offset >= 7) {
535 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
536 if (username_prompt[len - 1] == '\n') {
537 username_prompt[len - 1] = '\0';
539 cprintf("334 %s\r\n", username_prompt);
540 sSMTP->command_state = smtp_user;
545 if (!strncasecmp(method, "plain", 5) ) {
547 if (num_tokens(ChrPtr(sSMTP->Cmd) + offset, ' ') < 2) {
549 SMTP->command_state = smtp_plain;
553 len = extract_token(encoded_authstring,
554 ChrPtr(sSMTP->Cmd) + offset,
556 sizeof encoded_authstring);
557 StrBufPlain(sSMTP->Cmd, encoded_authstring, len);
558 smtp_try_plain(0, Flags);
562 if (strncasecmp(method, "login", 5) ) {
563 cprintf("504 Unknown authentication method.\r\n");
571 * Implements the RSET (reset state) command.
572 * Currently this just zeroes out the state buffer. If pointers to data
573 * allocated with malloc() are ever placed in the state buffer, we have to
574 * be sure to free() them first!
576 * Set do_response to nonzero to output the SMTP RSET response code.
578 void smtp_rset(long offset, long do_response) {
579 citsmtp *sSMTP = SMTP;
582 * Our entire SMTP state is discarded when a RSET command is issued,
583 * but we need to preserve this one little piece of information, so
584 * we save it for later.
587 FlushStrBuf(sSMTP->Cmd);
588 FlushStrBuf(sSMTP->helo_node);
589 FlushStrBuf(sSMTP->from);
590 FlushStrBuf(sSMTP->recipients);
591 FlushStrBuf(sSMTP->OneRcpt);
593 sSMTP->command_state = 0;
594 sSMTP->number_of_recipients = 0;
595 sSMTP->delivery_mode = 0;
596 sSMTP->message_originated_locally = 0;
599 * we must remember is_lmtp & is_unfiltered.
603 * It is somewhat ambiguous whether we want to log out when a RSET
604 * command is issued. Here's the code to do it. It is commented out
605 * because some clients (such as Pine) issue RSET commands before
606 * each message, but still expect to be logged in.
608 * if (CC->logged_in) {
614 cprintf("250 Zap!\r\n");
619 * Clear out the portions of the state buffer that need to be cleared out
620 * after the DATA command finishes.
622 void smtp_data_clear(long offset, long flags)
624 citsmtp *sSMTP = SMTP;
626 FlushStrBuf(sSMTP->from);
627 FlushStrBuf(sSMTP->recipients);
628 FlushStrBuf(sSMTP->OneRcpt);
629 sSMTP->number_of_recipients = 0;
630 sSMTP->delivery_mode = 0;
631 sSMTP->message_originated_locally = 0;
635 * Implements the "MAIL FROM:" command
637 void smtp_mail(long offset, long flags) {
641 struct CitContext *CCC = CC;
642 citsmtp *sSMTP = SMTP;
644 if (StrLength(sSMTP->from) > 0) {
645 cprintf("503 Only one sender permitted\r\n");
649 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "From:", 5)) {
650 cprintf("501 Syntax error\r\n");
654 StrBufAppendBuf(sSMTP->from, sSMTP->Cmd, offset);
655 StrBufTrim(sSMTP->from);
656 if (strchr(ChrPtr(sSMTP->from), '<') != NULL) {
657 StrBufStripAllBut(sSMTP->from, '<', '>');
660 /* We used to reject empty sender names, until it was brought to our
661 * attention that RFC1123 5.2.9 requires that this be allowed. So now
662 * we allow it, but replace the empty string with a fake
663 * address so we don't have to contend with the empty string causing
664 * other code to fail when it's expecting something there.
666 if (StrLength(sSMTP->from) == 0) {
667 StrBufPlain(sSMTP->from, HKEY("someone@example.com"));
670 /* If this SMTP connection is from a logged-in user, force the 'from'
671 * to be the user's Internet e-mail address as Citadel knows it.
673 if (CCC->logged_in) {
674 StrBufPlain(sSMTP->from, CCC->cs_inet_email, -1);
675 cprintf("250 Sender ok <%s>\r\n", ChrPtr(sSMTP->from));
676 sSMTP->message_originated_locally = 1;
680 else if (sSMTP->is_lmtp) {
681 /* Bypass forgery checking for LMTP */
684 /* Otherwise, make sure outsiders aren't trying to forge mail from
685 * this system (unless, of course, c_allow_spoofing is enabled)
687 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
688 process_rfc822_addr(ChrPtr(sSMTP->from), user, node, name);
689 syslog(LOG_DEBUG, "Claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
690 ChrPtr(sSMTP->from), user, node, name
692 if (CtdlHostAlias(node) != hostalias_nomatch) {
693 cprintf("550 You must log in to send mail from %s\r\n", node);
694 FlushStrBuf(sSMTP->from);
695 syslog(LOG_DEBUG, "Rejecting unauthenticated mail from %s", node);
700 cprintf("250 Sender ok\r\n");
706 * Implements the "RCPT To:" command
708 void smtp_rcpt(long offset, long flags)
710 struct CitContext *CCC = CC;
711 char message_to_spammer[SIZ];
712 recptypes *valid = NULL;
713 citsmtp *sSMTP = SMTP;
715 if (StrLength(sSMTP->from) == 0) {
716 cprintf("503 Need MAIL before RCPT\r\n");
720 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "To:", 3)) {
721 cprintf("501 Syntax error\r\n");
725 if ( (sSMTP->is_msa) && (!CCC->logged_in) ) {
726 cprintf("550 You must log in to send mail on this port.\r\n");
727 FlushStrBuf(sSMTP->from);
730 FlushStrBuf(sSMTP->OneRcpt);
731 StrBufAppendBuf(sSMTP->OneRcpt, sSMTP->Cmd, offset + 3);
732 StrBufTrim(sSMTP->OneRcpt);
733 StrBufStripAllBut(sSMTP->OneRcpt, '<', '>');
735 if ( (StrLength(sSMTP->OneRcpt) + StrLength(sSMTP->recipients)) >= SIZ) {
736 cprintf("452 Too many recipients\r\n");
741 if ( (!CCC->logged_in) /* Don't RBL authenticated users */
742 && (!sSMTP->is_lmtp) ) { /* Don't RBL LMTP clients */
743 if (CtdlGetConfigInt("c_rbl_at_greeting") == 0) { /* Don't RBL again if we already did it */
744 if (rbl_check(CC->cs_addr, message_to_spammer)) {
745 if (server_shutting_down)
746 cprintf("421 %s\r\n", message_to_spammer);
748 cprintf("550 %s\r\n", message_to_spammer);
749 /* no need to free_recipients(valid), it's not allocated yet */
755 valid = validate_recipients(
756 ChrPtr(sSMTP->OneRcpt),
757 smtp_get_Recipients(),
758 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
760 if (valid->num_error != 0) {
761 cprintf("550 %s\r\n", valid->errormsg);
762 free_recipients(valid);
766 if (valid->num_internet > 0) {
767 if (CCC->logged_in) {
768 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
769 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n",
770 ChrPtr(sSMTP->OneRcpt));
771 free_recipients(valid);
777 if (valid->num_internet > 0) {
778 if ( (sSMTP->message_originated_locally == 0)
779 && (sSMTP->is_lmtp == 0) ) {
780 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(sSMTP->OneRcpt));
781 free_recipients(valid);
786 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(sSMTP->OneRcpt));
787 if (StrLength(sSMTP->recipients) > 0) {
788 StrBufAppendBufPlain(sSMTP->recipients, HKEY(","), 0);
790 StrBufAppendBuf(sSMTP->recipients, sSMTP->OneRcpt, 0);
791 sSMTP->number_of_recipients ++;
793 free_recipients(valid);
801 * Implements the DATA command
803 void smtp_data(long offset, long flags)
805 struct CitContext *CCC = CC;
808 struct CtdlMessage *msg = NULL;
814 citsmtp *sSMTP = SMTP;
816 if (StrLength(sSMTP->from) == 0) {
817 cprintf("503 Need MAIL command first.\r\n");
821 if (sSMTP->number_of_recipients < 1) {
822 cprintf("503 Need RCPT command first.\r\n");
826 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
828 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
829 defbody = NewStrBufPlain(NULL, SIZ);
831 if (defbody != NULL) {
832 if (sSMTP->is_lmtp && (CCC->cs_UDSclientUID != -1)) {
835 "Received: from %s (Citadel from userid %ld)\n"
837 ChrPtr(sSMTP->helo_node),
838 (long int) CCC->cs_UDSclientUID,
839 CtdlGetConfigStr("c_fqdn"),
845 "Received: from %s (%s [%s])\n"
847 ChrPtr(sSMTP->helo_node),
850 CtdlGetConfigStr("c_fqdn"),
854 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1);
855 FreeStrBuf(&defbody);
857 cprintf("550 Unable to save message: internal error.\r\n");
861 syslog(LOG_DEBUG, "Converting message...");
862 msg = convert_internet_message_buf(&body);
864 /* If the user is locally authenticated, FORCE the From: header to
865 * show up as the real sender. Yes, this violates the RFC standard,
866 * but IT MAKES SENSE. If you prefer strict RFC adherence over
867 * common sense, you can disable this in the configuration.
869 * We also set the "message room name" ('O' field) to MAILROOM
870 * (which is Mail> on most systems) to prevent it from getting set
871 * to something ugly like "0000058008.Sent Items>" when the message
872 * is read with a Citadel client.
874 if ( (CCC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
877 if (!CM_IsEmpty(msg, erFc822Addr) &&
878 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
879 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
881 if (!IsEmptyStr(CCC->cs_inet_email))
882 validemail = strcmp(CCC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
884 (!IsEmptyStr(CCC->cs_inet_other_emails)))
886 int num_secondary_emails = 0;
888 num_secondary_emails = num_tokens(CCC->cs_inet_other_emails, '|');
889 for (i=0; i < num_secondary_emails && !validemail; ++i) {
891 extract_token(buf, CCC->cs_inet_other_emails,i,'|',sizeof CCC->cs_inet_other_emails);
892 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
897 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
898 syslog(LOG_ERR, "invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
899 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
903 CM_SetField(msg, eOriginalRoom, HKEY(MAILROOM));
904 if (sSMTP->preferred_sender_name != NULL)
905 CM_SetField(msg, eAuthor, SKEY(sSMTP->preferred_sender_name));
907 CM_SetField(msg, eAuthor, CCC->user.fullname, strlen(CCC->user.fullname));
910 if (sSMTP->preferred_sender_email != NULL)
911 CM_SetField(msg, erFc822Addr, SKEY(sSMTP->preferred_sender_email));
913 CM_SetField(msg, erFc822Addr, CCC->cs_inet_email, strlen(CCC->cs_inet_email));
917 /* Set the "envelope from" address */
918 CM_SetField(msg, eMessagePath, SKEY(sSMTP->from));
920 /* Set the "envelope to" address */
921 CM_SetField(msg, eenVelopeTo, SKEY(sSMTP->recipients));
923 /* Submit the message into the Citadel system. */
924 valid = validate_recipients(
925 ChrPtr(sSMTP->recipients),
926 smtp_get_Recipients(),
927 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
930 /* If there are modules that want to scan this message before final
931 * submission (such as virus checkers or spam filters), call them now
932 * and give them an opportunity to reject the message.
934 if (sSMTP->is_unfiltered) {
938 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
941 if (scan_errors > 0) { /* We don't want this message! */
943 if (CM_IsEmpty(msg, eErrorMsg)) {
944 CM_SetField(msg, eErrorMsg, HKEY("Message rejected by filter"));
947 StrBufPrintf(sSMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
950 else { /* Ok, we'll accept this message. */
951 msgnum = CtdlSubmitMsg(msg, valid, "");
953 StrBufPrintf(sSMTP->OneRcpt, "250 Message accepted.\r\n");
956 StrBufPrintf(sSMTP->OneRcpt, "550 Internal delivery error\r\n");
960 /* For SMTP and ESMTP, just print the result message. For LMTP, we
961 * have to print one result message for each recipient. Since there
962 * is nothing in Citadel which would cause different recipients to
963 * have different results, we can get away with just spitting out the
964 * same message once for each recipient.
966 if (sSMTP->is_lmtp) {
967 for (i=0; i<sSMTP->number_of_recipients; ++i) {
968 cputbuf(sSMTP->OneRcpt);
972 cputbuf(sSMTP->OneRcpt);
975 /* Write something to the syslog(which may or may not be where the
976 * rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
978 syslog((LOG_MAIL | LOG_INFO),
979 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
982 sSMTP->number_of_recipients,
985 ChrPtr(sSMTP->OneRcpt)
990 free_recipients(valid);
991 smtp_data_clear(0, 0); /* clear out the buffers now */
996 * implements the STARTTLS command
998 void smtp_starttls(long offset, long flags)
1000 char ok_response[SIZ];
1001 char nosup_response[SIZ];
1002 char error_response[SIZ];
1004 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
1005 sprintf(nosup_response, "554 TLS not supported here\r\n");
1006 sprintf(error_response, "554 Internal error\r\n");
1007 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
1013 * Main command loop for SMTP server sessions.
1015 void smtp_command_loop(void)
1017 static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
1018 struct CitContext *CCC = CC;
1019 citsmtp *sSMTP = SMTP;
1020 const char *pch, *pchs;
1022 char CMD[MaxSMTPCmdLen + 1];
1024 if (sSMTP == NULL) {
1025 syslog(LOG_EMERG, "Session SMTP data is null. WTF? We will crash now.");
1029 time(&CCC->lastcmd);
1030 if (CtdlClientGetLine(sSMTP->Cmd) < 1) {
1031 syslog(LOG_CRIT, "SMTP: client disconnected: ending session.");
1032 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1035 syslog(LOG_DEBUG, "SMTP server: %s", ChrPtr(sSMTP->Cmd));
1037 if (sSMTP->command_state == smtp_user) {
1038 if (!strncmp(ChrPtr(sSMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len))
1039 smtp_try_plain(0, 0);
1045 else if (sSMTP->command_state == smtp_password) {
1046 smtp_get_pass(0, 0);
1050 else if (sSMTP->command_state == smtp_plain) {
1051 smtp_try_plain(0, 0);
1055 pchs = pch = ChrPtr(sSMTP->Cmd);
1057 while ((*pch != '\0') &&
1059 (pch - pchs <= MaxSMTPCmdLen))
1061 CMD[i] = toupper(*pch);
1067 if ((*pch == '\0') ||
1072 if (GetHash(SMTPCmds, CMD, i, &v) &&
1075 smtp_handler_hook *h = (smtp_handler_hook*) v;
1077 if (isblank(pchs[i]))
1085 cprintf("502 I'm afraid I can't do that.\r\n");
1088 void smtp_noop(long offest, long Flags)
1090 cprintf("250 NOOP\r\n");
1093 void smtp_quit(long offest, long Flags)
1095 cprintf("221 Goodbye...\r\n");
1096 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1099 /*****************************************************************************/
1100 /* MODULE INITIALIZATION STUFF */
1101 /*****************************************************************************/
1103 * This cleanup function blows away the temporary memory used by
1106 void smtp_cleanup_function(void)
1108 citsmtp *sSMTP = SMTP;
1109 struct CitContext *CCC = CC;
1111 /* Don't do this stuff if this is not an SMTP session! */
1112 if (CCC->h_command_function != smtp_command_loop) return;
1114 syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
1116 FreeStrBuf(&sSMTP->Cmd);
1117 FreeStrBuf(&sSMTP->helo_node);
1118 FreeStrBuf(&sSMTP->from);
1119 FreeStrBuf(&sSMTP->recipients);
1120 FreeStrBuf(&sSMTP->OneRcpt);
1121 FreeStrBuf(&sSMTP->preferred_sender_email);
1122 FreeStrBuf(&sSMTP->preferred_sender_name);
1127 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1128 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1129 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1130 const char *CitadelServiceSMTP_LMTP="LMTP";
1131 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1134 CTDL_MODULE_INIT(smtp)
1138 SMTPCmds = NewHash(1, NULL);
1140 RegisterSmtpCMD("AUTH", smtp_auth, 0);
1141 RegisterSmtpCMD("DATA", smtp_data, 0);
1142 RegisterSmtpCMD("HELO", smtp_hello, HELO);
1143 RegisterSmtpCMD("EHLO", smtp_hello, EHLO);
1144 RegisterSmtpCMD("LHLO", smtp_hello, LHLO);
1145 RegisterSmtpCMD("HELP", smtp_help, 0);
1146 RegisterSmtpCMD("MAIL", smtp_mail, 0);
1147 RegisterSmtpCMD("NOOP", smtp_noop, 0);
1148 RegisterSmtpCMD("QUIT", smtp_quit, 0);
1149 RegisterSmtpCMD("RCPT", smtp_rcpt, 0);
1150 RegisterSmtpCMD("RSET", smtp_rset, 1);
1152 RegisterSmtpCMD("STARTTLS", smtp_starttls, 0);
1156 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"), /* SMTP MTA */
1161 CitadelServiceSMTP_MTA);
1164 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"), /* SMTPS MTA */
1169 CitadelServiceSMTPS_MTA);
1172 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"), /* SMTP MSA */
1177 CitadelServiceSMTP_MSA);
1179 CtdlRegisterServiceHook(0, /* local LMTP */
1184 CitadelServiceSMTP_LMTP);
1186 CtdlRegisterServiceHook(0, /* local LMTP */
1187 file_lmtp_unfiltered_socket,
1188 lmtp_unfiltered_greeting,
1191 CitadelServiceSMTP_LMTP_UNF);
1193 CtdlRegisterCleanupHook(smtp_cleanup);
1194 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1197 /* return our module name for the log */