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>
46 #if TIME_WITH_SYS_TIME
47 # include <sys/time.h>
51 # include <sys/time.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 #include <libcitadel.h>
67 #include "citserver.h"
75 #include "internet_addressing.h"
78 #include "clientsocket.h"
79 #include "locate_host.h"
80 #include "citadel_dirs.h"
81 #include "ctdl_module.h"
83 #include "smtp_util.h"
85 enum { /* Command states for login authentication */
98 typedef void (*smtp_handler)(long offest, long Flags);
100 typedef struct _smtp_handler_hook {
105 int EnableSMTPLog = 0;
107 HashList *SMTPCmds = NULL;
108 #define MaxSMTPCmdLen 10
110 #define RegisterSmtpCMD(First, H, Flags) \
111 registerSmtpCMD(HKEY(First), H, Flags)
112 void registerSmtpCMD(const char *First, long FLen,
116 smtp_handler_hook *h;
118 if (FLen >= MaxSMTPCmdLen)
123 h = (smtp_handler_hook*) malloc(sizeof(smtp_handler_hook));
124 memset(h, 0, sizeof(smtp_handler_hook));
128 Put(SMTPCmds, First, FLen, h, NULL);
133 * Here's where our SMTP session begins its happy day.
135 void smtp_greeting(int is_msa)
138 char message_to_spammer[1024];
140 strcpy(CC->cs_clientname, "SMTP session");
141 CC->internal_pgm = 1;
142 CC->cs_flags |= CS_STEALTH;
143 CC->session_specific_data = malloc(sizeof(citsmtp));
144 memset(SMTP, 0, sizeof(citsmtp));
146 sSMTP->is_msa = is_msa;
147 sSMTP->Cmd = NewStrBufPlain(NULL, SIZ);
148 sSMTP->helo_node = NewStrBuf();
149 sSMTP->from = NewStrBufPlain(NULL, SIZ);
150 sSMTP->recipients = NewStrBufPlain(NULL, SIZ);
151 sSMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
152 sSMTP->preferred_sender_email = NULL;
153 sSMTP->preferred_sender_name = NULL;
155 /* If this config option is set, reject connections from problem
156 * addresses immediately instead of after they execute a RCPT
158 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (sSMTP->is_msa == 0) ) {
159 if (rbl_check(CC->cs_addr, message_to_spammer)) {
160 if (server_shutting_down)
161 cprintf("421 %s\r\n", message_to_spammer);
163 cprintf("550 %s\r\n", message_to_spammer);
164 CC->kill_me = KILLME_SPAMMER;
165 /* no need to free_recipients(valid), it's not allocated yet */
170 /* Otherwise we're either clean or we check later. */
172 if (CC->nologin==1) {
173 cprintf("451 Too many connections are already open; please try again later.\r\n");
174 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
175 /* no need to free_recipients(valid), it's not allocated yet */
179 /* Note: the FQDN *must* appear as the first thing after the 220 code.
180 * Some clients (including citmail.c) depend on it being there.
182 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
187 * SMTPS is just like SMTP, except it goes crypto right away.
189 void smtps_greeting(void) {
190 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
192 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
199 * SMTP MSA port requires authentication.
201 void smtp_msa_greeting(void) {
207 * LMTP is like SMTP but with some extra bonus footage added.
209 void lmtp_greeting(void) {
217 * Generic SMTP MTA greeting
219 void smtp_mta_greeting(void) {
225 * We also have an unfiltered LMTP socket that bypasses spam filters.
227 void lmtp_unfiltered_greeting(void) {
233 sSMTP->is_unfiltered = 1;
238 * Login greeting common to all auth methods
240 void smtp_auth_greeting(long offset, long Flags) {
241 struct CitContext *CCC = CC;
242 cprintf("235 Hello, %s\r\n", CCC->user.fullname);
243 syslog(LOG_NOTICE, "SMTP authenticated %s", CCC->user.fullname);
244 CCC->internal_pgm = 0;
245 CCC->cs_flags &= ~CS_STEALTH;
250 * Implement HELO and EHLO commands.
252 * which_command: 0=HELO, 1=EHLO, 2=LHLO
254 void smtp_hello(long offset, long which_command)
256 struct CitContext *CCC = CC;
257 citsmtp *sSMTP = SMTP;
259 StrBufAppendBuf (sSMTP->helo_node, sSMTP->Cmd, offset);
261 if ( (which_command != LHLO) && (sSMTP->is_lmtp) ) {
262 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
266 if ( (which_command == LHLO) && (sSMTP->is_lmtp == 0) ) {
267 cprintf("500 LHLO is only allowed when running LMTP\r\n");
271 if (which_command == HELO) {
272 cprintf("250 Hello %s (%s [%s])\r\n",
273 ChrPtr(sSMTP->helo_node),
279 if (which_command == EHLO) {
280 cprintf("250-Hello %s (%s [%s])\r\n",
281 ChrPtr(sSMTP->helo_node),
287 cprintf("250-Greetings and joyous salutations.\r\n");
289 cprintf("250-HELP\r\n");
290 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
294 * Offer TLS, but only if TLS is not already active.
295 * Furthermore, only offer TLS when running on
296 * the SMTP-MSA port, not on the SMTP-MTA port, due to
297 * questionable reliability of TLS in certain sending MTA's.
299 if ( (!CCC->redirect_ssl) && (sSMTP->is_msa) ) {
300 cprintf("250-STARTTLS\r\n");
302 #endif /* HAVE_OPENSSL */
304 cprintf("250-AUTH LOGIN PLAIN\r\n"
305 "250-AUTH=LOGIN PLAIN\r\n"
313 * Backend function for smtp_webcit_preferences_hack().
314 * Look at a message and determine if it's the preferences file.
316 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
317 struct CtdlMessage *msg;
318 char **webcit_conf = (char **) userdata;
321 return; // already got it
324 msg = CtdlFetchMessage(msgnum, 1);
329 if ( !CM_IsEmpty(msg, eMsgSubject) &&
330 (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __")))
332 /* This is it! Change ownership of the message text so it doesn't get freed. */
333 *webcit_conf = (char *)msg->cm_fields[eMesageText];
334 msg->cm_fields[eMesageText] = NULL;
341 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
342 * stored in the account's WebCit configuration. We have to fetch it now.
344 void smtp_webcit_preferences_hack(void) {
345 struct CitContext *CCC = CC;
346 char config_roomname[ROOMNAMELEN];
347 char *webcit_conf = NULL;
348 citsmtp *sSMTP = SMTP;
350 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CCC->user.usernum, USERCONFIGROOM);
351 if (CtdlGetRoom(&CCC->room, config_roomname) != 0) {
356 * Find the WebCit configuration message
359 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
365 /* Parse the webcit configuration and attempt to do something useful with it */
366 char *str = webcit_conf;
368 char *this_line = NULL;
369 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
371 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
372 sSMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
374 if (!strncasecmp(this_line, "defaultname|", 12)) {
375 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
377 if ((!strncasecmp(this_line, "defaultname|", 12)) && (sSMTP->preferred_sender_name == NULL)) {
378 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
388 * Implement HELP command.
390 void smtp_help(long offset, long Flags) {
391 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
398 void smtp_get_user(long offset)
401 citsmtp *sSMTP = SMTP;
403 StrBufDecodeBase64(sSMTP->Cmd);
405 if (CtdlLoginExistingUser(ChrPtr(sSMTP->Cmd)) == login_ok) {
406 size_t len = CtdlEncodeBase64(buf, "Password:", 9, 0);
408 if (buf[len - 1] == '\n') {
411 cprintf("334 %s\r\n", buf);
412 sSMTP->command_state = smtp_password;
415 cprintf("500 No such user.\r\n");
416 sSMTP->command_state = smtp_command;
424 void smtp_get_pass(long offset, long Flags)
426 citsmtp *sSMTP = SMTP;
429 memset(password, 0, sizeof(password));
430 StrBufDecodeBase64(sSMTP->Cmd);
431 syslog(LOG_DEBUG, "Trying <%s>", password);
432 if (CtdlTryPassword(SKEY(sSMTP->Cmd)) == pass_ok) {
433 smtp_auth_greeting(offset, Flags);
436 cprintf("535 Authentication failed.\r\n");
438 sSMTP->command_state = smtp_command;
443 * Back end for PLAIN auth method (either inline or multistate)
445 void smtp_try_plain(long offset, long Flags)
447 citsmtp *sSMTP = SMTP;
448 const char*decoded_authstring;
449 char ident[256] = "";
458 memset(pass, 0, sizeof(pass));
459 decoded_len = StrBufDecodeBase64(sSMTP->Cmd);
463 decoded_authstring = ChrPtr(sSMTP->Cmd);
465 len = safestrncpy(ident, decoded_authstring, sizeof ident);
467 decoded_len -= len - 1;
468 decoded_authstring += len + 1;
472 len = safestrncpy(user, decoded_authstring, sizeof user);
474 decoded_authstring += len + 1;
475 decoded_len -= len - 1;
480 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
483 plen = sizeof(pass) - 1;
487 sSMTP->command_state = smtp_command;
489 if (!IsEmptyStr(ident)) {
490 result = CtdlLoginExistingUser(ident);
493 result = CtdlLoginExistingUser(user);
496 if (result == login_ok) {
497 if (CtdlTryPassword(pass, plen) == pass_ok) {
498 smtp_webcit_preferences_hack();
499 smtp_auth_greeting(offset, Flags);
503 cprintf("504 Authentication failed.\r\n");
508 * Attempt to perform authenticated SMTP
510 void smtp_auth(long offset, long Flags)
512 struct CitContext *CCC = CC;
513 citsmtp *sSMTP = SMTP;
514 char username_prompt[64];
516 char encoded_authstring[1024];
518 if (CCC->logged_in) {
519 cprintf("504 Already logged in.\r\n");
523 extract_token(method, ChrPtr(sSMTP->Cmd) + offset, 0, ' ', sizeof method);
525 if (!strncasecmp(method, "login", 5) ) {
526 if (StrLength(sSMTP->Cmd) - offset >= 7) {
530 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
531 if (username_prompt[len - 1] == '\n') {
532 username_prompt[len - 1] = '\0';
534 cprintf("334 %s\r\n", username_prompt);
535 sSMTP->command_state = smtp_user;
540 if (!strncasecmp(method, "plain", 5) ) {
542 if (num_tokens(ChrPtr(sSMTP->Cmd) + offset, ' ') < 2) {
544 SMTP->command_state = smtp_plain;
548 len = extract_token(encoded_authstring,
549 ChrPtr(sSMTP->Cmd) + offset,
551 sizeof encoded_authstring);
552 StrBufPlain(sSMTP->Cmd, encoded_authstring, len);
553 smtp_try_plain(0, Flags);
557 if (strncasecmp(method, "login", 5) ) {
558 cprintf("504 Unknown authentication method.\r\n");
566 * Implements the RSET (reset state) command.
567 * Currently this just zeroes out the state buffer. If pointers to data
568 * allocated with malloc() are ever placed in the state buffer, we have to
569 * be sure to free() them first!
571 * Set do_response to nonzero to output the SMTP RSET response code.
573 void smtp_rset(long offset, long do_response) {
574 citsmtp *sSMTP = SMTP;
577 * Our entire SMTP state is discarded when a RSET command is issued,
578 * but we need to preserve this one little piece of information, so
579 * we save it for later.
582 FlushStrBuf(sSMTP->Cmd);
583 FlushStrBuf(sSMTP->helo_node);
584 FlushStrBuf(sSMTP->from);
585 FlushStrBuf(sSMTP->recipients);
586 FlushStrBuf(sSMTP->OneRcpt);
588 sSMTP->command_state = 0;
589 sSMTP->number_of_recipients = 0;
590 sSMTP->delivery_mode = 0;
591 sSMTP->message_originated_locally = 0;
594 * we must remember is_lmtp & is_unfiltered.
598 * It is somewhat ambiguous whether we want to log out when a RSET
599 * command is issued. Here's the code to do it. It is commented out
600 * because some clients (such as Pine) issue RSET commands before
601 * each message, but still expect to be logged in.
603 * if (CC->logged_in) {
609 cprintf("250 Zap!\r\n");
614 * Clear out the portions of the state buffer that need to be cleared out
615 * after the DATA command finishes.
617 void smtp_data_clear(long offset, long flags)
619 citsmtp *sSMTP = SMTP;
621 FlushStrBuf(sSMTP->from);
622 FlushStrBuf(sSMTP->recipients);
623 FlushStrBuf(sSMTP->OneRcpt);
624 sSMTP->number_of_recipients = 0;
625 sSMTP->delivery_mode = 0;
626 sSMTP->message_originated_locally = 0;
630 * Implements the "MAIL FROM:" command
632 void smtp_mail(long offset, long flags) {
636 struct CitContext *CCC = CC;
637 citsmtp *sSMTP = SMTP;
639 if (StrLength(sSMTP->from) > 0) {
640 cprintf("503 Only one sender permitted\r\n");
644 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "From:", 5)) {
645 cprintf("501 Syntax error\r\n");
649 StrBufAppendBuf(sSMTP->from, sSMTP->Cmd, offset);
650 StrBufTrim(sSMTP->from);
651 if (strchr(ChrPtr(sSMTP->from), '<') != NULL) {
652 StrBufStripAllBut(sSMTP->from, '<', '>');
655 /* We used to reject empty sender names, until it was brought to our
656 * attention that RFC1123 5.2.9 requires that this be allowed. So now
657 * we allow it, but replace the empty string with a fake
658 * address so we don't have to contend with the empty string causing
659 * other code to fail when it's expecting something there.
661 if (StrLength(sSMTP->from) == 0) {
662 StrBufPlain(sSMTP->from, HKEY("someone@example.com"));
665 /* If this SMTP connection is from a logged-in user, force the 'from'
666 * to be the user's Internet e-mail address as Citadel knows it.
668 if (CCC->logged_in) {
669 StrBufPlain(sSMTP->from, CCC->cs_inet_email, -1);
670 cprintf("250 Sender ok <%s>\r\n", ChrPtr(sSMTP->from));
671 sSMTP->message_originated_locally = 1;
675 else if (sSMTP->is_lmtp) {
676 /* Bypass forgery checking for LMTP */
679 /* Otherwise, make sure outsiders aren't trying to forge mail from
680 * this system (unless, of course, c_allow_spoofing is enabled)
682 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
683 process_rfc822_addr(ChrPtr(sSMTP->from), user, node, name);
684 syslog(LOG_DEBUG, "Claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
685 ChrPtr(sSMTP->from), user, node, name
687 if (CtdlHostAlias(node) != hostalias_nomatch) {
688 cprintf("550 You must log in to send mail from %s\r\n", node);
689 FlushStrBuf(sSMTP->from);
690 syslog(LOG_DEBUG, "Rejecting unauthenticated mail from %s", node);
695 cprintf("250 Sender ok\r\n");
701 * Implements the "RCPT To:" command
703 void smtp_rcpt(long offset, long flags)
705 struct CitContext *CCC = CC;
706 char message_to_spammer[SIZ];
707 recptypes *valid = NULL;
708 citsmtp *sSMTP = SMTP;
710 if (StrLength(sSMTP->from) == 0) {
711 cprintf("503 Need MAIL before RCPT\r\n");
715 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "To:", 3)) {
716 cprintf("501 Syntax error\r\n");
720 if ( (sSMTP->is_msa) && (!CCC->logged_in) ) {
721 cprintf("550 You must log in to send mail on this port.\r\n");
722 FlushStrBuf(sSMTP->from);
725 FlushStrBuf(sSMTP->OneRcpt);
726 StrBufAppendBuf(sSMTP->OneRcpt, sSMTP->Cmd, offset + 3);
727 StrBufTrim(sSMTP->OneRcpt);
728 StrBufStripAllBut(sSMTP->OneRcpt, '<', '>');
730 if ( (StrLength(sSMTP->OneRcpt) + StrLength(sSMTP->recipients)) >= SIZ) {
731 cprintf("452 Too many recipients\r\n");
736 if ( (!CCC->logged_in) /* Don't RBL authenticated users */
737 && (!sSMTP->is_lmtp) ) { /* Don't RBL LMTP clients */
738 if (CtdlGetConfigInt("c_rbl_at_greeting") == 0) { /* Don't RBL again if we already did it */
739 if (rbl_check(CC->cs_addr, message_to_spammer)) {
740 if (server_shutting_down)
741 cprintf("421 %s\r\n", message_to_spammer);
743 cprintf("550 %s\r\n", message_to_spammer);
744 /* no need to free_recipients(valid), it's not allocated yet */
750 valid = validate_recipients(
751 ChrPtr(sSMTP->OneRcpt),
752 smtp_get_Recipients(),
753 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
755 if (valid->num_error != 0) {
756 cprintf("550 %s\r\n", valid->errormsg);
757 free_recipients(valid);
761 if (valid->num_internet > 0) {
762 if (CCC->logged_in) {
763 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
764 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n",
765 ChrPtr(sSMTP->OneRcpt));
766 free_recipients(valid);
772 if (valid->num_internet > 0) {
773 if ( (sSMTP->message_originated_locally == 0)
774 && (sSMTP->is_lmtp == 0) ) {
775 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(sSMTP->OneRcpt));
776 free_recipients(valid);
781 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(sSMTP->OneRcpt));
782 if (StrLength(sSMTP->recipients) > 0) {
783 StrBufAppendBufPlain(sSMTP->recipients, HKEY(","), 0);
785 StrBufAppendBuf(sSMTP->recipients, sSMTP->OneRcpt, 0);
786 sSMTP->number_of_recipients ++;
788 free_recipients(valid);
796 * Implements the DATA command
798 void smtp_data(long offset, long flags)
800 struct CitContext *CCC = CC;
803 struct CtdlMessage *msg = NULL;
809 citsmtp *sSMTP = SMTP;
811 if (StrLength(sSMTP->from) == 0) {
812 cprintf("503 Need MAIL command first.\r\n");
816 if (sSMTP->number_of_recipients < 1) {
817 cprintf("503 Need RCPT command first.\r\n");
821 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
823 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
824 defbody = NewStrBufPlain(NULL, SIZ);
826 if (defbody != NULL) {
827 if (sSMTP->is_lmtp && (CCC->cs_UDSclientUID != -1)) {
830 "Received: from %s (Citadel from userid %ld)\n"
832 ChrPtr(sSMTP->helo_node),
833 (long int) CCC->cs_UDSclientUID,
834 CtdlGetConfigStr("c_fqdn"),
840 "Received: from %s (%s [%s])\n"
842 ChrPtr(sSMTP->helo_node),
845 CtdlGetConfigStr("c_fqdn"),
849 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1);
850 FreeStrBuf(&defbody);
852 cprintf("550 Unable to save message: internal error.\r\n");
856 syslog(LOG_DEBUG, "Converting message...");
857 msg = convert_internet_message_buf(&body);
859 /* If the user is locally authenticated, FORCE the From: header to
860 * show up as the real sender. Yes, this violates the RFC standard,
861 * but IT MAKES SENSE. If you prefer strict RFC adherence over
862 * common sense, you can disable this in the configuration.
864 * We also set the "message room name" ('O' field) to MAILROOM
865 * (which is Mail> on most systems) to prevent it from getting set
866 * to something ugly like "0000058008.Sent Items>" when the message
867 * is read with a Citadel client.
869 if ( (CCC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
872 if (!CM_IsEmpty(msg, erFc822Addr) &&
873 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
874 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
876 if (!IsEmptyStr(CCC->cs_inet_email))
877 validemail = strcmp(CCC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
879 (!IsEmptyStr(CCC->cs_inet_other_emails)))
881 int num_secondary_emails = 0;
883 num_secondary_emails = num_tokens(CCC->cs_inet_other_emails, '|');
884 for (i=0; i < num_secondary_emails && !validemail; ++i) {
886 extract_token(buf, CCC->cs_inet_other_emails,i,'|',sizeof CCC->cs_inet_other_emails);
887 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
892 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
893 syslog(LOG_ERR, "invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
894 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
898 CM_SetField(msg, eOriginalRoom, HKEY(MAILROOM));
899 if (sSMTP->preferred_sender_name != NULL)
900 CM_SetField(msg, eAuthor, SKEY(sSMTP->preferred_sender_name));
902 CM_SetField(msg, eAuthor, CCC->user.fullname, strlen(CCC->user.fullname));
905 if (sSMTP->preferred_sender_email != NULL)
906 CM_SetField(msg, erFc822Addr, SKEY(sSMTP->preferred_sender_email));
908 CM_SetField(msg, erFc822Addr, CCC->cs_inet_email, strlen(CCC->cs_inet_email));
912 /* Set the "envelope from" address */
913 CM_SetField(msg, eMessagePath, SKEY(sSMTP->from));
915 /* Set the "envelope to" address */
916 CM_SetField(msg, eenVelopeTo, SKEY(sSMTP->recipients));
918 /* Submit the message into the Citadel system. */
919 valid = validate_recipients(
920 ChrPtr(sSMTP->recipients),
921 smtp_get_Recipients(),
922 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
925 /* If there are modules that want to scan this message before final
926 * submission (such as virus checkers or spam filters), call them now
927 * and give them an opportunity to reject the message.
929 if (sSMTP->is_unfiltered) {
933 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
936 if (scan_errors > 0) { /* We don't want this message! */
938 if (CM_IsEmpty(msg, eErrorMsg)) {
939 CM_SetField(msg, eErrorMsg, HKEY("Message rejected by filter"));
942 StrBufPrintf(sSMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
945 else { /* Ok, we'll accept this message. */
946 msgnum = CtdlSubmitMsg(msg, valid, "");
948 StrBufPrintf(sSMTP->OneRcpt, "250 Message accepted.\r\n");
951 StrBufPrintf(sSMTP->OneRcpt, "550 Internal delivery error\r\n");
955 /* For SMTP and ESMTP, just print the result message. For LMTP, we
956 * have to print one result message for each recipient. Since there
957 * is nothing in Citadel which would cause different recipients to
958 * have different results, we can get away with just spitting out the
959 * same message once for each recipient.
961 if (sSMTP->is_lmtp) {
962 for (i=0; i<sSMTP->number_of_recipients; ++i) {
963 cputbuf(sSMTP->OneRcpt);
967 cputbuf(sSMTP->OneRcpt);
970 /* Write something to the syslog(which may or may not be where the
971 * rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
973 syslog((LOG_MAIL | LOG_INFO),
974 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
977 sSMTP->number_of_recipients,
980 ChrPtr(sSMTP->OneRcpt)
985 free_recipients(valid);
986 smtp_data_clear(0, 0); /* clear out the buffers now */
991 * implements the STARTTLS command
993 void smtp_starttls(long offset, long flags)
995 char ok_response[SIZ];
996 char nosup_response[SIZ];
997 char error_response[SIZ];
999 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
1000 sprintf(nosup_response, "554 TLS not supported here\r\n");
1001 sprintf(error_response, "554 Internal error\r\n");
1002 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
1008 * Main command loop for SMTP server sessions.
1010 void smtp_command_loop(void)
1012 static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
1013 struct CitContext *CCC = CC;
1014 citsmtp *sSMTP = SMTP;
1015 const char *pch, *pchs;
1017 char CMD[MaxSMTPCmdLen + 1];
1019 if (sSMTP == NULL) {
1020 syslog(LOG_EMERG, "Session SMTP data is null. WTF? We will crash now.");
1024 time(&CCC->lastcmd);
1025 if (CtdlClientGetLine(sSMTP->Cmd) < 1) {
1026 syslog(LOG_CRIT, "SMTP: client disconnected: ending session.");
1027 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1030 syslog(LOG_DEBUG, "SMTP server: %s", ChrPtr(sSMTP->Cmd));
1032 if (sSMTP->command_state == smtp_user) {
1033 if (!strncmp(ChrPtr(sSMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len))
1034 smtp_try_plain(0, 0);
1040 else if (sSMTP->command_state == smtp_password) {
1041 smtp_get_pass(0, 0);
1045 else if (sSMTP->command_state == smtp_plain) {
1046 smtp_try_plain(0, 0);
1050 pchs = pch = ChrPtr(sSMTP->Cmd);
1052 while ((*pch != '\0') &&
1054 (pch - pchs <= MaxSMTPCmdLen))
1056 CMD[i] = toupper(*pch);
1062 if ((*pch == '\0') ||
1067 if (GetHash(SMTPCmds, CMD, i, &v) &&
1070 smtp_handler_hook *h = (smtp_handler_hook*) v;
1072 if (isblank(pchs[i]))
1080 cprintf("502 I'm afraid I can't do that.\r\n");
1083 void smtp_noop(long offest, long Flags)
1085 cprintf("250 NOOP\r\n");
1088 void smtp_quit(long offest, long Flags)
1090 cprintf("221 Goodbye...\r\n");
1091 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1094 /*****************************************************************************/
1095 /* MODULE INITIALIZATION STUFF */
1096 /*****************************************************************************/
1098 * This cleanup function blows away the temporary memory used by
1101 void smtp_cleanup_function(void)
1103 citsmtp *sSMTP = SMTP;
1104 struct CitContext *CCC = CC;
1106 /* Don't do this stuff if this is not an SMTP session! */
1107 if (CCC->h_command_function != smtp_command_loop) return;
1109 syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
1111 FreeStrBuf(&sSMTP->Cmd);
1112 FreeStrBuf(&sSMTP->helo_node);
1113 FreeStrBuf(&sSMTP->from);
1114 FreeStrBuf(&sSMTP->recipients);
1115 FreeStrBuf(&sSMTP->OneRcpt);
1116 FreeStrBuf(&sSMTP->preferred_sender_email);
1117 FreeStrBuf(&sSMTP->preferred_sender_name);
1122 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1123 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1124 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1125 const char *CitadelServiceSMTP_LMTP="LMTP";
1126 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1129 CTDL_MODULE_INIT(smtp)
1133 SMTPCmds = NewHash(1, NULL);
1135 RegisterSmtpCMD("AUTH", smtp_auth, 0);
1136 RegisterSmtpCMD("DATA", smtp_data, 0);
1137 RegisterSmtpCMD("HELO", smtp_hello, HELO);
1138 RegisterSmtpCMD("EHLO", smtp_hello, EHLO);
1139 RegisterSmtpCMD("LHLO", smtp_hello, LHLO);
1140 RegisterSmtpCMD("HELP", smtp_help, 0);
1141 RegisterSmtpCMD("MAIL", smtp_mail, 0);
1142 RegisterSmtpCMD("NOOP", smtp_noop, 0);
1143 RegisterSmtpCMD("QUIT", smtp_quit, 0);
1144 RegisterSmtpCMD("RCPT", smtp_rcpt, 0);
1145 RegisterSmtpCMD("RSET", smtp_rset, 1);
1147 RegisterSmtpCMD("STARTTLS", smtp_starttls, 0);
1151 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"), /* SMTP MTA */
1156 CitadelServiceSMTP_MTA);
1159 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"), /* SMTPS MTA */
1164 CitadelServiceSMTPS_MTA);
1167 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"), /* SMTP MSA */
1172 CitadelServiceSMTP_MSA);
1174 CtdlRegisterServiceHook(0, /* local LMTP */
1179 CitadelServiceSMTP_LMTP);
1181 CtdlRegisterServiceHook(0, /* local LMTP */
1182 file_lmtp_unfiltered_socket,
1183 lmtp_unfiltered_greeting,
1186 CitadelServiceSMTP_LMTP_UNF);
1188 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1191 /* return our module name for the log */