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-2015 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"
84 enum { /* Command states for login authentication */
97 typedef void (*smtp_handler)(long offest, long Flags);
99 typedef struct _smtp_handler_hook {
104 int EnableSMTPLog = 0;
106 HashList *SMTPCmds = NULL;
107 #define MaxSMTPCmdLen 10
109 #define RegisterSmtpCMD(First, H, Flags) \
110 registerSmtpCMD(HKEY(First), H, Flags)
111 void registerSmtpCMD(const char *First, long FLen,
115 smtp_handler_hook *h;
117 if (FLen >= MaxSMTPCmdLen)
118 cit_panic_backtrace (0);
120 h = (smtp_handler_hook*) malloc(sizeof(smtp_handler_hook));
121 memset(h, 0, sizeof(smtp_handler_hook));
125 Put(SMTPCmds, First, FLen, h, NULL);
128 void smtp_cleanup(void)
130 DeleteHash(&SMTPCmds);
134 * Here's where our SMTP session begins its happy day.
136 void smtp_greeting(int is_msa)
139 char message_to_spammer[1024];
141 strcpy(CC->cs_clientname, "SMTP session");
142 CC->internal_pgm = 1;
143 CC->cs_flags |= CS_STEALTH;
144 CC->session_specific_data = malloc(sizeof(citsmtp));
145 memset(SMTP, 0, sizeof(citsmtp));
147 sSMTP->is_msa = is_msa;
148 sSMTP->Cmd = NewStrBufPlain(NULL, SIZ);
149 sSMTP->helo_node = NewStrBuf();
150 sSMTP->from = NewStrBufPlain(NULL, SIZ);
151 sSMTP->recipients = NewStrBufPlain(NULL, SIZ);
152 sSMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
153 sSMTP->preferred_sender_email = NULL;
154 sSMTP->preferred_sender_name = NULL;
156 /* If this config option is set, reject connections from problem
157 * addresses immediately instead of after they execute a RCPT
159 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (sSMTP->is_msa == 0) ) {
160 if (rbl_check(message_to_spammer)) {
161 if (server_shutting_down)
162 cprintf("421 %s\r\n", message_to_spammer);
164 cprintf("550 %s\r\n", message_to_spammer);
165 CC->kill_me = KILLME_SPAMMER;
166 /* no need to free_recipients(valid), it's not allocated yet */
171 /* Otherwise we're either clean or we check later. */
173 if (CC->nologin==1) {
174 cprintf("451 Too many connections are already open; please try again later.\r\n");
175 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
176 /* no need to free_recipients(valid), it's not allocated yet */
180 /* Note: the FQDN *must* appear as the first thing after the 220 code.
181 * Some clients (including citmail.c) depend on it being there.
183 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
188 * SMTPS is just like SMTP, except it goes crypto right away.
190 void smtps_greeting(void) {
191 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
193 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
200 * SMTP MSA port requires authentication.
202 void smtp_msa_greeting(void) {
208 * LMTP is like SMTP but with some extra bonus footage added.
210 void lmtp_greeting(void) {
218 * Generic SMTP MTA greeting
220 void smtp_mta_greeting(void) {
226 * We also have an unfiltered LMTP socket that bypasses spam filters.
228 void lmtp_unfiltered_greeting(void) {
234 sSMTP->is_unfiltered = 1;
239 * Login greeting common to all auth methods
241 void smtp_auth_greeting(long offset, long Flags) {
242 struct CitContext *CCC = CC;
243 cprintf("235 Hello, %s\r\n", CCC->user.fullname);
244 syslog(LOG_NOTICE, "SMTP authenticated %s", CCC->user.fullname);
245 CCC->internal_pgm = 0;
246 CCC->cs_flags &= ~CS_STEALTH;
251 * Implement HELO and EHLO commands.
253 * which_command: 0=HELO, 1=EHLO, 2=LHLO
255 void smtp_hello(long offset, long which_command)
257 struct CitContext *CCC = CC;
258 citsmtp *sSMTP = SMTP;
260 StrBufAppendBuf (sSMTP->helo_node, sSMTP->Cmd, offset);
262 if ( (which_command != LHLO) && (sSMTP->is_lmtp) ) {
263 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
267 if ( (which_command == LHLO) && (sSMTP->is_lmtp == 0) ) {
268 cprintf("500 LHLO is only allowed when running LMTP\r\n");
272 if (which_command == HELO) {
273 cprintf("250 Hello %s (%s [%s])\r\n",
274 ChrPtr(sSMTP->helo_node),
280 if (which_command == EHLO) {
281 cprintf("250-Hello %s (%s [%s])\r\n",
282 ChrPtr(sSMTP->helo_node),
288 cprintf("250-Greetings and joyous salutations.\r\n");
290 cprintf("250-HELP\r\n");
291 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
295 * Offer TLS, but only if TLS is not already active.
296 * Furthermore, only offer TLS when running on
297 * the SMTP-MSA port, not on the SMTP-MTA port, due to
298 * questionable reliability of TLS in certain sending MTA's.
300 if ( (!CCC->redirect_ssl) && (sSMTP->is_msa) ) {
301 cprintf("250-STARTTLS\r\n");
303 #endif /* HAVE_OPENSSL */
305 cprintf("250-AUTH LOGIN PLAIN\r\n"
306 "250-AUTH=LOGIN PLAIN\r\n"
314 * Backend function for smtp_webcit_preferences_hack().
315 * Look at a message and determine if it's the preferences file.
317 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
318 struct CtdlMessage *msg;
319 char **webcit_conf = (char **) userdata;
322 return; // already got it
325 msg = CtdlFetchMessage(msgnum, 1, 1);
330 if ( !CM_IsEmpty(msg, eMsgSubject) &&
331 (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __")))
333 /* This is it! Change ownership of the message text so it doesn't get freed. */
334 *webcit_conf = (char *)msg->cm_fields[eMesageText];
335 msg->cm_fields[eMesageText] = NULL;
342 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
343 * stored in the account's WebCit configuration. We have to fetch it now.
345 void smtp_webcit_preferences_hack(void) {
346 struct CitContext *CCC = CC;
347 char config_roomname[ROOMNAMELEN];
348 char *webcit_conf = NULL;
349 citsmtp *sSMTP = SMTP;
351 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CCC->user.usernum, USERCONFIGROOM);
352 if (CtdlGetRoom(&CCC->room, config_roomname) != 0) {
357 * Find the WebCit configuration message
360 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
366 /* Parse the webcit configuration and attempt to do something useful with it */
367 char *str = webcit_conf;
369 char *this_line = NULL;
370 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
372 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
373 sSMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
375 if (!strncasecmp(this_line, "defaultname|", 12)) {
376 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
378 if ((!strncasecmp(this_line, "defaultname|", 12)) && (sSMTP->preferred_sender_name == NULL)) {
379 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
389 * Implement HELP command.
391 void smtp_help(long offset, long Flags) {
392 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
399 void smtp_get_user(long offset)
402 citsmtp *sSMTP = SMTP;
404 StrBufDecodeBase64(sSMTP->Cmd);
406 if (CtdlLoginExistingUser(NULL, ChrPtr(sSMTP->Cmd)) == login_ok) {
407 size_t len = CtdlEncodeBase64(buf, "Password:", 9, 0);
409 if (buf[len - 1] == '\n') {
412 cprintf("334 %s\r\n", buf);
413 sSMTP->command_state = smtp_password;
416 cprintf("500 No such user.\r\n");
417 sSMTP->command_state = smtp_command;
425 void smtp_get_pass(long offset, long Flags)
427 citsmtp *sSMTP = SMTP;
430 memset(password, 0, sizeof(password));
431 StrBufDecodeBase64(sSMTP->Cmd);
432 syslog(LOG_DEBUG, "Trying <%s>", password);
433 if (CtdlTryPassword(SKEY(sSMTP->Cmd)) == pass_ok) {
434 smtp_auth_greeting(offset, Flags);
437 cprintf("535 Authentication failed.\r\n");
439 sSMTP->command_state = smtp_command;
444 * Back end for PLAIN auth method (either inline or multistate)
446 void smtp_try_plain(long offset, long Flags)
448 citsmtp *sSMTP = SMTP;
449 const char*decoded_authstring;
450 char ident[256] = "";
459 memset(pass, 0, sizeof(pass));
460 decoded_len = StrBufDecodeBase64(sSMTP->Cmd);
464 decoded_authstring = ChrPtr(sSMTP->Cmd);
466 len = safestrncpy(ident, decoded_authstring, sizeof ident);
468 decoded_len -= len - 1;
469 decoded_authstring += len + 1;
473 len = safestrncpy(user, decoded_authstring, sizeof user);
475 decoded_authstring += len + 1;
476 decoded_len -= len - 1;
481 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
484 plen = sizeof(pass) - 1;
488 sSMTP->command_state = smtp_command;
490 if (!IsEmptyStr(ident)) {
491 result = CtdlLoginExistingUser(user, ident);
494 result = CtdlLoginExistingUser(NULL, user);
497 if (result == login_ok) {
498 if (CtdlTryPassword(pass, plen) == pass_ok) {
499 smtp_webcit_preferences_hack();
500 smtp_auth_greeting(offset, Flags);
504 cprintf("504 Authentication failed.\r\n");
509 * Attempt to perform authenticated SMTP
511 void smtp_auth(long offset, long Flags)
513 struct CitContext *CCC = CC;
514 citsmtp *sSMTP = SMTP;
515 char username_prompt[64];
517 char encoded_authstring[1024];
519 if (CCC->logged_in) {
520 cprintf("504 Already logged in.\r\n");
524 extract_token(method, ChrPtr(sSMTP->Cmd) + offset, 0, ' ', sizeof method);
526 if (!strncasecmp(method, "login", 5) ) {
527 if (StrLength(sSMTP->Cmd) - offset >= 7) {
531 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
532 if (username_prompt[len - 1] == '\n') {
533 username_prompt[len - 1] = '\0';
535 cprintf("334 %s\r\n", username_prompt);
536 sSMTP->command_state = smtp_user;
541 if (!strncasecmp(method, "plain", 5) ) {
543 if (num_tokens(ChrPtr(sSMTP->Cmd) + offset, ' ') < 2) {
545 SMTP->command_state = smtp_plain;
549 len = extract_token(encoded_authstring,
550 ChrPtr(sSMTP->Cmd) + offset,
552 sizeof encoded_authstring);
553 StrBufPlain(sSMTP->Cmd, encoded_authstring, len);
554 smtp_try_plain(0, Flags);
558 if (strncasecmp(method, "login", 5) ) {
559 cprintf("504 Unknown authentication method.\r\n");
567 * Implements the RSET (reset state) command.
568 * Currently this just zeroes out the state buffer. If pointers to data
569 * allocated with malloc() are ever placed in the state buffer, we have to
570 * be sure to free() them first!
572 * Set do_response to nonzero to output the SMTP RSET response code.
574 void smtp_rset(long offset, long do_response) {
575 citsmtp *sSMTP = SMTP;
578 * Our entire SMTP state is discarded when a RSET command is issued,
579 * but we need to preserve this one little piece of information, so
580 * we save it for later.
583 FlushStrBuf(sSMTP->Cmd);
584 FlushStrBuf(sSMTP->helo_node);
585 FlushStrBuf(sSMTP->from);
586 FlushStrBuf(sSMTP->recipients);
587 FlushStrBuf(sSMTP->OneRcpt);
589 sSMTP->command_state = 0;
590 sSMTP->number_of_recipients = 0;
591 sSMTP->delivery_mode = 0;
592 sSMTP->message_originated_locally = 0;
595 * we must remember is_lmtp & is_unfiltered.
599 * It is somewhat ambiguous whether we want to log out when a RSET
600 * command is issued. Here's the code to do it. It is commented out
601 * because some clients (such as Pine) issue RSET commands before
602 * each message, but still expect to be logged in.
604 * if (CC->logged_in) {
610 cprintf("250 Zap!\r\n");
615 * Clear out the portions of the state buffer that need to be cleared out
616 * after the DATA command finishes.
618 void smtp_data_clear(long offset, long flags)
620 citsmtp *sSMTP = SMTP;
622 FlushStrBuf(sSMTP->from);
623 FlushStrBuf(sSMTP->recipients);
624 FlushStrBuf(sSMTP->OneRcpt);
625 sSMTP->number_of_recipients = 0;
626 sSMTP->delivery_mode = 0;
627 sSMTP->message_originated_locally = 0;
631 * Implements the "MAIL FROM:" command
633 void smtp_mail(long offset, long flags) {
637 struct CitContext *CCC = CC;
638 citsmtp *sSMTP = SMTP;
640 if (StrLength(sSMTP->from) > 0) {
641 cprintf("503 Only one sender permitted\r\n");
645 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "From:", 5)) {
646 cprintf("501 Syntax error\r\n");
650 StrBufAppendBuf(sSMTP->from, sSMTP->Cmd, offset);
651 StrBufTrim(sSMTP->from);
652 if (strchr(ChrPtr(sSMTP->from), '<') != NULL) {
653 StrBufStripAllBut(sSMTP->from, '<', '>');
656 /* We used to reject empty sender names, until it was brought to our
657 * attention that RFC1123 5.2.9 requires that this be allowed. So now
658 * we allow it, but replace the empty string with a fake
659 * address so we don't have to contend with the empty string causing
660 * other code to fail when it's expecting something there.
662 if (StrLength(sSMTP->from) == 0) {
663 StrBufPlain(sSMTP->from, HKEY("someone@example.com"));
666 /* If this SMTP connection is from a logged-in user, force the 'from'
667 * to be the user's Internet e-mail address as Citadel knows it.
669 if (CCC->logged_in) {
670 StrBufPlain(sSMTP->from, CCC->cs_inet_email, -1);
671 cprintf("250 Sender ok <%s>\r\n", ChrPtr(sSMTP->from));
672 sSMTP->message_originated_locally = 1;
676 else if (sSMTP->is_lmtp) {
677 /* Bypass forgery checking for LMTP */
680 /* Otherwise, make sure outsiders aren't trying to forge mail from
681 * this system (unless, of course, c_allow_spoofing is enabled)
683 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
684 process_rfc822_addr(ChrPtr(sSMTP->from), user, node, name);
685 syslog(LOG_DEBUG, "Claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
686 ChrPtr(sSMTP->from), user, node, name
688 if (CtdlHostAlias(node) != hostalias_nomatch) {
689 cprintf("550 You must log in to send mail from %s\r\n", node);
690 FlushStrBuf(sSMTP->from);
691 syslog(LOG_DEBUG, "Rejecting unauthenticated mail from %s", node);
696 cprintf("250 Sender ok\r\n");
702 * Implements the "RCPT To:" command
704 void smtp_rcpt(long offset, long flags)
706 struct CitContext *CCC = CC;
707 char message_to_spammer[SIZ];
708 recptypes *valid = NULL;
709 citsmtp *sSMTP = SMTP;
711 if (StrLength(sSMTP->from) == 0) {
712 cprintf("503 Need MAIL before RCPT\r\n");
716 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "To:", 3)) {
717 cprintf("501 Syntax error\r\n");
721 if ( (sSMTP->is_msa) && (!CCC->logged_in) ) {
722 cprintf("550 You must log in to send mail on this port.\r\n");
723 FlushStrBuf(sSMTP->from);
726 FlushStrBuf(sSMTP->OneRcpt);
727 StrBufAppendBuf(sSMTP->OneRcpt, sSMTP->Cmd, offset + 3);
728 StrBufTrim(sSMTP->OneRcpt);
729 StrBufStripAllBut(sSMTP->OneRcpt, '<', '>');
731 if ( (StrLength(sSMTP->OneRcpt) + StrLength(sSMTP->recipients)) >= SIZ) {
732 cprintf("452 Too many recipients\r\n");
737 if ( (!CCC->logged_in) /* Don't RBL authenticated users */
738 && (!sSMTP->is_lmtp) ) { /* Don't RBL LMTP clients */
739 if (CtdlGetConfigInt("c_rbl_at_greeting") == 0) { /* Don't RBL again if we already did it */
740 if (rbl_check(message_to_spammer)) {
741 if (server_shutting_down)
742 cprintf("421 %s\r\n", message_to_spammer);
744 cprintf("550 %s\r\n", message_to_spammer);
745 /* no need to free_recipients(valid), it's not allocated yet */
751 valid = validate_recipients(
752 ChrPtr(sSMTP->OneRcpt),
753 smtp_get_Recipients(),
754 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
756 if (valid->num_error != 0) {
757 cprintf("550 %s\r\n", valid->errormsg);
758 free_recipients(valid);
762 if (valid->num_internet > 0) {
763 if (CCC->logged_in) {
764 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
765 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n",
766 ChrPtr(sSMTP->OneRcpt));
767 free_recipients(valid);
773 if (valid->num_internet > 0) {
774 if ( (sSMTP->message_originated_locally == 0)
775 && (sSMTP->is_lmtp == 0) ) {
776 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(sSMTP->OneRcpt));
777 free_recipients(valid);
782 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(sSMTP->OneRcpt));
783 if (StrLength(sSMTP->recipients) > 0) {
784 StrBufAppendBufPlain(sSMTP->recipients, HKEY(","), 0);
786 StrBufAppendBuf(sSMTP->recipients, sSMTP->OneRcpt, 0);
787 sSMTP->number_of_recipients ++;
789 free_recipients(valid);
797 * Implements the DATA command
799 void smtp_data(long offset, long flags)
801 struct CitContext *CCC = CC;
804 struct CtdlMessage *msg = NULL;
810 citsmtp *sSMTP = SMTP;
812 if (StrLength(sSMTP->from) == 0) {
813 cprintf("503 Need MAIL command first.\r\n");
817 if (sSMTP->number_of_recipients < 1) {
818 cprintf("503 Need RCPT command first.\r\n");
822 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
824 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
825 defbody = NewStrBufPlain(NULL, SIZ);
827 if (defbody != NULL) {
828 if (sSMTP->is_lmtp && (CCC->cs_UDSclientUID != -1)) {
831 "Received: from %s (Citadel from userid %ld)\n"
833 ChrPtr(sSMTP->helo_node),
834 (long int) CCC->cs_UDSclientUID,
835 CtdlGetConfigStr("c_fqdn"),
841 "Received: from %s (%s [%s])\n"
843 ChrPtr(sSMTP->helo_node),
846 CtdlGetConfigStr("c_fqdn"),
850 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1, NULL);
851 FreeStrBuf(&defbody);
853 cprintf("550 Unable to save message: internal error.\r\n");
857 syslog(LOG_DEBUG, "Converting message...");
858 msg = convert_internet_message_buf(&body);
860 /* If the user is locally authenticated, FORCE the From: header to
861 * show up as the real sender. Yes, this violates the RFC standard,
862 * but IT MAKES SENSE. If you prefer strict RFC adherence over
863 * common sense, you can disable this in the configuration.
865 * We also set the "message room name" ('O' field) to MAILROOM
866 * (which is Mail> on most systems) to prevent it from getting set
867 * to something ugly like "0000058008.Sent Items>" when the message
868 * is read with a Citadel client.
870 if ( (CCC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
873 if (!CM_IsEmpty(msg, erFc822Addr) &&
874 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
875 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
877 if (!IsEmptyStr(CCC->cs_inet_email))
878 validemail = strcmp(CCC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
880 (!IsEmptyStr(CCC->cs_inet_other_emails)))
882 int num_secondary_emails = 0;
884 num_secondary_emails = num_tokens(CCC->cs_inet_other_emails, '|');
885 for (i=0; i < num_secondary_emails && !validemail; ++i) {
887 extract_token(buf, CCC->cs_inet_other_emails,i,'|',sizeof CCC->cs_inet_other_emails);
888 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
893 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
894 syslog(LOG_ERR, "invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
895 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
899 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
900 CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
901 CM_SetField(msg, eOriginalRoom, HKEY(MAILROOM));
902 if (sSMTP->preferred_sender_name != NULL)
903 CM_SetField(msg, eAuthor, SKEY(sSMTP->preferred_sender_name));
905 CM_SetField(msg, eAuthor, CCC->user.fullname, strlen(CCC->user.fullname));
908 if (sSMTP->preferred_sender_email != NULL)
909 CM_SetField(msg, erFc822Addr, SKEY(sSMTP->preferred_sender_email));
911 CM_SetField(msg, erFc822Addr, CCC->cs_inet_email, strlen(CCC->cs_inet_email));
915 /* Set the "envelope from" address */
916 CM_SetField(msg, eMessagePath, SKEY(sSMTP->from));
918 /* Set the "envelope to" address */
919 CM_SetField(msg, eenVelopeTo, SKEY(sSMTP->recipients));
921 /* Submit the message into the Citadel system. */
922 valid = validate_recipients(
923 ChrPtr(sSMTP->recipients),
924 smtp_get_Recipients(),
925 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
928 /* If there are modules that want to scan this message before final
929 * submission (such as virus checkers or spam filters), call them now
930 * and give them an opportunity to reject the message.
932 if (sSMTP->is_unfiltered) {
936 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
939 if (scan_errors > 0) { /* We don't want this message! */
941 if (CM_IsEmpty(msg, eErrorMsg)) {
942 CM_SetField(msg, eErrorMsg, HKEY("Message rejected by filter"));
945 StrBufPrintf(sSMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
948 else { /* Ok, we'll accept this message. */
949 msgnum = CtdlSubmitMsg(msg, valid, "", 0);
951 StrBufPrintf(sSMTP->OneRcpt, "250 Message accepted.\r\n");
954 StrBufPrintf(sSMTP->OneRcpt, "550 Internal delivery error\r\n");
958 /* For SMTP and ESMTP, just print the result message. For LMTP, we
959 * have to print one result message for each recipient. Since there
960 * is nothing in Citadel which would cause different recipients to
961 * have different results, we can get away with just spitting out the
962 * same message once for each recipient.
964 if (sSMTP->is_lmtp) {
965 for (i=0; i<sSMTP->number_of_recipients; ++i) {
966 cputbuf(sSMTP->OneRcpt);
970 cputbuf(sSMTP->OneRcpt);
973 /* Write something to the syslog(which may or may not be where the
974 * rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
976 syslog((LOG_MAIL | LOG_INFO),
977 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
980 sSMTP->number_of_recipients,
983 ChrPtr(sSMTP->OneRcpt)
988 free_recipients(valid);
989 smtp_data_clear(0, 0); /* clear out the buffers now */
994 * implements the STARTTLS command
996 void smtp_starttls(long offset, long flags)
998 char ok_response[SIZ];
999 char nosup_response[SIZ];
1000 char error_response[SIZ];
1002 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
1003 sprintf(nosup_response, "554 TLS not supported here\r\n");
1004 sprintf(error_response, "554 Internal error\r\n");
1005 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
1011 * Main command loop for SMTP server sessions.
1013 void smtp_command_loop(void)
1015 static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
1016 struct CitContext *CCC = CC;
1017 citsmtp *sSMTP = SMTP;
1018 const char *pch, *pchs;
1020 char CMD[MaxSMTPCmdLen + 1];
1022 if (sSMTP == NULL) {
1023 syslog(LOG_EMERG, "Session SMTP data is null. WTF? We will crash now.");
1024 return cit_panic_backtrace (0);
1027 time(&CCC->lastcmd);
1028 if (CtdlClientGetLine(sSMTP->Cmd) < 1) {
1029 syslog(LOG_CRIT, "SMTP: client disconnected: ending session.");
1030 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1033 syslog(LOG_DEBUG, "SMTP server: %s", ChrPtr(sSMTP->Cmd));
1035 if (sSMTP->command_state == smtp_user) {
1036 if (!strncmp(ChrPtr(sSMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len))
1037 smtp_try_plain(0, 0);
1043 else if (sSMTP->command_state == smtp_password) {
1044 smtp_get_pass(0, 0);
1048 else if (sSMTP->command_state == smtp_plain) {
1049 smtp_try_plain(0, 0);
1053 pchs = pch = ChrPtr(sSMTP->Cmd);
1055 while ((*pch != '\0') &&
1057 (pch - pchs <= MaxSMTPCmdLen))
1059 CMD[i] = toupper(*pch);
1065 if ((*pch == '\0') ||
1070 if (GetHash(SMTPCmds, CMD, i, &v) &&
1073 smtp_handler_hook *h = (smtp_handler_hook*) v;
1075 if (isblank(pchs[i]))
1083 cprintf("502 I'm afraid I can't do that.\r\n");
1086 void smtp_noop(long offest, long Flags)
1088 cprintf("250 NOOP\r\n");
1091 void smtp_quit(long offest, long Flags)
1093 cprintf("221 Goodbye...\r\n");
1094 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1097 /*****************************************************************************/
1098 /* MODULE INITIALIZATION STUFF */
1099 /*****************************************************************************/
1101 * This cleanup function blows away the temporary memory used by
1104 void smtp_cleanup_function(void)
1106 citsmtp *sSMTP = SMTP;
1107 struct CitContext *CCC = CC;
1109 /* Don't do this stuff if this is not an SMTP session! */
1110 if (CCC->h_command_function != smtp_command_loop) return;
1112 syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
1114 FreeStrBuf(&sSMTP->Cmd);
1115 FreeStrBuf(&sSMTP->helo_node);
1116 FreeStrBuf(&sSMTP->from);
1117 FreeStrBuf(&sSMTP->recipients);
1118 FreeStrBuf(&sSMTP->OneRcpt);
1119 FreeStrBuf(&sSMTP->preferred_sender_email);
1120 FreeStrBuf(&sSMTP->preferred_sender_name);
1125 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1126 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1127 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1128 const char *CitadelServiceSMTP_LMTP="LMTP";
1129 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1132 CTDL_MODULE_INIT(smtp)
1136 SMTPCmds = NewHash(1, NULL);
1138 RegisterSmtpCMD("AUTH", smtp_auth, 0);
1139 RegisterSmtpCMD("DATA", smtp_data, 0);
1140 RegisterSmtpCMD("HELO", smtp_hello, HELO);
1141 RegisterSmtpCMD("EHLO", smtp_hello, EHLO);
1142 RegisterSmtpCMD("LHLO", smtp_hello, LHLO);
1143 RegisterSmtpCMD("HELP", smtp_help, 0);
1144 RegisterSmtpCMD("MAIL", smtp_mail, 0);
1145 RegisterSmtpCMD("NOOP", smtp_noop, 0);
1146 RegisterSmtpCMD("QUIT", smtp_quit, 0);
1147 RegisterSmtpCMD("RCPT", smtp_rcpt, 0);
1148 RegisterSmtpCMD("RSET", smtp_rset, 1);
1150 RegisterSmtpCMD("STARTTLS", smtp_starttls, 0);
1154 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"), /* SMTP MTA */
1159 CitadelServiceSMTP_MTA);
1162 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"), /* SMTPS MTA */
1167 CitadelServiceSMTPS_MTA);
1170 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"), /* SMTP MSA */
1175 CitadelServiceSMTP_MSA);
1177 CtdlRegisterServiceHook(0, /* local LMTP */
1182 CitadelServiceSMTP_LMTP);
1184 CtdlRegisterServiceHook(0, /* local LMTP */
1185 file_lmtp_unfiltered_socket,
1186 lmtp_unfiltered_greeting,
1189 CitadelServiceSMTP_LMTP_UNF);
1191 CtdlRegisterCleanupHook(smtp_cleanup);
1192 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1195 /* return our module name for the log */