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"
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)
119 cit_panic_backtrace (0);
121 h = (smtp_handler_hook*) malloc(sizeof(smtp_handler_hook));
122 memset(h, 0, sizeof(smtp_handler_hook));
126 Put(SMTPCmds, First, FLen, h, NULL);
130 void smtp_cleanup(void)
132 DeleteHash(&SMTPCmds);
136 * Here's where our SMTP session begins its happy day.
138 void smtp_greeting(int is_msa)
141 char message_to_spammer[1024];
143 strcpy(CC->cs_clientname, "SMTP session");
144 CC->internal_pgm = 1;
145 CC->cs_flags |= CS_STEALTH;
146 CC->session_specific_data = malloc(sizeof(citsmtp));
147 memset(SMTP, 0, sizeof(citsmtp));
149 sSMTP->is_msa = is_msa;
150 sSMTP->Cmd = NewStrBufPlain(NULL, SIZ);
151 sSMTP->helo_node = NewStrBuf();
152 sSMTP->from = NewStrBufPlain(NULL, SIZ);
153 sSMTP->recipients = NewStrBufPlain(NULL, SIZ);
154 sSMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
155 sSMTP->preferred_sender_email = NULL;
156 sSMTP->preferred_sender_name = NULL;
158 /* If this config option is set, reject connections from problem
159 * addresses immediately instead of after they execute a RCPT
161 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (sSMTP->is_msa == 0) ) {
162 if (rbl_check(message_to_spammer)) {
163 if (server_shutting_down)
164 cprintf("421 %s\r\n", message_to_spammer);
166 cprintf("550 %s\r\n", message_to_spammer);
167 CC->kill_me = KILLME_SPAMMER;
168 /* no need to free_recipients(valid), it's not allocated yet */
173 /* Otherwise we're either clean or we check later. */
175 if (CC->nologin==1) {
176 cprintf("451 Too many connections are already open; please try again later.\r\n");
177 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
178 /* no need to free_recipients(valid), it's not allocated yet */
182 /* Note: the FQDN *must* appear as the first thing after the 220 code.
183 * Some clients (including citmail.c) depend on it being there.
185 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
190 * SMTPS is just like SMTP, except it goes crypto right away.
192 void smtps_greeting(void) {
193 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
195 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
202 * SMTP MSA port requires authentication.
204 void smtp_msa_greeting(void) {
210 * LMTP is like SMTP but with some extra bonus footage added.
212 void lmtp_greeting(void) {
220 * Generic SMTP MTA greeting
222 void smtp_mta_greeting(void) {
228 * We also have an unfiltered LMTP socket that bypasses spam filters.
230 void lmtp_unfiltered_greeting(void) {
236 sSMTP->is_unfiltered = 1;
241 * Login greeting common to all auth methods
243 void smtp_auth_greeting(long offset, long Flags) {
244 struct CitContext *CCC = CC;
245 cprintf("235 Hello, %s\r\n", CCC->user.fullname);
246 syslog(LOG_NOTICE, "SMTP authenticated %s", CCC->user.fullname);
247 CCC->internal_pgm = 0;
248 CCC->cs_flags &= ~CS_STEALTH;
253 * Implement HELO and EHLO commands.
255 * which_command: 0=HELO, 1=EHLO, 2=LHLO
257 void smtp_hello(long offset, long which_command)
259 struct CitContext *CCC = CC;
260 citsmtp *sSMTP = SMTP;
262 StrBufAppendBuf (sSMTP->helo_node, sSMTP->Cmd, offset);
264 if ( (which_command != LHLO) && (sSMTP->is_lmtp) ) {
265 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
269 if ( (which_command == LHLO) && (sSMTP->is_lmtp == 0) ) {
270 cprintf("500 LHLO is only allowed when running LMTP\r\n");
274 if (which_command == HELO) {
275 cprintf("250 Hello %s (%s [%s])\r\n",
276 ChrPtr(sSMTP->helo_node),
282 if (which_command == EHLO) {
283 cprintf("250-Hello %s (%s [%s])\r\n",
284 ChrPtr(sSMTP->helo_node),
290 cprintf("250-Greetings and joyous salutations.\r\n");
292 cprintf("250-HELP\r\n");
293 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
297 * Offer TLS, but only if TLS is not already active.
298 * Furthermore, only offer TLS when running on
299 * the SMTP-MSA port, not on the SMTP-MTA port, due to
300 * questionable reliability of TLS in certain sending MTA's.
302 if ( (!CCC->redirect_ssl) && (sSMTP->is_msa) ) {
303 cprintf("250-STARTTLS\r\n");
305 #endif /* HAVE_OPENSSL */
307 cprintf("250-AUTH LOGIN PLAIN\r\n"
308 "250-AUTH=LOGIN PLAIN\r\n"
316 * Backend function for smtp_webcit_preferences_hack().
317 * Look at a message and determine if it's the preferences file.
319 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
320 struct CtdlMessage *msg;
321 char **webcit_conf = (char **) userdata;
324 return; // already got it
327 msg = CtdlFetchMessage(msgnum, 1, 1);
332 if ( !CM_IsEmpty(msg, eMsgSubject) &&
333 (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __")))
335 /* This is it! Change ownership of the message text so it doesn't get freed. */
336 *webcit_conf = (char *)msg->cm_fields[eMesageText];
337 msg->cm_fields[eMesageText] = NULL;
344 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
345 * stored in the account's WebCit configuration. We have to fetch it now.
347 void smtp_webcit_preferences_hack(void) {
348 struct CitContext *CCC = CC;
349 char config_roomname[ROOMNAMELEN];
350 char *webcit_conf = NULL;
351 citsmtp *sSMTP = SMTP;
353 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CCC->user.usernum, USERCONFIGROOM);
354 if (CtdlGetRoom(&CCC->room, config_roomname) != 0) {
359 * Find the WebCit configuration message
362 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
368 /* Parse the webcit configuration and attempt to do something useful with it */
369 char *str = webcit_conf;
371 char *this_line = NULL;
372 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
374 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
375 sSMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
377 if (!strncasecmp(this_line, "defaultname|", 12)) {
378 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
380 if ((!strncasecmp(this_line, "defaultname|", 12)) && (sSMTP->preferred_sender_name == NULL)) {
381 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
391 * Implement HELP command.
393 void smtp_help(long offset, long Flags) {
394 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
401 void smtp_get_user(long offset)
404 citsmtp *sSMTP = SMTP;
406 StrBufDecodeBase64(sSMTP->Cmd);
408 if (CtdlLoginExistingUser(NULL, ChrPtr(sSMTP->Cmd)) == login_ok) {
409 size_t len = CtdlEncodeBase64(buf, "Password:", 9, 0);
411 if (buf[len - 1] == '\n') {
414 cprintf("334 %s\r\n", buf);
415 sSMTP->command_state = smtp_password;
418 cprintf("500 No such user.\r\n");
419 sSMTP->command_state = smtp_command;
427 void smtp_get_pass(long offset, long Flags)
429 citsmtp *sSMTP = SMTP;
432 memset(password, 0, sizeof(password));
433 StrBufDecodeBase64(sSMTP->Cmd);
434 syslog(LOG_DEBUG, "Trying <%s>", password);
435 if (CtdlTryPassword(SKEY(sSMTP->Cmd)) == pass_ok) {
436 smtp_auth_greeting(offset, Flags);
439 cprintf("535 Authentication failed.\r\n");
441 sSMTP->command_state = smtp_command;
446 * Back end for PLAIN auth method (either inline or multistate)
448 void smtp_try_plain(long offset, long Flags)
450 citsmtp *sSMTP = SMTP;
451 const char*decoded_authstring;
452 char ident[256] = "";
461 memset(pass, 0, sizeof(pass));
462 decoded_len = StrBufDecodeBase64(sSMTP->Cmd);
466 decoded_authstring = ChrPtr(sSMTP->Cmd);
468 len = safestrncpy(ident, decoded_authstring, sizeof ident);
470 decoded_len -= len - 1;
471 decoded_authstring += len + 1;
475 len = safestrncpy(user, decoded_authstring, sizeof user);
477 decoded_authstring += len + 1;
478 decoded_len -= len - 1;
483 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
486 plen = sizeof(pass) - 1;
490 sSMTP->command_state = smtp_command;
492 if (!IsEmptyStr(ident)) {
493 result = CtdlLoginExistingUser(user, ident);
496 result = CtdlLoginExistingUser(NULL, user);
499 if (result == login_ok) {
500 if (CtdlTryPassword(pass, plen) == pass_ok) {
501 smtp_webcit_preferences_hack();
502 smtp_auth_greeting(offset, Flags);
506 cprintf("504 Authentication failed.\r\n");
511 * Attempt to perform authenticated SMTP
513 void smtp_auth(long offset, long Flags)
515 struct CitContext *CCC = CC;
516 citsmtp *sSMTP = SMTP;
517 char username_prompt[64];
519 char encoded_authstring[1024];
521 if (CCC->logged_in) {
522 cprintf("504 Already logged in.\r\n");
526 extract_token(method, ChrPtr(sSMTP->Cmd) + offset, 0, ' ', sizeof method);
528 if (!strncasecmp(method, "login", 5) ) {
529 if (StrLength(sSMTP->Cmd) - offset >= 7) {
533 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
534 if (username_prompt[len - 1] == '\n') {
535 username_prompt[len - 1] = '\0';
537 cprintf("334 %s\r\n", username_prompt);
538 sSMTP->command_state = smtp_user;
543 if (!strncasecmp(method, "plain", 5) ) {
545 if (num_tokens(ChrPtr(sSMTP->Cmd) + offset, ' ') < 2) {
547 SMTP->command_state = smtp_plain;
551 len = extract_token(encoded_authstring,
552 ChrPtr(sSMTP->Cmd) + offset,
554 sizeof encoded_authstring);
555 StrBufPlain(sSMTP->Cmd, encoded_authstring, len);
556 smtp_try_plain(0, Flags);
560 if (strncasecmp(method, "login", 5) ) {
561 cprintf("504 Unknown authentication method.\r\n");
569 * Implements the RSET (reset state) command.
570 * Currently this just zeroes out the state buffer. If pointers to data
571 * allocated with malloc() are ever placed in the state buffer, we have to
572 * be sure to free() them first!
574 * Set do_response to nonzero to output the SMTP RSET response code.
576 void smtp_rset(long offset, long do_response) {
577 citsmtp *sSMTP = SMTP;
580 * Our entire SMTP state is discarded when a RSET command is issued,
581 * but we need to preserve this one little piece of information, so
582 * we save it for later.
585 FlushStrBuf(sSMTP->Cmd);
586 FlushStrBuf(sSMTP->helo_node);
587 FlushStrBuf(sSMTP->from);
588 FlushStrBuf(sSMTP->recipients);
589 FlushStrBuf(sSMTP->OneRcpt);
591 sSMTP->command_state = 0;
592 sSMTP->number_of_recipients = 0;
593 sSMTP->delivery_mode = 0;
594 sSMTP->message_originated_locally = 0;
597 * we must remember is_lmtp & is_unfiltered.
601 * It is somewhat ambiguous whether we want to log out when a RSET
602 * command is issued. Here's the code to do it. It is commented out
603 * because some clients (such as Pine) issue RSET commands before
604 * each message, but still expect to be logged in.
606 * if (CC->logged_in) {
612 cprintf("250 Zap!\r\n");
617 * Clear out the portions of the state buffer that need to be cleared out
618 * after the DATA command finishes.
620 void smtp_data_clear(long offset, long flags)
622 citsmtp *sSMTP = SMTP;
624 FlushStrBuf(sSMTP->from);
625 FlushStrBuf(sSMTP->recipients);
626 FlushStrBuf(sSMTP->OneRcpt);
627 sSMTP->number_of_recipients = 0;
628 sSMTP->delivery_mode = 0;
629 sSMTP->message_originated_locally = 0;
633 * Implements the "MAIL FROM:" command
635 void smtp_mail(long offset, long flags) {
639 struct CitContext *CCC = CC;
640 citsmtp *sSMTP = SMTP;
642 if (StrLength(sSMTP->from) > 0) {
643 cprintf("503 Only one sender permitted\r\n");
647 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "From:", 5)) {
648 cprintf("501 Syntax error\r\n");
652 StrBufAppendBuf(sSMTP->from, sSMTP->Cmd, offset);
653 StrBufTrim(sSMTP->from);
654 if (strchr(ChrPtr(sSMTP->from), '<') != NULL) {
655 StrBufStripAllBut(sSMTP->from, '<', '>');
658 /* We used to reject empty sender names, until it was brought to our
659 * attention that RFC1123 5.2.9 requires that this be allowed. So now
660 * we allow it, but replace the empty string with a fake
661 * address so we don't have to contend with the empty string causing
662 * other code to fail when it's expecting something there.
664 if (StrLength(sSMTP->from) == 0) {
665 StrBufPlain(sSMTP->from, HKEY("someone@example.com"));
668 /* If this SMTP connection is from a logged-in user, force the 'from'
669 * to be the user's Internet e-mail address as Citadel knows it.
671 if (CCC->logged_in) {
672 StrBufPlain(sSMTP->from, CCC->cs_inet_email, -1);
673 cprintf("250 Sender ok <%s>\r\n", ChrPtr(sSMTP->from));
674 sSMTP->message_originated_locally = 1;
678 else if (sSMTP->is_lmtp) {
679 /* Bypass forgery checking for LMTP */
682 /* Otherwise, make sure outsiders aren't trying to forge mail from
683 * this system (unless, of course, c_allow_spoofing is enabled)
685 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
686 process_rfc822_addr(ChrPtr(sSMTP->from), user, node, name);
687 syslog(LOG_DEBUG, "Claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
688 ChrPtr(sSMTP->from), user, node, name
690 if (CtdlHostAlias(node) != hostalias_nomatch) {
691 cprintf("550 You must log in to send mail from %s\r\n", node);
692 FlushStrBuf(sSMTP->from);
693 syslog(LOG_DEBUG, "Rejecting unauthenticated mail from %s", node);
698 cprintf("250 Sender ok\r\n");
704 * Implements the "RCPT To:" command
706 void smtp_rcpt(long offset, long flags)
708 struct CitContext *CCC = CC;
709 char message_to_spammer[SIZ];
710 recptypes *valid = NULL;
711 citsmtp *sSMTP = SMTP;
713 if (StrLength(sSMTP->from) == 0) {
714 cprintf("503 Need MAIL before RCPT\r\n");
718 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "To:", 3)) {
719 cprintf("501 Syntax error\r\n");
723 if ( (sSMTP->is_msa) && (!CCC->logged_in) ) {
724 cprintf("550 You must log in to send mail on this port.\r\n");
725 FlushStrBuf(sSMTP->from);
728 FlushStrBuf(sSMTP->OneRcpt);
729 StrBufAppendBuf(sSMTP->OneRcpt, sSMTP->Cmd, offset + 3);
730 StrBufTrim(sSMTP->OneRcpt);
731 StrBufStripAllBut(sSMTP->OneRcpt, '<', '>');
733 if ( (StrLength(sSMTP->OneRcpt) + StrLength(sSMTP->recipients)) >= SIZ) {
734 cprintf("452 Too many recipients\r\n");
739 if ( (!CCC->logged_in) /* Don't RBL authenticated users */
740 && (!sSMTP->is_lmtp) ) { /* Don't RBL LMTP clients */
741 if (CtdlGetConfigInt("c_rbl_at_greeting") == 0) { /* Don't RBL again if we already did it */
742 if (rbl_check(message_to_spammer)) {
743 if (server_shutting_down)
744 cprintf("421 %s\r\n", message_to_spammer);
746 cprintf("550 %s\r\n", message_to_spammer);
747 /* no need to free_recipients(valid), it's not allocated yet */
753 valid = validate_recipients(
754 ChrPtr(sSMTP->OneRcpt),
755 smtp_get_Recipients(),
756 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
758 if (valid->num_error != 0) {
759 cprintf("550 %s\r\n", valid->errormsg);
760 free_recipients(valid);
764 if (valid->num_internet > 0) {
765 if (CCC->logged_in) {
766 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
767 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n",
768 ChrPtr(sSMTP->OneRcpt));
769 free_recipients(valid);
775 if (valid->num_internet > 0) {
776 if ( (sSMTP->message_originated_locally == 0)
777 && (sSMTP->is_lmtp == 0) ) {
778 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(sSMTP->OneRcpt));
779 free_recipients(valid);
784 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(sSMTP->OneRcpt));
785 if (StrLength(sSMTP->recipients) > 0) {
786 StrBufAppendBufPlain(sSMTP->recipients, HKEY(","), 0);
788 StrBufAppendBuf(sSMTP->recipients, sSMTP->OneRcpt, 0);
789 sSMTP->number_of_recipients ++;
791 free_recipients(valid);
799 * Implements the DATA command
801 void smtp_data(long offset, long flags)
803 struct CitContext *CCC = CC;
806 struct CtdlMessage *msg = NULL;
812 citsmtp *sSMTP = SMTP;
814 if (StrLength(sSMTP->from) == 0) {
815 cprintf("503 Need MAIL command first.\r\n");
819 if (sSMTP->number_of_recipients < 1) {
820 cprintf("503 Need RCPT command first.\r\n");
824 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
826 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
827 defbody = NewStrBufPlain(NULL, SIZ);
829 if (defbody != NULL) {
830 if (sSMTP->is_lmtp && (CCC->cs_UDSclientUID != -1)) {
833 "Received: from %s (Citadel from userid %ld)\n"
835 ChrPtr(sSMTP->helo_node),
836 (long int) CCC->cs_UDSclientUID,
837 CtdlGetConfigStr("c_fqdn"),
843 "Received: from %s (%s [%s])\n"
845 ChrPtr(sSMTP->helo_node),
848 CtdlGetConfigStr("c_fqdn"),
852 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1);
853 FreeStrBuf(&defbody);
855 cprintf("550 Unable to save message: internal error.\r\n");
859 syslog(LOG_DEBUG, "Converting message...");
860 msg = convert_internet_message_buf(&body);
862 /* If the user is locally authenticated, FORCE the From: header to
863 * show up as the real sender. Yes, this violates the RFC standard,
864 * but IT MAKES SENSE. If you prefer strict RFC adherence over
865 * common sense, you can disable this in the configuration.
867 * We also set the "message room name" ('O' field) to MAILROOM
868 * (which is Mail> on most systems) to prevent it from getting set
869 * to something ugly like "0000058008.Sent Items>" when the message
870 * is read with a Citadel client.
872 if ( (CCC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
875 if (!CM_IsEmpty(msg, erFc822Addr) &&
876 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
877 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
879 if (!IsEmptyStr(CCC->cs_inet_email))
880 validemail = strcmp(CCC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
882 (!IsEmptyStr(CCC->cs_inet_other_emails)))
884 int num_secondary_emails = 0;
886 num_secondary_emails = num_tokens(CCC->cs_inet_other_emails, '|');
887 for (i=0; i < num_secondary_emails && !validemail; ++i) {
889 extract_token(buf, CCC->cs_inet_other_emails,i,'|',sizeof CCC->cs_inet_other_emails);
890 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
895 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
896 syslog(LOG_ERR, "invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
897 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
901 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
902 CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
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, "", 0);
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.");
1026 return cit_panic_backtrace (0);
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 */