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 #define SMTPLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (EnableSMTPLog != 0))
108 #define SMTP_syslog(LEVEL, FORMAT, ...) \
109 SMTPLOG(LEVEL) syslog(LEVEL, \
110 "%s CC[%d]: " FORMAT, IOSTR, CCCID, __VA_ARGS__)
112 #define SMTPM_syslog(LEVEL, FORMAT) \
113 SMTPLOG(LEVEL) syslog(LEVEL, \
114 "%s CC[%d]: " FORMAT, IOSTR, CCCID);
116 HashList *SMTPCmds = NULL;
117 #define MaxSMTPCmdLen 10
119 #define RegisterSmtpCMD(First, H, Flags) \
120 registerSmtpCMD(HKEY(First), H, Flags)
121 void registerSmtpCMD(const char *First, long FLen,
125 smtp_handler_hook *h;
127 if (FLen >= MaxSMTPCmdLen)
128 cit_panic_backtrace (0);
130 h = (smtp_handler_hook*) malloc(sizeof(smtp_handler_hook));
131 memset(h, 0, sizeof(smtp_handler_hook));
135 Put(SMTPCmds, First, FLen, h, NULL);
138 void smtp_cleanup(void)
140 DeleteHash(&SMTPCmds);
144 * Here's where our SMTP session begins its happy day.
146 void smtp_greeting(int is_msa)
149 char message_to_spammer[1024];
151 strcpy(CC->cs_clientname, "SMTP session");
152 CC->internal_pgm = 1;
153 CC->cs_flags |= CS_STEALTH;
154 CC->session_specific_data = malloc(sizeof(citsmtp));
155 memset(SMTP, 0, sizeof(citsmtp));
157 sSMTP->is_msa = is_msa;
158 sSMTP->Cmd = NewStrBufPlain(NULL, SIZ);
159 sSMTP->helo_node = NewStrBuf();
160 sSMTP->from = NewStrBufPlain(NULL, SIZ);
161 sSMTP->recipients = NewStrBufPlain(NULL, SIZ);
162 sSMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
163 sSMTP->preferred_sender_email = NULL;
164 sSMTP->preferred_sender_name = NULL;
166 /* If this config option is set, reject connections from problem
167 * addresses immediately instead of after they execute a RCPT
169 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (sSMTP->is_msa == 0) ) {
170 if (rbl_check(message_to_spammer)) {
171 if (server_shutting_down)
172 cprintf("421 %s\r\n", message_to_spammer);
174 cprintf("550 %s\r\n", message_to_spammer);
175 CC->kill_me = KILLME_SPAMMER;
176 /* no need to free_recipients(valid), it's not allocated yet */
181 /* Otherwise we're either clean or we check later. */
183 if (CC->nologin==1) {
184 cprintf("451 Too many connections are already open; please try again later.\r\n");
185 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
186 /* no need to free_recipients(valid), it's not allocated yet */
190 /* Note: the FQDN *must* appear as the first thing after the 220 code.
191 * Some clients (including citmail.c) depend on it being there.
193 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
198 * SMTPS is just like SMTP, except it goes crypto right away.
200 void smtps_greeting(void) {
201 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
203 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
210 * SMTP MSA port requires authentication.
212 void smtp_msa_greeting(void) {
218 * LMTP is like SMTP but with some extra bonus footage added.
220 void lmtp_greeting(void) {
228 * Generic SMTP MTA greeting
230 void smtp_mta_greeting(void) {
236 * We also have an unfiltered LMTP socket that bypasses spam filters.
238 void lmtp_unfiltered_greeting(void) {
244 sSMTP->is_unfiltered = 1;
249 * Login greeting common to all auth methods
251 void smtp_auth_greeting(long offset, long Flags) {
252 struct CitContext *CCC = CC;
253 cprintf("235 Hello, %s\r\n", CCC->user.fullname);
254 SMTP_syslog(LOG_NOTICE, "SMTP authenticated %s", CCC->user.fullname);
255 CCC->internal_pgm = 0;
256 CCC->cs_flags &= ~CS_STEALTH;
261 * Implement HELO and EHLO commands.
263 * which_command: 0=HELO, 1=EHLO, 2=LHLO
265 void smtp_hello(long offset, long which_command)
267 struct CitContext *CCC = CC;
268 citsmtp *sSMTP = SMTP;
270 StrBufAppendBuf (sSMTP->helo_node, sSMTP->Cmd, offset);
272 if ( (which_command != LHLO) && (sSMTP->is_lmtp) ) {
273 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
277 if ( (which_command == LHLO) && (sSMTP->is_lmtp == 0) ) {
278 cprintf("500 LHLO is only allowed when running LMTP\r\n");
282 if (which_command == HELO) {
283 cprintf("250 Hello %s (%s [%s])\r\n",
284 ChrPtr(sSMTP->helo_node),
290 if (which_command == EHLO) {
291 cprintf("250-Hello %s (%s [%s])\r\n",
292 ChrPtr(sSMTP->helo_node),
298 cprintf("250-Greetings and joyous salutations.\r\n");
300 cprintf("250-HELP\r\n");
301 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
305 * Offer TLS, but only if TLS is not already active.
306 * Furthermore, only offer TLS when running on
307 * the SMTP-MSA port, not on the SMTP-MTA port, due to
308 * questionable reliability of TLS in certain sending MTA's.
310 if ( (!CCC->redirect_ssl) && (sSMTP->is_msa) ) {
311 cprintf("250-STARTTLS\r\n");
313 #endif /* HAVE_OPENSSL */
315 cprintf("250-AUTH LOGIN PLAIN\r\n"
316 "250-AUTH=LOGIN PLAIN\r\n"
324 * Backend function for smtp_webcit_preferences_hack().
325 * Look at a message and determine if it's the preferences file.
327 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
328 struct CtdlMessage *msg;
329 char **webcit_conf = (char **) userdata;
332 return; // already got it
335 msg = CtdlFetchMessage(msgnum, 1, 1);
340 if ( !CM_IsEmpty(msg, eMsgSubject) &&
341 (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __")))
343 /* This is it! Change ownership of the message text so it doesn't get freed. */
344 *webcit_conf = (char *)msg->cm_fields[eMesageText];
345 msg->cm_fields[eMesageText] = NULL;
352 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
353 * stored in the account's WebCit configuration. We have to fetch it now.
355 void smtp_webcit_preferences_hack(void) {
356 struct CitContext *CCC = CC;
357 char config_roomname[ROOMNAMELEN];
358 char *webcit_conf = NULL;
359 citsmtp *sSMTP = SMTP;
361 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CCC->user.usernum, USERCONFIGROOM);
362 if (CtdlGetRoom(&CCC->room, config_roomname) != 0) {
367 * Find the WebCit configuration message
370 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
376 /* Parse the webcit configuration and attempt to do something useful with it */
377 char *str = webcit_conf;
379 char *this_line = NULL;
380 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
382 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
383 sSMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
385 if (!strncasecmp(this_line, "defaultname|", 12)) {
386 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
388 if ((!strncasecmp(this_line, "defaultname|", 12)) && (sSMTP->preferred_sender_name == NULL)) {
389 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
399 * Implement HELP command.
401 void smtp_help(long offset, long Flags) {
402 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
409 void smtp_get_user(long offset)
412 citsmtp *sSMTP = SMTP;
414 StrBufDecodeBase64(sSMTP->Cmd);
416 if (CtdlLoginExistingUser(NULL, ChrPtr(sSMTP->Cmd)) == login_ok) {
417 size_t len = CtdlEncodeBase64(buf, "Password:", 9, 0);
419 if (buf[len - 1] == '\n') {
422 cprintf("334 %s\r\n", buf);
423 sSMTP->command_state = smtp_password;
426 cprintf("500 No such user.\r\n");
427 sSMTP->command_state = smtp_command;
435 void smtp_get_pass(long offset, long Flags)
437 struct CitContext *CCC = CC;
438 citsmtp *sSMTP = SMTP;
441 memset(password, 0, sizeof(password));
442 StrBufDecodeBase64(sSMTP->Cmd);
443 SMTP_syslog(LOG_DEBUG, "Trying <%s>", password);
444 if (CtdlTryPassword(SKEY(sSMTP->Cmd)) == pass_ok) {
445 smtp_auth_greeting(offset, Flags);
448 cprintf("535 Authentication failed.\r\n");
450 sSMTP->command_state = smtp_command;
455 * Back end for PLAIN auth method (either inline or multistate)
457 void smtp_try_plain(long offset, long Flags)
459 citsmtp *sSMTP = SMTP;
460 const char*decoded_authstring;
461 char ident[256] = "";
470 memset(pass, 0, sizeof(pass));
471 decoded_len = StrBufDecodeBase64(sSMTP->Cmd);
475 decoded_authstring = ChrPtr(sSMTP->Cmd);
477 len = safestrncpy(ident, decoded_authstring, sizeof ident);
479 decoded_len -= len - 1;
480 decoded_authstring += len + 1;
484 len = safestrncpy(user, decoded_authstring, sizeof user);
486 decoded_authstring += len + 1;
487 decoded_len -= len - 1;
492 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
495 plen = sizeof(pass) - 1;
499 sSMTP->command_state = smtp_command;
501 if (!IsEmptyStr(ident)) {
502 result = CtdlLoginExistingUser(user, ident);
505 result = CtdlLoginExistingUser(NULL, user);
508 if (result == login_ok) {
509 if (CtdlTryPassword(pass, plen) == pass_ok) {
510 smtp_webcit_preferences_hack();
511 smtp_auth_greeting(offset, Flags);
515 cprintf("504 Authentication failed.\r\n");
520 * Attempt to perform authenticated SMTP
522 void smtp_auth(long offset, long Flags)
524 struct CitContext *CCC = CC;
525 citsmtp *sSMTP = SMTP;
526 char username_prompt[64];
528 char encoded_authstring[1024];
530 if (CCC->logged_in) {
531 cprintf("504 Already logged in.\r\n");
535 extract_token(method, ChrPtr(sSMTP->Cmd) + offset, 0, ' ', sizeof method);
537 if (!strncasecmp(method, "login", 5) ) {
538 if (StrLength(sSMTP->Cmd) - offset >= 7) {
542 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
543 if (username_prompt[len - 1] == '\n') {
544 username_prompt[len - 1] = '\0';
546 cprintf("334 %s\r\n", username_prompt);
547 sSMTP->command_state = smtp_user;
552 if (!strncasecmp(method, "plain", 5) ) {
554 if (num_tokens(ChrPtr(sSMTP->Cmd) + offset, ' ') < 2) {
556 SMTP->command_state = smtp_plain;
560 len = extract_token(encoded_authstring,
561 ChrPtr(sSMTP->Cmd) + offset,
563 sizeof encoded_authstring);
564 StrBufPlain(sSMTP->Cmd, encoded_authstring, len);
565 smtp_try_plain(0, Flags);
569 if (strncasecmp(method, "login", 5) ) {
570 cprintf("504 Unknown authentication method.\r\n");
578 * Implements the RSET (reset state) command.
579 * Currently this just zeroes out the state buffer. If pointers to data
580 * allocated with malloc() are ever placed in the state buffer, we have to
581 * be sure to free() them first!
583 * Set do_response to nonzero to output the SMTP RSET response code.
585 void smtp_rset(long offset, long do_response) {
586 citsmtp *sSMTP = SMTP;
589 * Our entire SMTP state is discarded when a RSET command is issued,
590 * but we need to preserve this one little piece of information, so
591 * we save it for later.
594 FlushStrBuf(sSMTP->Cmd);
595 FlushStrBuf(sSMTP->helo_node);
596 FlushStrBuf(sSMTP->from);
597 FlushStrBuf(sSMTP->recipients);
598 FlushStrBuf(sSMTP->OneRcpt);
600 sSMTP->command_state = 0;
601 sSMTP->number_of_recipients = 0;
602 sSMTP->delivery_mode = 0;
603 sSMTP->message_originated_locally = 0;
606 * we must remember is_lmtp & is_unfiltered.
610 * It is somewhat ambiguous whether we want to log out when a RSET
611 * command is issued. Here's the code to do it. It is commented out
612 * because some clients (such as Pine) issue RSET commands before
613 * each message, but still expect to be logged in.
615 * if (CC->logged_in) {
621 cprintf("250 Zap!\r\n");
626 * Clear out the portions of the state buffer that need to be cleared out
627 * after the DATA command finishes.
629 void smtp_data_clear(long offset, long flags)
631 citsmtp *sSMTP = SMTP;
633 FlushStrBuf(sSMTP->from);
634 FlushStrBuf(sSMTP->recipients);
635 FlushStrBuf(sSMTP->OneRcpt);
636 sSMTP->number_of_recipients = 0;
637 sSMTP->delivery_mode = 0;
638 sSMTP->message_originated_locally = 0;
642 * Implements the "MAIL FROM:" command
644 void smtp_mail(long offset, long flags) {
648 struct CitContext *CCC = CC;
649 citsmtp *sSMTP = SMTP;
651 if (StrLength(sSMTP->from) > 0) {
652 cprintf("503 Only one sender permitted\r\n");
656 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "From:", 5)) {
657 cprintf("501 Syntax error\r\n");
661 StrBufAppendBuf(sSMTP->from, sSMTP->Cmd, offset);
662 StrBufTrim(sSMTP->from);
663 if (strchr(ChrPtr(sSMTP->from), '<') != NULL) {
664 StrBufStripAllBut(sSMTP->from, '<', '>');
667 /* We used to reject empty sender names, until it was brought to our
668 * attention that RFC1123 5.2.9 requires that this be allowed. So now
669 * we allow it, but replace the empty string with a fake
670 * address so we don't have to contend with the empty string causing
671 * other code to fail when it's expecting something there.
673 if (StrLength(sSMTP->from) == 0) {
674 StrBufPlain(sSMTP->from, HKEY("someone@example.com"));
677 /* If this SMTP connection is from a logged-in user, force the 'from'
678 * to be the user's Internet e-mail address as Citadel knows it.
680 if (CCC->logged_in) {
681 StrBufPlain(sSMTP->from, CCC->cs_inet_email, -1);
682 cprintf("250 Sender ok <%s>\r\n", ChrPtr(sSMTP->from));
683 sSMTP->message_originated_locally = 1;
687 else if (sSMTP->is_lmtp) {
688 /* Bypass forgery checking for LMTP */
691 /* Otherwise, make sure outsiders aren't trying to forge mail from
692 * this system (unless, of course, c_allow_spoofing is enabled)
694 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
695 process_rfc822_addr(ChrPtr(sSMTP->from), user, node, name);
696 SMTP_syslog(LOG_DEBUG, "Claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
697 ChrPtr(sSMTP->from), user, node, name
699 if (CtdlHostAlias(node) != hostalias_nomatch) {
700 cprintf("550 You must log in to send mail from %s\r\n", node);
701 FlushStrBuf(sSMTP->from);
702 SMTP_syslog(LOG_DEBUG, "Rejecting unauthenticated mail from %s", node);
707 cprintf("250 Sender ok\r\n");
713 * Implements the "RCPT To:" command
715 void smtp_rcpt(long offset, long flags)
717 struct CitContext *CCC = CC;
718 char message_to_spammer[SIZ];
719 recptypes *valid = NULL;
720 citsmtp *sSMTP = SMTP;
722 if (StrLength(sSMTP->from) == 0) {
723 cprintf("503 Need MAIL before RCPT\r\n");
727 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "To:", 3)) {
728 cprintf("501 Syntax error\r\n");
732 if ( (sSMTP->is_msa) && (!CCC->logged_in) ) {
733 cprintf("550 You must log in to send mail on this port.\r\n");
734 FlushStrBuf(sSMTP->from);
737 FlushStrBuf(sSMTP->OneRcpt);
738 StrBufAppendBuf(sSMTP->OneRcpt, sSMTP->Cmd, offset + 3);
739 StrBufTrim(sSMTP->OneRcpt);
740 StrBufStripAllBut(sSMTP->OneRcpt, '<', '>');
742 if ( (StrLength(sSMTP->OneRcpt) + StrLength(sSMTP->recipients)) >= SIZ) {
743 cprintf("452 Too many recipients\r\n");
748 if ( (!CCC->logged_in) /* Don't RBL authenticated users */
749 && (!sSMTP->is_lmtp) ) { /* Don't RBL LMTP clients */
750 if (CtdlGetConfigInt("c_rbl_at_greeting") == 0) { /* Don't RBL again if we already did it */
751 if (rbl_check(message_to_spammer)) {
752 if (server_shutting_down)
753 cprintf("421 %s\r\n", message_to_spammer);
755 cprintf("550 %s\r\n", message_to_spammer);
756 /* no need to free_recipients(valid), it's not allocated yet */
762 valid = validate_recipients(
763 ChrPtr(sSMTP->OneRcpt),
764 smtp_get_Recipients(),
765 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
767 if (valid->num_error != 0) {
768 cprintf("550 %s\r\n", valid->errormsg);
769 free_recipients(valid);
773 if (valid->num_internet > 0) {
774 if (CCC->logged_in) {
775 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
776 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n",
777 ChrPtr(sSMTP->OneRcpt));
778 free_recipients(valid);
784 if (valid->num_internet > 0) {
785 if ( (sSMTP->message_originated_locally == 0)
786 && (sSMTP->is_lmtp == 0) ) {
787 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(sSMTP->OneRcpt));
788 free_recipients(valid);
793 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(sSMTP->OneRcpt));
794 if (StrLength(sSMTP->recipients) > 0) {
795 StrBufAppendBufPlain(sSMTP->recipients, HKEY(","), 0);
797 StrBufAppendBuf(sSMTP->recipients, sSMTP->OneRcpt, 0);
798 sSMTP->number_of_recipients ++;
800 free_recipients(valid);
808 * Implements the DATA command
810 void smtp_data(long offset, long flags)
812 struct CitContext *CCC = CC;
815 struct CtdlMessage *msg = NULL;
821 citsmtp *sSMTP = SMTP;
823 if (StrLength(sSMTP->from) == 0) {
824 cprintf("503 Need MAIL command first.\r\n");
828 if (sSMTP->number_of_recipients < 1) {
829 cprintf("503 Need RCPT command first.\r\n");
833 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
835 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
836 defbody = NewStrBufPlain(NULL, SIZ);
838 if (defbody != NULL) {
839 if (sSMTP->is_lmtp && (CCC->cs_UDSclientUID != -1)) {
842 "Received: from %s (Citadel from userid %ld)\n"
844 ChrPtr(sSMTP->helo_node),
845 (long int) CCC->cs_UDSclientUID,
846 CtdlGetConfigStr("c_fqdn"),
852 "Received: from %s (%s [%s])\n"
854 ChrPtr(sSMTP->helo_node),
857 CtdlGetConfigStr("c_fqdn"),
861 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1, NULL);
862 FreeStrBuf(&defbody);
864 cprintf("550 Unable to save message: internal error.\r\n");
868 SMTPM_syslog(LOG_DEBUG, "Converting message...");
869 msg = convert_internet_message_buf(&body);
871 /* If the user is locally authenticated, FORCE the From: header to
872 * show up as the real sender. Yes, this violates the RFC standard,
873 * but IT MAKES SENSE. If you prefer strict RFC adherence over
874 * common sense, you can disable this in the configuration.
876 * We also set the "message room name" ('O' field) to MAILROOM
877 * (which is Mail> on most systems) to prevent it from getting set
878 * to something ugly like "0000058008.Sent Items>" when the message
879 * is read with a Citadel client.
881 if ( (CCC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
884 if (!CM_IsEmpty(msg, erFc822Addr) &&
885 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
886 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
888 if (!IsEmptyStr(CCC->cs_inet_email))
889 validemail = strcmp(CCC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
891 (!IsEmptyStr(CCC->cs_inet_other_emails)))
893 int num_secondary_emails = 0;
895 num_secondary_emails = num_tokens(CCC->cs_inet_other_emails, '|');
896 for (i=0; i < num_secondary_emails && !validemail; ++i) {
898 extract_token(buf, CCC->cs_inet_other_emails,i,'|',sizeof CCC->cs_inet_other_emails);
899 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
904 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
905 SMTP_syslog(LOG_ERR, "invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
906 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
910 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
911 CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
912 CM_SetField(msg, eOriginalRoom, HKEY(MAILROOM));
913 if (sSMTP->preferred_sender_name != NULL)
914 CM_SetField(msg, eAuthor, SKEY(sSMTP->preferred_sender_name));
916 CM_SetField(msg, eAuthor, CCC->user.fullname, strlen(CCC->user.fullname));
919 if (sSMTP->preferred_sender_email != NULL)
920 CM_SetField(msg, erFc822Addr, SKEY(sSMTP->preferred_sender_email));
922 CM_SetField(msg, erFc822Addr, CCC->cs_inet_email, strlen(CCC->cs_inet_email));
926 /* Set the "envelope from" address */
927 CM_SetField(msg, eMessagePath, SKEY(sSMTP->from));
929 /* Set the "envelope to" address */
930 CM_SetField(msg, eenVelopeTo, SKEY(sSMTP->recipients));
932 /* Submit the message into the Citadel system. */
933 valid = validate_recipients(
934 ChrPtr(sSMTP->recipients),
935 smtp_get_Recipients(),
936 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
939 /* If there are modules that want to scan this message before final
940 * submission (such as virus checkers or spam filters), call them now
941 * and give them an opportunity to reject the message.
943 if (sSMTP->is_unfiltered) {
947 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
950 if (scan_errors > 0) { /* We don't want this message! */
952 if (CM_IsEmpty(msg, eErrorMsg)) {
953 CM_SetField(msg, eErrorMsg, HKEY("Message rejected by filter"));
956 StrBufPrintf(sSMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
959 else { /* Ok, we'll accept this message. */
960 msgnum = CtdlSubmitMsg(msg, valid, "", 0);
962 StrBufPrintf(sSMTP->OneRcpt, "250 Message accepted.\r\n");
965 StrBufPrintf(sSMTP->OneRcpt, "550 Internal delivery error\r\n");
969 /* For SMTP and ESMTP, just print the result message. For LMTP, we
970 * have to print one result message for each recipient. Since there
971 * is nothing in Citadel which would cause different recipients to
972 * have different results, we can get away with just spitting out the
973 * same message once for each recipient.
975 if (sSMTP->is_lmtp) {
976 for (i=0; i<sSMTP->number_of_recipients; ++i) {
977 cputbuf(sSMTP->OneRcpt);
981 cputbuf(sSMTP->OneRcpt);
984 /* Write something to the syslog(which may or may not be where the
985 * rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
987 SMTP_syslog((LOG_MAIL | LOG_INFO),
988 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
991 sSMTP->number_of_recipients,
994 ChrPtr(sSMTP->OneRcpt)
999 free_recipients(valid);
1000 smtp_data_clear(0, 0); /* clear out the buffers now */
1005 * implements the STARTTLS command
1007 void smtp_starttls(long offset, long flags)
1009 char ok_response[SIZ];
1010 char nosup_response[SIZ];
1011 char error_response[SIZ];
1013 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
1014 sprintf(nosup_response, "554 TLS not supported here\r\n");
1015 sprintf(error_response, "554 Internal error\r\n");
1016 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
1022 * Main command loop for SMTP server sessions.
1024 void smtp_command_loop(void)
1026 static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
1027 struct CitContext *CCC = CC;
1028 citsmtp *sSMTP = SMTP;
1029 const char *pch, *pchs;
1031 char CMD[MaxSMTPCmdLen + 1];
1033 if (sSMTP == NULL) {
1034 SMTPM_syslog(LOG_EMERG, "Session SMTP data is null. WTF? We will crash now.");
1035 return cit_panic_backtrace (0);
1038 time(&CCC->lastcmd);
1039 if (CtdlClientGetLine(sSMTP->Cmd) < 1) {
1040 SMTPM_syslog(LOG_CRIT, "SMTP: client disconnected: ending session.");
1041 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1044 SMTP_syslog(LOG_DEBUG, "SMTP server: %s", ChrPtr(sSMTP->Cmd));
1046 if (sSMTP->command_state == smtp_user) {
1047 if (!strncmp(ChrPtr(sSMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len))
1048 smtp_try_plain(0, 0);
1054 else if (sSMTP->command_state == smtp_password) {
1055 smtp_get_pass(0, 0);
1059 else if (sSMTP->command_state == smtp_plain) {
1060 smtp_try_plain(0, 0);
1064 pchs = pch = ChrPtr(sSMTP->Cmd);
1066 while ((*pch != '\0') &&
1068 (pch - pchs <= MaxSMTPCmdLen))
1070 CMD[i] = toupper(*pch);
1076 if ((*pch == '\0') ||
1081 if (GetHash(SMTPCmds, CMD, i, &v) &&
1084 smtp_handler_hook *h = (smtp_handler_hook*) v;
1086 if (isblank(pchs[i]))
1094 cprintf("502 I'm afraid I can't do that.\r\n");
1097 void smtp_noop(long offest, long Flags)
1099 cprintf("250 NOOP\r\n");
1102 void smtp_quit(long offest, long Flags)
1104 cprintf("221 Goodbye...\r\n");
1105 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1108 /*****************************************************************************/
1109 /* MODULE INITIALIZATION STUFF */
1110 /*****************************************************************************/
1112 * This cleanup function blows away the temporary memory used by
1115 void smtp_cleanup_function(void)
1117 citsmtp *sSMTP = SMTP;
1118 struct CitContext *CCC = CC;
1120 /* Don't do this stuff if this is not an SMTP session! */
1121 if (CCC->h_command_function != smtp_command_loop) return;
1123 SMTPM_syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
1125 FreeStrBuf(&sSMTP->Cmd);
1126 FreeStrBuf(&sSMTP->helo_node);
1127 FreeStrBuf(&sSMTP->from);
1128 FreeStrBuf(&sSMTP->recipients);
1129 FreeStrBuf(&sSMTP->OneRcpt);
1130 FreeStrBuf(&sSMTP->preferred_sender_email);
1131 FreeStrBuf(&sSMTP->preferred_sender_name);
1136 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1137 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1138 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1139 const char *CitadelServiceSMTP_LMTP="LMTP";
1140 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1142 void DebugSMTPEnable(const int n)
1147 CTDL_MODULE_INIT(smtp)
1151 CtdlRegisterDebugFlagHook(HKEY("SMTP"), DebugSMTPEnable, &EnableSMTPLog);
1153 SMTPCmds = NewHash(1, NULL);
1155 RegisterSmtpCMD("AUTH", smtp_auth, 0);
1156 RegisterSmtpCMD("DATA", smtp_data, 0);
1157 RegisterSmtpCMD("HELO", smtp_hello, HELO);
1158 RegisterSmtpCMD("EHLO", smtp_hello, EHLO);
1159 RegisterSmtpCMD("LHLO", smtp_hello, LHLO);
1160 RegisterSmtpCMD("HELP", smtp_help, 0);
1161 RegisterSmtpCMD("MAIL", smtp_mail, 0);
1162 RegisterSmtpCMD("NOOP", smtp_noop, 0);
1163 RegisterSmtpCMD("QUIT", smtp_quit, 0);
1164 RegisterSmtpCMD("RCPT", smtp_rcpt, 0);
1165 RegisterSmtpCMD("RSET", smtp_rset, 1);
1167 RegisterSmtpCMD("STARTTLS", smtp_starttls, 0);
1171 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"), /* SMTP MTA */
1176 CitadelServiceSMTP_MTA);
1179 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"), /* SMTPS MTA */
1184 CitadelServiceSMTPS_MTA);
1187 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"), /* SMTP MSA */
1192 CitadelServiceSMTP_MSA);
1194 CtdlRegisterServiceHook(0, /* local LMTP */
1199 CitadelServiceSMTP_LMTP);
1201 CtdlRegisterServiceHook(0, /* local LMTP */
1202 file_lmtp_unfiltered_socket,
1203 lmtp_unfiltered_greeting,
1206 CitadelServiceSMTP_LMTP_UNF);
1208 CtdlRegisterCleanupHook(smtp_cleanup);
1209 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1212 /* return our module name for the log */