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);
88 typedef struct _smtp_handler_hook {
93 HashList *SMTPCmds = NULL;
94 #define MaxSMTPCmdLen 10
96 #define RegisterSmtpCMD(First, H, Flags) registerSmtpCMD(HKEY(First), H, Flags)
97 void registerSmtpCMD(const char *First, long FLen, smtp_handler H, int Flags) {
100 if (FLen >= MaxSMTPCmdLen) {
104 h = (smtp_handler_hook*) malloc(sizeof(smtp_handler_hook));
105 memset(h, 0, sizeof(smtp_handler_hook));
109 Put(SMTPCmds, First, FLen, h, NULL);
114 * Here's where our SMTP session begins its happy day.
116 void smtp_greeting(int is_msa) {
117 char message_to_spammer[1024];
119 strcpy(CC->cs_clientname, "SMTP session");
120 CC->internal_pgm = 1;
121 CC->cs_flags |= CS_STEALTH;
122 CC->session_specific_data = malloc(sizeof(citsmtp));
123 memset(SMTP, 0, sizeof(citsmtp));
124 SMTP->is_msa = is_msa;
125 SMTP->Cmd = NewStrBufPlain(NULL, SIZ);
126 SMTP->helo_node = NewStrBuf();
127 SMTP->from = NewStrBufPlain(NULL, SIZ);
128 SMTP->recipients = NewStrBufPlain(NULL, SIZ);
129 SMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
130 SMTP->preferred_sender_email = NULL;
131 SMTP->preferred_sender_name = NULL;
133 /* If this config option is set, reject connections from problem
134 * addresses immediately instead of after they execute a RCPT
136 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (SMTP->is_msa == 0) ) {
137 if (rbl_check(CC->cs_addr, message_to_spammer)) {
138 if (server_shutting_down)
139 cprintf("421 %s\r\n", message_to_spammer);
141 cprintf("550 %s\r\n", message_to_spammer);
142 CC->kill_me = KILLME_SPAMMER;
143 /* no need to free_recipients(valid), it's not allocated yet */
148 /* Otherwise we're either clean or we check later. */
150 if (CC->nologin==1) {
151 cprintf("451 Too many connections are already open; please try again later.\r\n");
152 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
153 /* no need to free_recipients(valid), it's not allocated yet */
157 /* Note: the FQDN *must* appear as the first thing after the 220 code.
158 * Some clients (including citmail.c) depend on it being there.
160 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
165 * SMTPS is just like SMTP, except it goes crypto right away.
167 void smtps_greeting(void) {
168 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
170 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
177 * SMTP MSA port requires authentication.
179 void smtp_msa_greeting(void) {
185 * LMTP is like SMTP but with some extra bonus footage added.
187 void lmtp_greeting(void) {
195 * Generic SMTP MTA greeting
197 void smtp_mta_greeting(void) {
203 * We also have an unfiltered LMTP socket that bypasses spam filters.
205 void lmtp_unfiltered_greeting(void) {
208 SMTP->is_unfiltered = 1;
213 * Login greeting common to all auth methods
215 void smtp_auth_greeting(long offset, long Flags) {
216 cprintf("235 Hello, %s\r\n", CC->user.fullname);
217 syslog(LOG_INFO, "serv_smtp: SMTP authenticated %s", CC->user.fullname);
218 CC->internal_pgm = 0;
219 CC->cs_flags &= ~CS_STEALTH;
224 * Implement HELO and EHLO commands.
226 * which_command: 0=HELO, 1=EHLO, 2=LHLO
228 void smtp_hello(long offset, long which_command) {
230 StrBufAppendBuf (SMTP->helo_node, SMTP->Cmd, offset);
232 if ( (which_command != LHLO) && (SMTP->is_lmtp) ) {
233 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
237 if ( (which_command == LHLO) && (SMTP->is_lmtp == 0) ) {
238 cprintf("500 LHLO is only allowed when running LMTP\r\n");
242 if (which_command == HELO) {
243 cprintf("250 Hello %s (%s [%s])\r\n",
244 ChrPtr(SMTP->helo_node),
250 if (which_command == EHLO) {
251 cprintf("250-Hello %s (%s [%s])\r\n",
252 ChrPtr(SMTP->helo_node),
258 cprintf("250-Greetings and joyous salutations.\r\n");
260 cprintf("250-HELP\r\n");
261 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
265 * Offer TLS, but only if TLS is not already active.
266 * Furthermore, only offer TLS when running on
267 * the SMTP-MSA port, not on the SMTP-MTA port, due to
268 * questionable reliability of TLS in certain sending MTA's.
270 if ( (!CC->redirect_ssl) && (SMTP->is_msa) ) {
271 cprintf("250-STARTTLS\r\n");
273 #endif /* HAVE_OPENSSL */
275 cprintf("250-AUTH LOGIN PLAIN\r\n"
276 "250-AUTH=LOGIN PLAIN\r\n"
284 * Backend function for smtp_webcit_preferences_hack().
285 * Look at a message and determine if it's the preferences file.
287 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
288 struct CtdlMessage *msg;
289 char **webcit_conf = (char **) userdata;
292 return; // already got it
295 msg = CtdlFetchMessage(msgnum, 1);
300 if ( !CM_IsEmpty(msg, eMsgSubject) && (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __"))) {
301 /* This is it! Change ownership of the message text so it doesn't get freed. */
302 *webcit_conf = (char *)msg->cm_fields[eMesageText];
303 msg->cm_fields[eMesageText] = NULL;
310 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
311 * stored in the account's WebCit configuration. We have to fetch it now.
313 void smtp_webcit_preferences_hack(void) {
314 char config_roomname[ROOMNAMELEN];
315 char *webcit_conf = NULL;
317 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CC->user.usernum, USERCONFIGROOM);
318 if (CtdlGetRoom(&CC->room, config_roomname) != 0) {
323 * Find the WebCit configuration message
326 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
332 /* Parse the webcit configuration and attempt to do something useful with it */
333 char *str = webcit_conf;
335 char *this_line = NULL;
336 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
338 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
339 SMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
341 if (!strncasecmp(this_line, "defaultname|", 12)) {
342 SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
344 if ((!strncasecmp(this_line, "defaultname|", 12)) && (SMTP->preferred_sender_name == NULL)) {
345 SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
354 * Implement HELP command.
356 void smtp_help(long offset, long Flags) {
357 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
364 void smtp_get_user(long offset) {
367 StrBufDecodeBase64(SMTP->Cmd);
369 if (CtdlLoginExistingUser(ChrPtr(SMTP->Cmd)) == login_ok) {
370 size_t len = CtdlEncodeBase64(buf, "Password:", 9, 0);
372 if (buf[len - 1] == '\n') {
375 cprintf("334 %s\r\n", buf);
376 SMTP->command_state = smtp_password;
379 cprintf("500 No such user.\r\n");
380 SMTP->command_state = smtp_command;
388 void smtp_get_pass(long offset, long Flags)
392 memset(password, 0, sizeof(password));
393 StrBufDecodeBase64(SMTP->Cmd);
394 syslog(LOG_DEBUG, "serv_smtp: trying <%s>", password);
395 if (CtdlTryPassword(SKEY(SMTP->Cmd)) == pass_ok) {
396 smtp_auth_greeting(offset, Flags);
399 cprintf("535 Authentication failed.\r\n");
401 SMTP->command_state = smtp_command;
406 * Back end for PLAIN auth method (either inline or multistate)
408 void smtp_try_plain(long offset, long Flags) {
409 const char*decoded_authstring;
410 char ident[256] = "";
419 memset(pass, 0, sizeof(pass));
420 decoded_len = StrBufDecodeBase64(SMTP->Cmd);
424 decoded_authstring = ChrPtr(SMTP->Cmd);
426 len = safestrncpy(ident, decoded_authstring, sizeof ident);
428 decoded_len -= len - 1;
429 decoded_authstring += len + 1;
433 len = safestrncpy(user, decoded_authstring, sizeof user);
435 decoded_authstring += len + 1;
436 decoded_len -= len - 1;
441 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
444 plen = sizeof(pass) - 1;
448 SMTP->command_state = smtp_command;
450 if (!IsEmptyStr(ident)) {
451 result = CtdlLoginExistingUser(ident);
454 result = CtdlLoginExistingUser(user);
457 if (result == login_ok) {
458 if (CtdlTryPassword(pass, plen) == pass_ok) {
459 smtp_webcit_preferences_hack();
460 smtp_auth_greeting(offset, Flags);
464 cprintf("504 Authentication failed.\r\n");
469 * Attempt to perform authenticated SMTP
471 void smtp_auth(long offset, long Flags) {
472 char username_prompt[64];
474 char encoded_authstring[1024];
477 cprintf("504 Already logged in.\r\n");
481 extract_token(method, ChrPtr(SMTP->Cmd) + offset, 0, ' ', sizeof method);
483 if (!strncasecmp(method, "login", 5) ) {
484 if (StrLength(SMTP->Cmd) - offset >= 7) {
488 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
489 if (username_prompt[len - 1] == '\n') {
490 username_prompt[len - 1] = '\0';
492 cprintf("334 %s\r\n", username_prompt);
493 SMTP->command_state = smtp_user;
498 if (!strncasecmp(method, "plain", 5) ) {
500 if (num_tokens(ChrPtr(SMTP->Cmd) + offset, ' ') < 2) {
502 SMTP->command_state = smtp_plain;
506 len = extract_token(encoded_authstring,
507 ChrPtr(SMTP->Cmd) + offset,
509 sizeof encoded_authstring);
510 StrBufPlain(SMTP->Cmd, encoded_authstring, len);
511 smtp_try_plain(0, Flags);
515 if (strncasecmp(method, "login", 5) ) {
516 cprintf("504 Unknown authentication method.\r\n");
524 * Implements the RSET (reset state) command.
525 * Currently this just zeroes out the state buffer. If pointers to data
526 * allocated with malloc() are ever placed in the state buffer, we have to
527 * be sure to free() them first!
529 * Set do_response to nonzero to output the SMTP RSET response code.
531 void smtp_rset(long offset, long do_response) {
533 * Our entire SMTP state is discarded when a RSET command is issued,
534 * but we need to preserve this one little piece of information, so
535 * we save it for later.
538 FlushStrBuf(SMTP->Cmd);
539 FlushStrBuf(SMTP->helo_node);
540 FlushStrBuf(SMTP->from);
541 FlushStrBuf(SMTP->recipients);
542 FlushStrBuf(SMTP->OneRcpt);
544 SMTP->command_state = 0;
545 SMTP->number_of_recipients = 0;
546 SMTP->delivery_mode = 0;
547 SMTP->message_originated_locally = 0;
550 * we must remember is_lmtp & is_unfiltered.
554 * It is somewhat ambiguous whether we want to log out when a RSET
555 * command is issued. Here's the code to do it. It is commented out
556 * because some clients (such as Pine) issue RSET commands before
557 * each message, but still expect to be logged in.
559 * if (CC->logged_in) {
565 cprintf("250 Zap!\r\n");
571 * Clear out the portions of the state buffer that need to be cleared out
572 * after the DATA command finishes.
574 void smtp_data_clear(long offset, long flags) {
575 FlushStrBuf(SMTP->from);
576 FlushStrBuf(SMTP->recipients);
577 FlushStrBuf(SMTP->OneRcpt);
578 SMTP->number_of_recipients = 0;
579 SMTP->delivery_mode = 0;
580 SMTP->message_originated_locally = 0;
585 * Implements the "MAIL FROM:" command
587 void smtp_mail(long offset, long flags) {
592 if (StrLength(SMTP->from) > 0) {
593 cprintf("503 Only one sender permitted\r\n");
597 if (strncasecmp(ChrPtr(SMTP->Cmd) + offset, "From:", 5)) {
598 cprintf("501 Syntax error\r\n");
602 StrBufAppendBuf(SMTP->from, SMTP->Cmd, offset);
603 StrBufTrim(SMTP->from);
604 if (strchr(ChrPtr(SMTP->from), '<') != NULL) {
605 StrBufStripAllBut(SMTP->from, '<', '>');
608 /* We used to reject empty sender names, until it was brought to our
609 * attention that RFC1123 5.2.9 requires that this be allowed. So now
610 * we allow it, but replace the empty string with a fake
611 * address so we don't have to contend with the empty string causing
612 * other code to fail when it's expecting something there.
614 if (StrLength(SMTP->from) == 0) {
615 StrBufPlain(SMTP->from, HKEY("someone@example.com"));
618 /* If this SMTP connection is from a logged-in user, force the 'from'
619 * to be the user's Internet e-mail address as Citadel knows it.
622 StrBufPlain(SMTP->from, CC->cs_inet_email, -1);
623 cprintf("250 Sender ok <%s>\r\n", ChrPtr(SMTP->from));
624 SMTP->message_originated_locally = 1;
628 else if (SMTP->is_lmtp) {
629 /* Bypass forgery checking for LMTP */
632 /* Otherwise, make sure outsiders aren't trying to forge mail from
633 * this system (unless, of course, c_allow_spoofing is enabled)
635 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
636 process_rfc822_addr(ChrPtr(SMTP->from), user, node, name);
637 syslog(LOG_DEBUG, "serv_smtp: claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
638 ChrPtr(SMTP->from), user, node, name
640 if (CtdlHostAlias(node) != hostalias_nomatch) {
641 cprintf("550 You must log in to send mail from %s\r\n", node);
642 FlushStrBuf(SMTP->from);
643 syslog(LOG_DEBUG, "serv_smtp: rejecting unauthenticated mail from %s", node);
648 cprintf("250 Sender ok\r\n");
653 * Implements the "RCPT To:" command
655 void smtp_rcpt(long offset, long flags) {
656 char message_to_spammer[SIZ];
657 struct recptypes *valid = NULL;
659 if (StrLength(SMTP->from) == 0) {
660 cprintf("503 Need MAIL before RCPT\r\n");
664 if (strncasecmp(ChrPtr(SMTP->Cmd) + offset, "To:", 3)) {
665 cprintf("501 Syntax error\r\n");
669 if ( (SMTP->is_msa) && (!CC->logged_in) ) {
670 cprintf("550 You must log in to send mail on this port.\r\n");
671 FlushStrBuf(SMTP->from);
674 FlushStrBuf(SMTP->OneRcpt);
675 StrBufAppendBuf(SMTP->OneRcpt, SMTP->Cmd, offset + 3);
676 StrBufTrim(SMTP->OneRcpt);
677 StrBufStripAllBut(SMTP->OneRcpt, '<', '>');
679 if ( (StrLength(SMTP->OneRcpt) + StrLength(SMTP->recipients)) >= SIZ) {
680 cprintf("452 Too many recipients\r\n");
685 if ( (!CC->logged_in) /* Don't RBL authenticated users */
686 && (!SMTP->is_lmtp) ) { /* Don't RBL LMTP clients */
687 if (CtdlGetConfigInt("c_rbl_at_greeting") == 0) { /* Don't RBL again if we already did it */
688 if (rbl_check(CC->cs_addr, message_to_spammer)) {
689 if (server_shutting_down)
690 cprintf("421 %s\r\n", message_to_spammer);
692 cprintf("550 %s\r\n", message_to_spammer);
693 /* no need to free_recipients(valid), it's not allocated yet */
699 valid = validate_recipients(
700 ChrPtr(SMTP->OneRcpt),
701 smtp_get_Recipients(),
702 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
704 if (valid->num_error != 0) {
705 cprintf("550 %s\r\n", valid->errormsg);
706 free_recipients(valid);
710 if (valid->num_internet > 0) {
712 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
713 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n",
714 ChrPtr(SMTP->OneRcpt));
715 free_recipients(valid);
721 if (valid->num_internet > 0) {
722 if ( (SMTP->message_originated_locally == 0)
723 && (SMTP->is_lmtp == 0) ) {
724 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(SMTP->OneRcpt));
725 free_recipients(valid);
730 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(SMTP->OneRcpt));
731 if (StrLength(SMTP->recipients) > 0) {
732 StrBufAppendBufPlain(SMTP->recipients, HKEY(","), 0);
734 StrBufAppendBuf(SMTP->recipients, SMTP->OneRcpt, 0);
735 SMTP->number_of_recipients ++;
737 free_recipients(valid);
743 * Implements the DATA command
745 void smtp_data(long offset, long flags) {
748 struct CtdlMessage *msg = NULL;
751 struct recptypes *valid;
755 if (StrLength(SMTP->from) == 0) {
756 cprintf("503 Need MAIL command first.\r\n");
760 if (SMTP->number_of_recipients < 1) {
761 cprintf("503 Need RCPT command first.\r\n");
765 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
767 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
768 defbody = NewStrBufPlain(NULL, SIZ);
770 if (defbody != NULL) {
771 if (SMTP->is_lmtp && (CC->cs_UDSclientUID != -1)) {
774 "Received: from %s (Citadel from userid %ld)\n"
776 ChrPtr(SMTP->helo_node),
777 (long int) CC->cs_UDSclientUID,
778 CtdlGetConfigStr("c_fqdn"),
784 "Received: from %s (%s [%s])\n"
786 ChrPtr(SMTP->helo_node),
789 CtdlGetConfigStr("c_fqdn"),
793 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1);
794 FreeStrBuf(&defbody);
796 cprintf("550 Unable to save message: internal error.\r\n");
800 syslog(LOG_DEBUG, "serv_smtp: converting message...");
801 msg = convert_internet_message_buf(&body);
803 /* If the user is locally authenticated, FORCE the From: header to
804 * show up as the real sender. Yes, this violates the RFC standard,
805 * but IT MAKES SENSE. If you prefer strict RFC adherence over
806 * common sense, you can disable this in the configuration.
808 * We also set the "message room name" ('O' field) to MAILROOM
809 * (which is Mail> on most systems) to prevent it from getting set
810 * to something ugly like "0000058008.Sent Items>" when the message
811 * is read with a Citadel client.
813 if ( (CC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
816 if (!CM_IsEmpty(msg, erFc822Addr) &&
817 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
818 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
820 if (!IsEmptyStr(CC->cs_inet_email))
821 validemail = strcmp(CC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
823 (!IsEmptyStr(CC->cs_inet_other_emails)))
825 int num_secondary_emails = 0;
827 num_secondary_emails = num_tokens(CC->cs_inet_other_emails, '|');
828 for (i=0; i < num_secondary_emails && !validemail; ++i) {
830 extract_token(buf, CC->cs_inet_other_emails,i,'|',sizeof CC->cs_inet_other_emails);
831 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
836 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
837 syslog(LOG_ERR, "serv_smtp: invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
838 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
842 CM_SetField(msg, eOriginalRoom, HKEY(MAILROOM));
843 if (SMTP->preferred_sender_name != NULL)
844 CM_SetField(msg, eAuthor, SKEY(SMTP->preferred_sender_name));
846 CM_SetField(msg, eAuthor, CC->user.fullname, strlen(CC->user.fullname));
849 if (SMTP->preferred_sender_email != NULL) {
850 CM_SetField(msg, erFc822Addr, SKEY(SMTP->preferred_sender_email));
853 CM_SetField(msg, erFc822Addr, CC->cs_inet_email, strlen(CC->cs_inet_email));
858 /* Set the "envelope from" address */
859 CM_SetField(msg, eMessagePath, SKEY(SMTP->from));
861 /* Set the "envelope to" address */
862 CM_SetField(msg, eenVelopeTo, SKEY(SMTP->recipients));
864 /* Submit the message into the Citadel system. */
865 valid = validate_recipients(
866 ChrPtr(SMTP->recipients),
867 smtp_get_Recipients(),
868 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
871 /* If there are modules that want to scan this message before final
872 * submission (such as virus checkers or spam filters), call them now
873 * and give them an opportunity to reject the message.
875 if (SMTP->is_unfiltered) {
879 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
882 if (scan_errors > 0) { /* We don't want this message! */
884 if (CM_IsEmpty(msg, eErrorMsg)) {
885 CM_SetField(msg, eErrorMsg, HKEY("Message rejected by filter"));
888 StrBufPrintf(SMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
891 else { /* Ok, we'll accept this message. */
892 msgnum = CtdlSubmitMsg(msg, valid, "");
894 StrBufPrintf(SMTP->OneRcpt, "250 Message accepted.\r\n");
897 StrBufPrintf(SMTP->OneRcpt, "550 Internal delivery error\r\n");
901 /* For SMTP and ESMTP, just print the result message. For LMTP, we
902 * have to print one result message for each recipient. Since there
903 * is nothing in Citadel which would cause different recipients to
904 * have different results, we can get away with just spitting out the
905 * same message once for each recipient.
908 for (i=0; i<SMTP->number_of_recipients; ++i) {
909 cputbuf(SMTP->OneRcpt);
913 cputbuf(SMTP->OneRcpt);
916 /* Write something to the syslog(which may or may not be where the
917 * rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
919 syslog((LOG_MAIL | LOG_INFO),
920 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
923 SMTP->number_of_recipients,
926 ChrPtr(SMTP->OneRcpt)
931 free_recipients(valid);
932 smtp_data_clear(0, 0); /* clear out the buffers now */
937 * implements the STARTTLS command
939 void smtp_starttls(long offset, long flags) {
940 char ok_response[SIZ];
941 char nosup_response[SIZ];
942 char error_response[SIZ];
944 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
945 sprintf(nosup_response, "554 TLS not supported here\r\n");
946 sprintf(error_response, "554 Internal error\r\n");
947 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
953 * Main command loop for SMTP server sessions.
955 void smtp_command_loop(void) {
956 static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
957 const char *pch, *pchs;
959 char CMD[MaxSMTPCmdLen + 1];
962 syslog(LOG_ERR, "serv_smtp: Session SMTP data is null. WTF? We will crash now.");
967 if (CtdlClientGetLine(SMTP->Cmd) < 1) {
968 syslog(LOG_INFO, "SMTP: client disconnected: ending session.");
969 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
972 syslog(LOG_DEBUG, "serv_smtp: %s", ChrPtr(SMTP->Cmd));
974 if (SMTP->command_state == smtp_user) {
975 if (!strncmp(ChrPtr(SMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len)) {
976 smtp_try_plain(0, 0);
984 else if (SMTP->command_state == smtp_password) {
989 else if (SMTP->command_state == smtp_plain) {
990 smtp_try_plain(0, 0);
994 pchs = pch = ChrPtr(SMTP->Cmd);
996 while ((*pch != '\0') && (!isblank(*pch)) && (pch - pchs <= MaxSMTPCmdLen)) {
997 CMD[i] = toupper(*pch);
1003 if ((*pch == '\0') || (isblank(*pch))) {
1006 if (GetHash(SMTPCmds, CMD, i, &v) &&
1009 smtp_handler_hook *h = (smtp_handler_hook*) v;
1011 if (isblank(pchs[i]))
1019 cprintf("502 I'm afraid I can't do that.\r\n");
1023 void smtp_noop(long offest, long Flags) {
1024 cprintf("250 NOOP\r\n");
1028 void smtp_quit(long offest, long Flags) {
1029 cprintf("221 Goodbye...\r\n");
1030 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1034 /*****************************************************************************/
1035 /* MODULE INITIALIZATION STUFF */
1036 /*****************************************************************************/
1038 * This cleanup function blows away the temporary memory used by
1041 void smtp_cleanup_function(void)
1043 /* Don't do this stuff if this is not an SMTP session! */
1044 if (CC->h_command_function != smtp_command_loop) return;
1046 syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
1048 FreeStrBuf(&SMTP->Cmd);
1049 FreeStrBuf(&SMTP->helo_node);
1050 FreeStrBuf(&SMTP->from);
1051 FreeStrBuf(&SMTP->recipients);
1052 FreeStrBuf(&SMTP->OneRcpt);
1053 FreeStrBuf(&SMTP->preferred_sender_email);
1054 FreeStrBuf(&SMTP->preferred_sender_name);
1059 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1060 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1061 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1062 const char *CitadelServiceSMTP_LMTP="LMTP";
1063 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1066 CTDL_MODULE_INIT(smtp)
1069 SMTPCmds = NewHash(1, NULL);
1071 RegisterSmtpCMD("AUTH", smtp_auth, 0);
1072 RegisterSmtpCMD("DATA", smtp_data, 0);
1073 RegisterSmtpCMD("HELO", smtp_hello, HELO);
1074 RegisterSmtpCMD("EHLO", smtp_hello, EHLO);
1075 RegisterSmtpCMD("LHLO", smtp_hello, LHLO);
1076 RegisterSmtpCMD("HELP", smtp_help, 0);
1077 RegisterSmtpCMD("MAIL", smtp_mail, 0);
1078 RegisterSmtpCMD("NOOP", smtp_noop, 0);
1079 RegisterSmtpCMD("QUIT", smtp_quit, 0);
1080 RegisterSmtpCMD("RCPT", smtp_rcpt, 0);
1081 RegisterSmtpCMD("RSET", smtp_rset, 1);
1083 RegisterSmtpCMD("STARTTLS", smtp_starttls, 0);
1087 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"), /* SMTP MTA */
1092 CitadelServiceSMTP_MTA);
1095 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"), /* SMTPS MTA */
1100 CitadelServiceSMTPS_MTA);
1103 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"), /* SMTP MSA */
1108 CitadelServiceSMTP_MSA);
1110 CtdlRegisterServiceHook(0, /* local LMTP */
1115 CitadelServiceSMTP_LMTP);
1117 CtdlRegisterServiceHook(0, /* local LMTP */
1118 file_lmtp_unfiltered_socket,
1119 lmtp_unfiltered_greeting,
1122 CitadelServiceSMTP_LMTP_UNF);
1124 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1127 /* return our module name for the log */