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-2021 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>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <arpa/inet.h>
53 #include <libcitadel.h>
56 #include "citserver.h"
64 #include "internet_addressing.h"
67 #include "clientsocket.h"
68 #include "locate_host.h"
69 #include "citadel_dirs.h"
70 #include "ctdl_module.h"
72 #include "smtp_util.h"
74 enum { /* Command states for login authentication */
87 typedef void (*smtp_handler)(long offest, long Flags);
89 typedef struct _smtp_handler_hook {
94 int EnableSMTPLog = 0;
96 HashList *SMTPCmds = NULL;
97 #define MaxSMTPCmdLen 10
99 #define RegisterSmtpCMD(First, H, Flags) registerSmtpCMD(HKEY(First), H, Flags)
100 void registerSmtpCMD(const char *First, long FLen, smtp_handler H, int Flags) {
101 smtp_handler_hook *h;
103 if (FLen >= MaxSMTPCmdLen) {
107 h = (smtp_handler_hook*) malloc(sizeof(smtp_handler_hook));
108 memset(h, 0, sizeof(smtp_handler_hook));
112 Put(SMTPCmds, First, FLen, h, NULL);
117 * Here's where our SMTP session begins its happy day.
119 void smtp_greeting(int is_msa) {
120 char message_to_spammer[1024];
122 strcpy(CC->cs_clientname, "SMTP session");
123 CC->internal_pgm = 1;
124 CC->cs_flags |= CS_STEALTH;
125 CC->session_specific_data = malloc(sizeof(citsmtp));
126 memset(SMTP, 0, sizeof(citsmtp));
127 SMTP->is_msa = is_msa;
128 SMTP->Cmd = NewStrBufPlain(NULL, SIZ);
129 SMTP->helo_node = NewStrBuf();
130 SMTP->from = NewStrBufPlain(NULL, SIZ);
131 SMTP->recipients = NewStrBufPlain(NULL, SIZ);
132 SMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
133 SMTP->preferred_sender_email = NULL;
134 SMTP->preferred_sender_name = NULL;
136 /* If this config option is set, reject connections from problem
137 * addresses immediately instead of after they execute a RCPT
139 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (SMTP->is_msa == 0) ) {
140 if (rbl_check(CC->cs_addr, message_to_spammer)) {
141 if (server_shutting_down)
142 cprintf("421 %s\r\n", message_to_spammer);
144 cprintf("550 %s\r\n", message_to_spammer);
145 CC->kill_me = KILLME_SPAMMER;
146 /* no need to free_recipients(valid), it's not allocated yet */
151 /* Otherwise we're either clean or we check later. */
153 if (CC->nologin==1) {
154 cprintf("451 Too many connections are already open; please try again later.\r\n");
155 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
156 /* no need to free_recipients(valid), it's not allocated yet */
160 /* Note: the FQDN *must* appear as the first thing after the 220 code.
161 * Some clients (including citmail.c) depend on it being there.
163 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
168 * SMTPS is just like SMTP, except it goes crypto right away.
170 void smtps_greeting(void) {
171 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
173 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
180 * SMTP MSA port requires authentication.
182 void smtp_msa_greeting(void) {
188 * LMTP is like SMTP but with some extra bonus footage added.
190 void lmtp_greeting(void) {
198 * Generic SMTP MTA greeting
200 void smtp_mta_greeting(void) {
206 * We also have an unfiltered LMTP socket that bypasses spam filters.
208 void lmtp_unfiltered_greeting(void) {
211 SMTP->is_unfiltered = 1;
216 * Login greeting common to all auth methods
218 void smtp_auth_greeting(long offset, long Flags) {
219 cprintf("235 Hello, %s\r\n", CC->user.fullname);
220 syslog(LOG_INFO, "serv_smtp: SMTP authenticated %s", CC->user.fullname);
221 CC->internal_pgm = 0;
222 CC->cs_flags &= ~CS_STEALTH;
227 * Implement HELO and EHLO commands.
229 * which_command: 0=HELO, 1=EHLO, 2=LHLO
231 void smtp_hello(long offset, long which_command) {
233 StrBufAppendBuf (SMTP->helo_node, SMTP->Cmd, offset);
235 if ( (which_command != LHLO) && (SMTP->is_lmtp) ) {
236 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
240 if ( (which_command == LHLO) && (SMTP->is_lmtp == 0) ) {
241 cprintf("500 LHLO is only allowed when running LMTP\r\n");
245 if (which_command == HELO) {
246 cprintf("250 Hello %s (%s [%s])\r\n",
247 ChrPtr(SMTP->helo_node),
253 if (which_command == EHLO) {
254 cprintf("250-Hello %s (%s [%s])\r\n",
255 ChrPtr(SMTP->helo_node),
261 cprintf("250-Greetings and joyous salutations.\r\n");
263 cprintf("250-HELP\r\n");
264 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
268 * Offer TLS, but only if TLS is not already active.
269 * Furthermore, only offer TLS when running on
270 * the SMTP-MSA port, not on the SMTP-MTA port, due to
271 * questionable reliability of TLS in certain sending MTA's.
273 if ( (!CC->redirect_ssl) && (SMTP->is_msa) ) {
274 cprintf("250-STARTTLS\r\n");
276 #endif /* HAVE_OPENSSL */
278 cprintf("250-AUTH LOGIN PLAIN\r\n"
279 "250-AUTH=LOGIN PLAIN\r\n"
287 * Backend function for smtp_webcit_preferences_hack().
288 * Look at a message and determine if it's the preferences file.
290 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
291 struct CtdlMessage *msg;
292 char **webcit_conf = (char **) userdata;
295 return; // already got it
298 msg = CtdlFetchMessage(msgnum, 1);
303 if ( !CM_IsEmpty(msg, eMsgSubject) &&
304 (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __")))
306 /* This is it! Change ownership of the message text so it doesn't get freed. */
307 *webcit_conf = (char *)msg->cm_fields[eMesageText];
308 msg->cm_fields[eMesageText] = NULL;
315 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
316 * stored in the account's WebCit configuration. We have to fetch it now.
318 void smtp_webcit_preferences_hack(void) {
319 char config_roomname[ROOMNAMELEN];
320 char *webcit_conf = NULL;
322 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CC->user.usernum, USERCONFIGROOM);
323 if (CtdlGetRoom(&CC->room, config_roomname) != 0) {
328 * Find the WebCit configuration message
331 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
337 /* Parse the webcit configuration and attempt to do something useful with it */
338 char *str = webcit_conf;
340 char *this_line = NULL;
341 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
343 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
344 SMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
346 if (!strncasecmp(this_line, "defaultname|", 12)) {
347 SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
349 if ((!strncasecmp(this_line, "defaultname|", 12)) && (SMTP->preferred_sender_name == NULL)) {
350 SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
360 * Implement HELP command.
362 void smtp_help(long offset, long Flags) {
363 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
370 void smtp_get_user(long offset)
374 StrBufDecodeBase64(SMTP->Cmd);
376 if (CtdlLoginExistingUser(ChrPtr(SMTP->Cmd)) == login_ok) {
377 size_t len = CtdlEncodeBase64(buf, "Password:", 9, 0);
379 if (buf[len - 1] == '\n') {
382 cprintf("334 %s\r\n", buf);
383 SMTP->command_state = smtp_password;
386 cprintf("500 No such user.\r\n");
387 SMTP->command_state = smtp_command;
395 void smtp_get_pass(long offset, long Flags)
399 memset(password, 0, sizeof(password));
400 StrBufDecodeBase64(SMTP->Cmd);
401 syslog(LOG_DEBUG, "serv_smtp: trying <%s>", password);
402 if (CtdlTryPassword(SKEY(SMTP->Cmd)) == pass_ok) {
403 smtp_auth_greeting(offset, Flags);
406 cprintf("535 Authentication failed.\r\n");
408 SMTP->command_state = smtp_command;
413 * Back end for PLAIN auth method (either inline or multistate)
415 void smtp_try_plain(long offset, long Flags)
417 const char*decoded_authstring;
418 char ident[256] = "";
427 memset(pass, 0, sizeof(pass));
428 decoded_len = StrBufDecodeBase64(SMTP->Cmd);
432 decoded_authstring = ChrPtr(SMTP->Cmd);
434 len = safestrncpy(ident, decoded_authstring, sizeof ident);
436 decoded_len -= len - 1;
437 decoded_authstring += len + 1;
441 len = safestrncpy(user, decoded_authstring, sizeof user);
443 decoded_authstring += len + 1;
444 decoded_len -= len - 1;
449 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
452 plen = sizeof(pass) - 1;
456 SMTP->command_state = smtp_command;
458 if (!IsEmptyStr(ident)) {
459 result = CtdlLoginExistingUser(ident);
462 result = CtdlLoginExistingUser(user);
465 if (result == login_ok) {
466 if (CtdlTryPassword(pass, plen) == pass_ok) {
467 smtp_webcit_preferences_hack();
468 smtp_auth_greeting(offset, Flags);
472 cprintf("504 Authentication failed.\r\n");
477 * Attempt to perform authenticated SMTP
479 void smtp_auth(long offset, long Flags)
481 char username_prompt[64];
483 char encoded_authstring[1024];
486 cprintf("504 Already logged in.\r\n");
490 extract_token(method, ChrPtr(SMTP->Cmd) + offset, 0, ' ', sizeof method);
492 if (!strncasecmp(method, "login", 5) ) {
493 if (StrLength(SMTP->Cmd) - offset >= 7) {
497 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
498 if (username_prompt[len - 1] == '\n') {
499 username_prompt[len - 1] = '\0';
501 cprintf("334 %s\r\n", username_prompt);
502 SMTP->command_state = smtp_user;
507 if (!strncasecmp(method, "plain", 5) ) {
509 if (num_tokens(ChrPtr(SMTP->Cmd) + offset, ' ') < 2) {
511 SMTP->command_state = smtp_plain;
515 len = extract_token(encoded_authstring,
516 ChrPtr(SMTP->Cmd) + offset,
518 sizeof encoded_authstring);
519 StrBufPlain(SMTP->Cmd, encoded_authstring, len);
520 smtp_try_plain(0, Flags);
524 if (strncasecmp(method, "login", 5) ) {
525 cprintf("504 Unknown authentication method.\r\n");
533 * Implements the RSET (reset state) command.
534 * Currently this just zeroes out the state buffer. If pointers to data
535 * allocated with malloc() are ever placed in the state buffer, we have to
536 * be sure to free() them first!
538 * Set do_response to nonzero to output the SMTP RSET response code.
540 void smtp_rset(long offset, long do_response) {
542 * Our entire SMTP state is discarded when a RSET command is issued,
543 * but we need to preserve this one little piece of information, so
544 * we save it for later.
547 FlushStrBuf(SMTP->Cmd);
548 FlushStrBuf(SMTP->helo_node);
549 FlushStrBuf(SMTP->from);
550 FlushStrBuf(SMTP->recipients);
551 FlushStrBuf(SMTP->OneRcpt);
553 SMTP->command_state = 0;
554 SMTP->number_of_recipients = 0;
555 SMTP->delivery_mode = 0;
556 SMTP->message_originated_locally = 0;
559 * we must remember is_lmtp & is_unfiltered.
563 * It is somewhat ambiguous whether we want to log out when a RSET
564 * command is issued. Here's the code to do it. It is commented out
565 * because some clients (such as Pine) issue RSET commands before
566 * each message, but still expect to be logged in.
568 * if (CC->logged_in) {
574 cprintf("250 Zap!\r\n");
579 * Clear out the portions of the state buffer that need to be cleared out
580 * after the DATA command finishes.
582 void smtp_data_clear(long offset, long flags)
584 FlushStrBuf(SMTP->from);
585 FlushStrBuf(SMTP->recipients);
586 FlushStrBuf(SMTP->OneRcpt);
587 SMTP->number_of_recipients = 0;
588 SMTP->delivery_mode = 0;
589 SMTP->message_originated_locally = 0;
593 * Implements the "MAIL FROM:" command
595 void smtp_mail(long offset, long flags) {
600 if (StrLength(SMTP->from) > 0) {
601 cprintf("503 Only one sender permitted\r\n");
605 if (strncasecmp(ChrPtr(SMTP->Cmd) + offset, "From:", 5)) {
606 cprintf("501 Syntax error\r\n");
610 StrBufAppendBuf(SMTP->from, SMTP->Cmd, offset);
611 StrBufTrim(SMTP->from);
612 if (strchr(ChrPtr(SMTP->from), '<') != NULL) {
613 StrBufStripAllBut(SMTP->from, '<', '>');
616 /* We used to reject empty sender names, until it was brought to our
617 * attention that RFC1123 5.2.9 requires that this be allowed. So now
618 * we allow it, but replace the empty string with a fake
619 * address so we don't have to contend with the empty string causing
620 * other code to fail when it's expecting something there.
622 if (StrLength(SMTP->from) == 0) {
623 StrBufPlain(SMTP->from, HKEY("someone@example.com"));
626 /* If this SMTP connection is from a logged-in user, force the 'from'
627 * to be the user's Internet e-mail address as Citadel knows it.
630 StrBufPlain(SMTP->from, CC->cs_inet_email, -1);
631 cprintf("250 Sender ok <%s>\r\n", ChrPtr(SMTP->from));
632 SMTP->message_originated_locally = 1;
636 else if (SMTP->is_lmtp) {
637 /* Bypass forgery checking for LMTP */
640 /* Otherwise, make sure outsiders aren't trying to forge mail from
641 * this system (unless, of course, c_allow_spoofing is enabled)
643 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
644 process_rfc822_addr(ChrPtr(SMTP->from), user, node, name);
645 syslog(LOG_DEBUG, "serv_smtp: claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
646 ChrPtr(SMTP->from), user, node, name
648 if (CtdlHostAlias(node) != hostalias_nomatch) {
649 cprintf("550 You must log in to send mail from %s\r\n", node);
650 FlushStrBuf(SMTP->from);
651 syslog(LOG_DEBUG, "serv_smtp: rejecting unauthenticated mail from %s", node);
656 cprintf("250 Sender ok\r\n");
662 * Implements the "RCPT To:" command
664 void smtp_rcpt(long offset, long flags)
666 char message_to_spammer[SIZ];
667 struct recptypes *valid = NULL;
669 if (StrLength(SMTP->from) == 0) {
670 cprintf("503 Need MAIL before RCPT\r\n");
674 if (strncasecmp(ChrPtr(SMTP->Cmd) + offset, "To:", 3)) {
675 cprintf("501 Syntax error\r\n");
679 if ( (SMTP->is_msa) && (!CC->logged_in) ) {
680 cprintf("550 You must log in to send mail on this port.\r\n");
681 FlushStrBuf(SMTP->from);
684 FlushStrBuf(SMTP->OneRcpt);
685 StrBufAppendBuf(SMTP->OneRcpt, SMTP->Cmd, offset + 3);
686 StrBufTrim(SMTP->OneRcpt);
687 StrBufStripAllBut(SMTP->OneRcpt, '<', '>');
689 if ( (StrLength(SMTP->OneRcpt) + StrLength(SMTP->recipients)) >= SIZ) {
690 cprintf("452 Too many recipients\r\n");
695 if ( (!CC->logged_in) /* Don't RBL authenticated users */
696 && (!SMTP->is_lmtp) ) { /* Don't RBL LMTP clients */
697 if (CtdlGetConfigInt("c_rbl_at_greeting") == 0) { /* Don't RBL again if we already did it */
698 if (rbl_check(CC->cs_addr, message_to_spammer)) {
699 if (server_shutting_down)
700 cprintf("421 %s\r\n", message_to_spammer);
702 cprintf("550 %s\r\n", message_to_spammer);
703 /* no need to free_recipients(valid), it's not allocated yet */
709 valid = validate_recipients(
710 ChrPtr(SMTP->OneRcpt),
711 smtp_get_Recipients(),
712 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
714 if (valid->num_error != 0) {
715 cprintf("550 %s\r\n", valid->errormsg);
716 free_recipients(valid);
720 if (valid->num_internet > 0) {
722 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
723 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n",
724 ChrPtr(SMTP->OneRcpt));
725 free_recipients(valid);
731 if (valid->num_internet > 0) {
732 if ( (SMTP->message_originated_locally == 0)
733 && (SMTP->is_lmtp == 0) ) {
734 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(SMTP->OneRcpt));
735 free_recipients(valid);
740 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(SMTP->OneRcpt));
741 if (StrLength(SMTP->recipients) > 0) {
742 StrBufAppendBufPlain(SMTP->recipients, HKEY(","), 0);
744 StrBufAppendBuf(SMTP->recipients, SMTP->OneRcpt, 0);
745 SMTP->number_of_recipients ++;
747 free_recipients(valid);
755 * Implements the DATA command
757 void smtp_data(long offset, long flags)
761 struct CtdlMessage *msg = NULL;
764 struct recptypes *valid;
768 if (StrLength(SMTP->from) == 0) {
769 cprintf("503 Need MAIL command first.\r\n");
773 if (SMTP->number_of_recipients < 1) {
774 cprintf("503 Need RCPT command first.\r\n");
778 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
780 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
781 defbody = NewStrBufPlain(NULL, SIZ);
783 if (defbody != NULL) {
784 if (SMTP->is_lmtp && (CC->cs_UDSclientUID != -1)) {
787 "Received: from %s (Citadel from userid %ld)\n"
789 ChrPtr(SMTP->helo_node),
790 (long int) CC->cs_UDSclientUID,
791 CtdlGetConfigStr("c_fqdn"),
797 "Received: from %s (%s [%s])\n"
799 ChrPtr(SMTP->helo_node),
802 CtdlGetConfigStr("c_fqdn"),
806 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1);
807 FreeStrBuf(&defbody);
809 cprintf("550 Unable to save message: internal error.\r\n");
813 syslog(LOG_DEBUG, "serv_smtp: converting message...");
814 msg = convert_internet_message_buf(&body);
816 /* If the user is locally authenticated, FORCE the From: header to
817 * show up as the real sender. Yes, this violates the RFC standard,
818 * but IT MAKES SENSE. If you prefer strict RFC adherence over
819 * common sense, you can disable this in the configuration.
821 * We also set the "message room name" ('O' field) to MAILROOM
822 * (which is Mail> on most systems) to prevent it from getting set
823 * to something ugly like "0000058008.Sent Items>" when the message
824 * is read with a Citadel client.
826 if ( (CC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
829 if (!CM_IsEmpty(msg, erFc822Addr) &&
830 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
831 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
833 if (!IsEmptyStr(CC->cs_inet_email))
834 validemail = strcmp(CC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
836 (!IsEmptyStr(CC->cs_inet_other_emails)))
838 int num_secondary_emails = 0;
840 num_secondary_emails = num_tokens(CC->cs_inet_other_emails, '|');
841 for (i=0; i < num_secondary_emails && !validemail; ++i) {
843 extract_token(buf, CC->cs_inet_other_emails,i,'|',sizeof CC->cs_inet_other_emails);
844 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
849 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
850 syslog(LOG_ERR, "serv_smtp: invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
851 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
855 CM_SetField(msg, eOriginalRoom, HKEY(MAILROOM));
856 if (SMTP->preferred_sender_name != NULL)
857 CM_SetField(msg, eAuthor, SKEY(SMTP->preferred_sender_name));
859 CM_SetField(msg, eAuthor, CC->user.fullname, strlen(CC->user.fullname));
862 if (SMTP->preferred_sender_email != NULL) {
863 CM_SetField(msg, erFc822Addr, SKEY(SMTP->preferred_sender_email));
866 CM_SetField(msg, erFc822Addr, CC->cs_inet_email, strlen(CC->cs_inet_email));
871 /* Set the "envelope from" address */
872 CM_SetField(msg, eMessagePath, SKEY(SMTP->from));
874 /* Set the "envelope to" address */
875 CM_SetField(msg, eenVelopeTo, SKEY(SMTP->recipients));
877 /* Submit the message into the Citadel system. */
878 valid = validate_recipients(
879 ChrPtr(SMTP->recipients),
880 smtp_get_Recipients(),
881 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
884 /* If there are modules that want to scan this message before final
885 * submission (such as virus checkers or spam filters), call them now
886 * and give them an opportunity to reject the message.
888 if (SMTP->is_unfiltered) {
892 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
895 if (scan_errors > 0) { /* We don't want this message! */
897 if (CM_IsEmpty(msg, eErrorMsg)) {
898 CM_SetField(msg, eErrorMsg, HKEY("Message rejected by filter"));
901 StrBufPrintf(SMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
904 else { /* Ok, we'll accept this message. */
905 msgnum = CtdlSubmitMsg(msg, valid, "");
907 StrBufPrintf(SMTP->OneRcpt, "250 Message accepted.\r\n");
910 StrBufPrintf(SMTP->OneRcpt, "550 Internal delivery error\r\n");
914 /* For SMTP and ESMTP, just print the result message. For LMTP, we
915 * have to print one result message for each recipient. Since there
916 * is nothing in Citadel which would cause different recipients to
917 * have different results, we can get away with just spitting out the
918 * same message once for each recipient.
921 for (i=0; i<SMTP->number_of_recipients; ++i) {
922 cputbuf(SMTP->OneRcpt);
926 cputbuf(SMTP->OneRcpt);
929 /* Write something to the syslog(which may or may not be where the
930 * rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
932 syslog((LOG_MAIL | LOG_INFO),
933 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
936 SMTP->number_of_recipients,
939 ChrPtr(SMTP->OneRcpt)
944 free_recipients(valid);
945 smtp_data_clear(0, 0); /* clear out the buffers now */
950 * implements the STARTTLS command
952 void smtp_starttls(long offset, long flags)
954 char ok_response[SIZ];
955 char nosup_response[SIZ];
956 char error_response[SIZ];
958 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
959 sprintf(nosup_response, "554 TLS not supported here\r\n");
960 sprintf(error_response, "554 Internal error\r\n");
961 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
967 * Main command loop for SMTP server sessions.
969 void smtp_command_loop(void) {
970 static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
971 const char *pch, *pchs;
973 char CMD[MaxSMTPCmdLen + 1];
976 syslog(LOG_ERR, "serv_smtp: Session SMTP data is null. WTF? We will crash now.");
981 if (CtdlClientGetLine(SMTP->Cmd) < 1) {
982 syslog(LOG_INFO, "SMTP: client disconnected: ending session.");
983 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
986 syslog(LOG_DEBUG, "serv_smtp: %s", ChrPtr(SMTP->Cmd));
988 if (SMTP->command_state == smtp_user) {
989 if (!strncmp(ChrPtr(SMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len)) {
990 smtp_try_plain(0, 0);
998 else if (SMTP->command_state == smtp_password) {
1003 else if (SMTP->command_state == smtp_plain) {
1004 smtp_try_plain(0, 0);
1008 pchs = pch = ChrPtr(SMTP->Cmd);
1010 while ((*pch != '\0') &&
1012 (pch - pchs <= MaxSMTPCmdLen))
1014 CMD[i] = toupper(*pch);
1020 if ((*pch == '\0') ||
1025 if (GetHash(SMTPCmds, CMD, i, &v) &&
1028 smtp_handler_hook *h = (smtp_handler_hook*) v;
1030 if (isblank(pchs[i]))
1038 cprintf("502 I'm afraid I can't do that.\r\n");
1041 void smtp_noop(long offest, long Flags)
1043 cprintf("250 NOOP\r\n");
1046 void smtp_quit(long offest, long Flags)
1048 cprintf("221 Goodbye...\r\n");
1049 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1052 /*****************************************************************************/
1053 /* MODULE INITIALIZATION STUFF */
1054 /*****************************************************************************/
1056 * This cleanup function blows away the temporary memory used by
1059 void smtp_cleanup_function(void)
1061 /* Don't do this stuff if this is not an SMTP session! */
1062 if (CC->h_command_function != smtp_command_loop) return;
1064 syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
1066 FreeStrBuf(&SMTP->Cmd);
1067 FreeStrBuf(&SMTP->helo_node);
1068 FreeStrBuf(&SMTP->from);
1069 FreeStrBuf(&SMTP->recipients);
1070 FreeStrBuf(&SMTP->OneRcpt);
1071 FreeStrBuf(&SMTP->preferred_sender_email);
1072 FreeStrBuf(&SMTP->preferred_sender_name);
1077 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1078 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1079 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1080 const char *CitadelServiceSMTP_LMTP="LMTP";
1081 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1084 CTDL_MODULE_INIT(smtp)
1087 SMTPCmds = NewHash(1, NULL);
1089 RegisterSmtpCMD("AUTH", smtp_auth, 0);
1090 RegisterSmtpCMD("DATA", smtp_data, 0);
1091 RegisterSmtpCMD("HELO", smtp_hello, HELO);
1092 RegisterSmtpCMD("EHLO", smtp_hello, EHLO);
1093 RegisterSmtpCMD("LHLO", smtp_hello, LHLO);
1094 RegisterSmtpCMD("HELP", smtp_help, 0);
1095 RegisterSmtpCMD("MAIL", smtp_mail, 0);
1096 RegisterSmtpCMD("NOOP", smtp_noop, 0);
1097 RegisterSmtpCMD("QUIT", smtp_quit, 0);
1098 RegisterSmtpCMD("RCPT", smtp_rcpt, 0);
1099 RegisterSmtpCMD("RSET", smtp_rset, 1);
1101 RegisterSmtpCMD("STARTTLS", smtp_starttls, 0);
1105 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"), /* SMTP MTA */
1110 CitadelServiceSMTP_MTA);
1113 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"), /* SMTPS MTA */
1118 CitadelServiceSMTPS_MTA);
1121 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"), /* SMTP MSA */
1126 CitadelServiceSMTP_MSA);
1128 CtdlRegisterServiceHook(0, /* local LMTP */
1133 CitadelServiceSMTP_LMTP);
1135 CtdlRegisterServiceHook(0, /* local LMTP */
1136 file_lmtp_unfiltered_socket,
1137 lmtp_unfiltered_greeting,
1140 CitadelServiceSMTP_LMTP_UNF);
1142 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1145 /* return our module name for the log */