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-2013 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 HashList *SMTPCmds = NULL;
105 #define MaxSMTPCmdLen 10
107 #define RegisterSmtpCMD(First, H, Flags) \
108 registerSmtpCMD(HKEY(First), H, Flags)
109 void registerSmtpCMD(const char *First, long FLen,
113 smtp_handler_hook *h;
115 if (FLen >= MaxSMTPCmdLen)
116 cit_panic_backtrace (0);
118 h = (smtp_handler_hook*) malloc(sizeof(smtp_handler_hook));
119 memset(h, 0, sizeof(smtp_handler_hook));
123 Put(SMTPCmds, First, FLen, h, NULL);
126 void smtp_cleanup(void)
128 DeleteHash(&SMTPCmds);
132 * Here's where our SMTP session begins its happy day.
134 void smtp_greeting(int is_msa)
137 char message_to_spammer[1024];
139 strcpy(CC->cs_clientname, "SMTP session");
140 CC->internal_pgm = 1;
141 CC->cs_flags |= CS_STEALTH;
142 CC->session_specific_data = malloc(sizeof(citsmtp));
143 memset(SMTP, 0, sizeof(citsmtp));
145 sSMTP->is_msa = is_msa;
146 sSMTP->Cmd = NewStrBufPlain(NULL, SIZ);
147 sSMTP->helo_node = NewStrBuf();
148 sSMTP->from = NewStrBufPlain(NULL, SIZ);
149 sSMTP->recipients = NewStrBufPlain(NULL, SIZ);
150 sSMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
151 sSMTP->preferred_sender_email = NULL;
152 sSMTP->preferred_sender_name = NULL;
154 /* If this config option is set, reject connections from problem
155 * addresses immediately instead of after they execute a RCPT
157 if ( (config.c_rbl_at_greeting) && (sSMTP->is_msa == 0) ) {
158 if (rbl_check(message_to_spammer)) {
159 if (server_shutting_down)
160 cprintf("421 %s\r\n", message_to_spammer);
162 cprintf("550 %s\r\n", message_to_spammer);
163 CC->kill_me = KILLME_SPAMMER;
164 /* no need to free_recipients(valid), it's not allocated yet */
169 /* Otherwise we're either clean or we check later. */
171 if (CC->nologin==1) {
172 cprintf("451 Too many connections are already open; please try again later.\r\n");
173 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
174 /* no need to free_recipients(valid), it's not allocated yet */
178 /* Note: the FQDN *must* appear as the first thing after the 220 code.
179 * Some clients (including citmail.c) depend on it being there.
181 cprintf("220 %s ESMTP Citadel server ready.\r\n", config.c_fqdn);
186 * SMTPS is just like SMTP, except it goes crypto right away.
188 void smtps_greeting(void) {
189 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
191 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
198 * SMTP MSA port requires authentication.
200 void smtp_msa_greeting(void) {
206 * LMTP is like SMTP but with some extra bonus footage added.
208 void lmtp_greeting(void) {
216 * Generic SMTP MTA greeting
218 void smtp_mta_greeting(void) {
224 * We also have an unfiltered LMTP socket that bypasses spam filters.
226 void lmtp_unfiltered_greeting(void) {
232 sSMTP->is_unfiltered = 1;
237 * Login greeting common to all auth methods
239 void smtp_auth_greeting(long offset, long Flags) {
240 cprintf("235 Hello, %s\r\n", CC->user.fullname);
241 syslog(LOG_NOTICE, "SMTP authenticated %s\n", CC->user.fullname);
242 CC->internal_pgm = 0;
243 CC->cs_flags &= ~CS_STEALTH;
248 * Implement HELO and EHLO commands.
250 * which_command: 0=HELO, 1=EHLO, 2=LHLO
252 void smtp_hello(long offset, long which_command)
254 citsmtp *sSMTP = SMTP;
256 StrBufAppendBuf (sSMTP->helo_node, sSMTP->Cmd, offset);
258 if ( (which_command != LHLO) && (sSMTP->is_lmtp) ) {
259 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
263 if ( (which_command == LHLO) && (sSMTP->is_lmtp == 0) ) {
264 cprintf("500 LHLO is only allowed when running LMTP\r\n");
268 if (which_command == HELO) {
269 cprintf("250 Hello %s (%s [%s])\r\n",
270 ChrPtr(sSMTP->helo_node),
276 if (which_command == EHLO) {
277 cprintf("250-Hello %s (%s [%s])\r\n",
278 ChrPtr(sSMTP->helo_node),
284 cprintf("250-Greetings and joyous salutations.\r\n");
286 cprintf("250-HELP\r\n");
287 cprintf("250-SIZE %ld\r\n", config.c_maxmsglen);
291 * Offer TLS, but only if TLS is not already active.
292 * Furthermore, only offer TLS when running on
293 * the SMTP-MSA port, not on the SMTP-MTA port, due to
294 * questionable reliability of TLS in certain sending MTA's.
296 if ( (!CC->redirect_ssl) && (sSMTP->is_msa) ) {
297 cprintf("250-STARTTLS\r\n");
299 #endif /* HAVE_OPENSSL */
301 cprintf("250-AUTH LOGIN PLAIN\r\n"
302 "250-AUTH=LOGIN PLAIN\r\n"
310 * Backend function for smtp_webcit_preferences_hack().
311 * Look at a message and determine if it's the preferences file.
313 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
314 struct CtdlMessage *msg;
315 char **webcit_conf = (char **) userdata;
318 return; // already got it
321 msg = CtdlFetchMessage(msgnum, 1);
326 if ( !CM_IsEmpty(msg, eMsgSubject) &&
327 (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __")))
329 /* This is it! Change ownership of the message text so it doesn't get freed. */
330 *webcit_conf = (char *)msg->cm_fields[eMesageText];
331 msg->cm_fields[eMesageText] = NULL;
338 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
339 * stored in the account's WebCit configuration. We have to fetch it now.
341 void smtp_webcit_preferences_hack(void) {
342 char config_roomname[ROOMNAMELEN];
343 char *webcit_conf = NULL;
344 citsmtp *sSMTP = SMTP;
346 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CC->user.usernum, USERCONFIGROOM);
347 if (CtdlGetRoom(&CC->room, config_roomname) != 0) {
352 * Find the WebCit configuration message
355 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
361 /* Parse the webcit configuration and attempt to do something useful with it */
362 char *str = webcit_conf;
364 char *this_line = NULL;
365 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
367 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
368 sSMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
370 if (!strncasecmp(this_line, "defaultname|", 12)) {
371 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
373 if ((!strncasecmp(this_line, "defaultname|", 12)) && (sSMTP->preferred_sender_name == NULL)) {
374 sSMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
384 * Implement HELP command.
386 void smtp_help(long offset, long Flags) {
387 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
394 void smtp_get_user(long offset)
398 citsmtp *sSMTP = SMTP;
400 CtdlDecodeBase64(username, ChrPtr(sSMTP->Cmd) + offset, SIZ);
401 /* syslog(LOG_DEBUG, "Trying <%s>\n", username); */
402 if (CtdlLoginExistingUser(NULL, username) == login_ok) {
403 CtdlEncodeBase64(buf, "Password:", 9, 0);
404 cprintf("334 %s\r\n", buf);
405 sSMTP->command_state = smtp_password;
408 cprintf("500 No such user.\r\n");
409 sSMTP->command_state = smtp_command;
417 void smtp_get_pass(long offset, long Flags)
419 citsmtp *sSMTP = SMTP;
423 memset(password, 0, sizeof(password));
424 len = CtdlDecodeBase64(password, ChrPtr(sSMTP->Cmd), SIZ);
425 /* syslog(LOG_DEBUG, "Trying <%s>\n", password); */
426 if (CtdlTryPassword(password, len) == pass_ok) {
427 smtp_auth_greeting(offset, Flags);
430 cprintf("535 Authentication failed.\r\n");
432 sSMTP->command_state = smtp_command;
437 * Back end for PLAIN auth method (either inline or multistate)
439 void smtp_try_plain(long offset, long Flags)
441 citsmtp *sSMTP = SMTP;
442 const char*decoded_authstring;
443 char ident[256] = "";
451 memset(pass, 0, sizeof(pass));
452 decoded_len = StrBufDecodeBase64(sSMTP->Cmd);
456 decoded_authstring = ChrPtr(sSMTP->Cmd);
458 len = safestrncpy(ident, decoded_authstring, sizeof ident);
460 decoded_len -= len - 1;
461 decoded_authstring += len + 1;
465 len = safestrncpy(user, decoded_authstring, sizeof user);
467 decoded_authstring += len + 1;
468 decoded_len -= len - 1;
473 len = safestrncpy(pass, decoded_authstring, sizeof pass);
476 len = sizeof(pass) - 1;
480 sSMTP->command_state = smtp_command;
482 if (!IsEmptyStr(ident)) {
483 result = CtdlLoginExistingUser(user, ident);
486 result = CtdlLoginExistingUser(NULL, user);
489 if (result == login_ok) {
490 if (CtdlTryPassword(pass, len) == pass_ok) {
491 smtp_webcit_preferences_hack();
492 smtp_auth_greeting(offset, Flags);
496 cprintf("504 Authentication failed.\r\n");
501 * Attempt to perform authenticated SMTP
503 void smtp_auth(long offset, long Flags)
505 citsmtp *sSMTP = SMTP;
506 char username_prompt[64];
508 char encoded_authstring[1024];
511 cprintf("504 Already logged in.\r\n");
515 extract_token(method, ChrPtr(sSMTP->Cmd) + offset, 0, ' ', sizeof method);
517 if (!strncasecmp(method, "login", 5) ) {
518 if (StrLength(sSMTP->Cmd) - offset >= 7) {
522 CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
523 cprintf("334 %s\r\n", username_prompt);
524 sSMTP->command_state = smtp_user;
529 if (!strncasecmp(method, "plain", 5) ) {
531 if (num_tokens(ChrPtr(sSMTP->Cmd) + offset, ' ') < 2) {
533 SMTP->command_state = smtp_plain;
537 len = extract_token(encoded_authstring,
538 ChrPtr(sSMTP->Cmd) + offset,
540 sizeof encoded_authstring);
541 StrBufPlain(sSMTP->Cmd, encoded_authstring, len);
542 smtp_try_plain(0, Flags);
546 if (strncasecmp(method, "login", 5) ) {
547 cprintf("504 Unknown authentication method.\r\n");
555 * Implements the RSET (reset state) command.
556 * Currently this just zeroes out the state buffer. If pointers to data
557 * allocated with malloc() are ever placed in the state buffer, we have to
558 * be sure to free() them first!
560 * Set do_response to nonzero to output the SMTP RSET response code.
562 void smtp_rset(long offset, long do_response) {
563 citsmtp *sSMTP = SMTP;
566 * Our entire SMTP state is discarded when a RSET command is issued,
567 * but we need to preserve this one little piece of information, so
568 * we save it for later.
571 FlushStrBuf(sSMTP->Cmd);
572 FlushStrBuf(sSMTP->helo_node);
573 FlushStrBuf(sSMTP->from);
574 FlushStrBuf(sSMTP->recipients);
575 FlushStrBuf(sSMTP->OneRcpt);
577 sSMTP->command_state = 0;
578 sSMTP->number_of_recipients = 0;
579 sSMTP->delivery_mode = 0;
580 sSMTP->message_originated_locally = 0;
583 * we must remember is_lmtp & is_unfiltered.
587 * It is somewhat ambiguous whether we want to log out when a RSET
588 * command is issued. Here's the code to do it. It is commented out
589 * because some clients (such as Pine) issue RSET commands before
590 * each message, but still expect to be logged in.
592 * if (CC->logged_in) {
598 cprintf("250 Zap!\r\n");
603 * Clear out the portions of the state buffer that need to be cleared out
604 * after the DATA command finishes.
606 void smtp_data_clear(long offset, long flags)
608 citsmtp *sSMTP = SMTP;
610 FlushStrBuf(sSMTP->from);
611 FlushStrBuf(sSMTP->recipients);
612 FlushStrBuf(sSMTP->OneRcpt);
613 sSMTP->number_of_recipients = 0;
614 sSMTP->delivery_mode = 0;
615 sSMTP->message_originated_locally = 0;
619 * Implements the "MAIL FROM:" command
621 void smtp_mail(long offset, long flags) {
625 citsmtp *sSMTP = SMTP;
627 if (StrLength(sSMTP->from) > 0) {
628 cprintf("503 Only one sender permitted\r\n");
632 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "From:", 5)) {
633 cprintf("501 Syntax error\r\n");
637 StrBufAppendBuf(sSMTP->from, sSMTP->Cmd, offset);
638 StrBufTrim(sSMTP->from);
639 if (strchr(ChrPtr(sSMTP->from), '<') != NULL) {
640 StrBufStripAllBut(sSMTP->from, '<', '>');
643 /* We used to reject empty sender names, until it was brought to our
644 * attention that RFC1123 5.2.9 requires that this be allowed. So now
645 * we allow it, but replace the empty string with a fake
646 * address so we don't have to contend with the empty string causing
647 * other code to fail when it's expecting something there.
649 if (StrLength(sSMTP->from) == 0) {
650 StrBufPlain(sSMTP->from, HKEY("someone@example.com"));
653 /* If this SMTP connection is from a logged-in user, force the 'from'
654 * to be the user's Internet e-mail address as Citadel knows it.
657 StrBufPlain(sSMTP->from, CC->cs_inet_email, -1);
658 cprintf("250 Sender ok <%s>\r\n", ChrPtr(sSMTP->from));
659 sSMTP->message_originated_locally = 1;
663 else if (sSMTP->is_lmtp) {
664 /* Bypass forgery checking for LMTP */
667 /* Otherwise, make sure outsiders aren't trying to forge mail from
668 * this system (unless, of course, c_allow_spoofing is enabled)
670 else if (config.c_allow_spoofing == 0) {
671 process_rfc822_addr(ChrPtr(sSMTP->from), user, node, name);
672 syslog(LOG_DEBUG, "Claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
673 ChrPtr(sSMTP->from), user, node, name
675 if (CtdlHostAlias(node) != hostalias_nomatch) {
676 cprintf("550 You must log in to send mail from %s\r\n", node);
677 FlushStrBuf(sSMTP->from);
678 syslog(LOG_DEBUG, "Rejecting unauthenticated mail from %s", node);
683 cprintf("250 Sender ok\r\n");
689 * Implements the "RCPT To:" command
691 void smtp_rcpt(long offset, long flags)
693 struct CitContext *CCC = CC;
694 char message_to_spammer[SIZ];
695 recptypes *valid = NULL;
696 citsmtp *sSMTP = SMTP;
698 if (StrLength(sSMTP->from) == 0) {
699 cprintf("503 Need MAIL before RCPT\r\n");
703 if (strncasecmp(ChrPtr(sSMTP->Cmd) + offset, "To:", 3)) {
704 cprintf("501 Syntax error\r\n");
708 if ( (sSMTP->is_msa) && (!CCC->logged_in) ) {
709 cprintf("550 You must log in to send mail on this port.\r\n");
710 FlushStrBuf(sSMTP->from);
713 FlushStrBuf(sSMTP->OneRcpt);
714 StrBufAppendBuf(sSMTP->OneRcpt, sSMTP->Cmd, offset + 3);
715 StrBufTrim(sSMTP->OneRcpt);
716 StrBufStripAllBut(sSMTP->OneRcpt, '<', '>');
718 if ( (StrLength(sSMTP->OneRcpt) + StrLength(sSMTP->recipients)) >= SIZ) {
719 cprintf("452 Too many recipients\r\n");
724 if ( (!CCC->logged_in) /* Don't RBL authenticated users */
725 && (!sSMTP->is_lmtp) ) { /* Don't RBL LMTP clients */
726 if (config.c_rbl_at_greeting == 0) { /* Don't RBL again if we already did it */
727 if (rbl_check(message_to_spammer)) {
728 if (server_shutting_down)
729 cprintf("421 %s\r\n", message_to_spammer);
731 cprintf("550 %s\r\n", message_to_spammer);
732 /* no need to free_recipients(valid), it's not allocated yet */
738 valid = validate_recipients(
739 ChrPtr(sSMTP->OneRcpt),
740 smtp_get_Recipients(),
741 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
743 if (valid->num_error != 0) {
744 cprintf("550 %s\r\n", valid->errormsg);
745 free_recipients(valid);
749 if (valid->num_internet > 0) {
750 if (CCC->logged_in) {
751 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
752 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n",
753 ChrPtr(sSMTP->OneRcpt));
754 free_recipients(valid);
760 if (valid->num_internet > 0) {
761 if ( (sSMTP->message_originated_locally == 0)
762 && (sSMTP->is_lmtp == 0) ) {
763 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(sSMTP->OneRcpt));
764 free_recipients(valid);
769 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(sSMTP->OneRcpt));
770 if (StrLength(sSMTP->recipients) > 0) {
771 StrBufAppendBufPlain(sSMTP->recipients, HKEY(","), 0);
773 StrBufAppendBuf(sSMTP->recipients, sSMTP->OneRcpt, 0);
774 sSMTP->number_of_recipients ++;
776 free_recipients(valid);
784 * Implements the DATA command
786 void smtp_data(long offset, long flags)
788 struct CitContext *CCC = CC;
791 struct CtdlMessage *msg = NULL;
797 citsmtp *sSMTP = SMTP;
799 if (StrLength(sSMTP->from) == 0) {
800 cprintf("503 Need MAIL command first.\r\n");
804 if (sSMTP->number_of_recipients < 1) {
805 cprintf("503 Need RCPT command first.\r\n");
809 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
811 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
812 defbody = NewStrBufPlain(NULL, SIZ);
814 if (defbody != NULL) {
815 if (sSMTP->is_lmtp && (CCC->cs_UDSclientUID != -1)) {
818 "Received: from %s (Citadel from userid %ld)\n"
820 ChrPtr(sSMTP->helo_node),
821 (long int) CCC->cs_UDSclientUID,
828 "Received: from %s (%s [%s])\n"
830 ChrPtr(sSMTP->helo_node),
837 body = CtdlReadMessageBodyBuf(HKEY("."), config.c_maxmsglen, defbody, 1, NULL);
838 FreeStrBuf(&defbody);
840 cprintf("550 Unable to save message: internal error.\r\n");
844 syslog(LOG_DEBUG, "Converting message...\n");
845 msg = convert_internet_message_buf(&body);
847 /* If the user is locally authenticated, FORCE the From: header to
848 * show up as the real sender. Yes, this violates the RFC standard,
849 * but IT MAKES SENSE. If you prefer strict RFC adherence over
850 * common sense, you can disable this in the configuration.
852 * We also set the "message room name" ('O' field) to MAILROOM
853 * (which is Mail> on most systems) to prevent it from getting set
854 * to something ugly like "0000058008.Sent Items>" when the message
855 * is read with a Citadel client.
857 if ( (CCC->logged_in) && (config.c_rfc822_strict_from != CFG_SMTP_FROM_NOFILTER) ) {
860 if (!CM_IsEmpty(msg, erFc822Addr) &&
861 ((config.c_rfc822_strict_from == CFG_SMTP_FROM_CORRECT) ||
862 (config.c_rfc822_strict_from == CFG_SMTP_FROM_REJECT) ) )
864 if (!IsEmptyStr(CCC->cs_inet_email))
865 validemail = strcmp(CCC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
867 (!IsEmptyStr(CCC->cs_inet_other_emails)))
869 int num_secondary_emails = 0;
871 num_secondary_emails = num_tokens(CCC->cs_inet_other_emails, '|');
872 for (i=0; i < num_secondary_emails && !validemail; ++i) {
874 extract_token(buf, CCC->cs_inet_other_emails,i,'|',sizeof CCC->cs_inet_other_emails);
875 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
880 if (!validemail && (config.c_rfc822_strict_from == CFG_SMTP_FROM_REJECT)) {
881 syslog(LOG_ERR, "invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
882 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
886 CM_SetField(msg, eNodeName, CFG_KEY(c_nodename));
887 CM_SetField(msg, eHumanNode, CFG_KEY(c_humannode));
888 CM_SetField(msg, eOriginalRoom, HKEY(MAILROOM));
889 if (sSMTP->preferred_sender_name != NULL)
890 CM_SetField(msg, eAuthor, SKEY(sSMTP->preferred_sender_name));
892 CM_SetField(msg, eAuthor, CCC->user.fullname, strlen(CCC->user.fullname));
895 if (sSMTP->preferred_sender_email != NULL)
896 CM_SetField(msg, erFc822Addr, SKEY(sSMTP->preferred_sender_email));
898 CM_SetField(msg, erFc822Addr, CCC->cs_inet_email, strlen(CCC->cs_inet_email));
902 /* Set the "envelope from" address */
903 CM_SetField(msg, eMessagePath, SKEY(sSMTP->from));
905 /* Set the "envelope to" address */
906 CM_SetField(msg, eenVelopeTo, SKEY(sSMTP->recipients));
908 /* Submit the message into the Citadel system. */
909 valid = validate_recipients(
910 ChrPtr(sSMTP->recipients),
911 smtp_get_Recipients(),
912 (sSMTP->is_lmtp)? POST_LMTP: (CCC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
915 /* If there are modules that want to scan this message before final
916 * submission (such as virus checkers or spam filters), call them now
917 * and give them an opportunity to reject the message.
919 if (sSMTP->is_unfiltered) {
923 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
926 if (scan_errors > 0) { /* We don't want this message! */
928 if (CM_IsEmpty(msg, eErrorMsg)) {
929 CM_SetField(msg, eErrorMsg, HKEY("Message rejected by filter"));
932 StrBufPrintf(sSMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
935 else { /* Ok, we'll accept this message. */
936 msgnum = CtdlSubmitMsg(msg, valid, "", 0);
938 StrBufPrintf(sSMTP->OneRcpt, "250 Message accepted.\r\n");
941 StrBufPrintf(sSMTP->OneRcpt, "550 Internal delivery error\r\n");
945 /* For SMTP and ESMTP, just print the result message. For LMTP, we
946 * have to print one result message for each recipient. Since there
947 * is nothing in Citadel which would cause different recipients to
948 * have different results, we can get away with just spitting out the
949 * same message once for each recipient.
951 if (sSMTP->is_lmtp) {
952 for (i=0; i<sSMTP->number_of_recipients; ++i) {
953 cputbuf(sSMTP->OneRcpt);
957 cputbuf(sSMTP->OneRcpt);
960 /* Write something to the syslog(which may or may not be where the
961 * rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
963 syslog((LOG_MAIL | LOG_INFO),
964 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
967 sSMTP->number_of_recipients,
970 ChrPtr(sSMTP->OneRcpt)
975 free_recipients(valid);
976 smtp_data_clear(0, 0); /* clear out the buffers now */
981 * implements the STARTTLS command
983 void smtp_starttls(long offset, long flags)
985 char ok_response[SIZ];
986 char nosup_response[SIZ];
987 char error_response[SIZ];
989 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
990 sprintf(nosup_response, "554 TLS not supported here\r\n");
991 sprintf(error_response, "554 Internal error\r\n");
992 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
998 * Main command loop for SMTP server sessions.
1000 void smtp_command_loop(void)
1002 struct CitContext *CCC = CC;
1003 citsmtp *sSMTP = SMTP;
1004 const char *pch, *pchs;
1006 char CMD[MaxSMTPCmdLen + 1];
1008 if (sSMTP == NULL) {
1009 syslog(LOG_EMERG, "Session SMTP data is null. WTF? We will crash now.\n");
1010 return cit_panic_backtrace (0);
1013 time(&CCC->lastcmd);
1014 if (CtdlClientGetLine(sSMTP->Cmd) < 1) {
1015 syslog(LOG_CRIT, "SMTP: client disconnected: ending session.\n");
1016 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1019 syslog(LOG_DEBUG, "SMTP server: %s\n", ChrPtr(sSMTP->Cmd));
1021 if (sSMTP->command_state == smtp_user) {
1026 else if (sSMTP->command_state == smtp_password) {
1027 smtp_get_pass(0, 0);
1031 else if (sSMTP->command_state == smtp_plain) {
1032 smtp_try_plain(0, 0);
1036 pchs = pch = ChrPtr(sSMTP->Cmd);
1038 while ((*pch != '\0') &&
1040 (pch - pchs <= MaxSMTPCmdLen))
1042 CMD[i] = toupper(*pch);
1048 if ((*pch == '\0') ||
1053 if (GetHash(SMTPCmds, CMD, i, &v) &&
1056 smtp_handler_hook *h = (smtp_handler_hook*) v;
1058 if (isblank(pchs[i]))
1066 cprintf("502 I'm afraid I can't do that.\r\n");
1069 void smtp_noop(long offest, long Flags)
1071 cprintf("250 NOOP\r\n");
1074 void smtp_quit(long offest, long Flags)
1076 cprintf("221 Goodbye...\r\n");
1077 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1080 /*****************************************************************************/
1081 /* MODULE INITIALIZATION STUFF */
1082 /*****************************************************************************/
1084 * This cleanup function blows away the temporary memory used by
1087 void smtp_cleanup_function(void)
1089 citsmtp *sSMTP = SMTP;
1091 /* Don't do this stuff if this is not an SMTP session! */
1092 if (CC->h_command_function != smtp_command_loop) return;
1094 syslog(LOG_DEBUG, "Performing SMTP cleanup hook\n");
1096 FreeStrBuf(&sSMTP->Cmd);
1097 FreeStrBuf(&sSMTP->helo_node);
1098 FreeStrBuf(&sSMTP->from);
1099 FreeStrBuf(&sSMTP->recipients);
1100 FreeStrBuf(&sSMTP->OneRcpt);
1101 FreeStrBuf(&sSMTP->preferred_sender_email);
1102 FreeStrBuf(&sSMTP->preferred_sender_name);
1107 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1108 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1109 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1110 const char *CitadelServiceSMTP_LMTP="LMTP";
1111 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1113 CTDL_MODULE_INIT(smtp)
1117 SMTPCmds = NewHash(1, NULL);
1119 RegisterSmtpCMD("AUTH", smtp_auth, 0);
1120 RegisterSmtpCMD("DATA", smtp_data, 0);
1121 RegisterSmtpCMD("HELO", smtp_hello, HELO);
1122 RegisterSmtpCMD("EHLO", smtp_hello, EHLO);
1123 RegisterSmtpCMD("LHLO", smtp_hello, LHLO);
1124 RegisterSmtpCMD("HELP", smtp_help, 0);
1125 RegisterSmtpCMD("MAIL", smtp_mail, 0);
1126 RegisterSmtpCMD("NOOP", smtp_noop, 0);
1127 RegisterSmtpCMD("QUIT", smtp_quit, 0);
1128 RegisterSmtpCMD("RCPT", smtp_rcpt, 0);
1129 RegisterSmtpCMD("RSET", smtp_rset, 1);
1131 RegisterSmtpCMD("STARTTLS", smtp_starttls, 0);
1135 CtdlRegisterServiceHook(config.c_smtp_port, /* SMTP MTA */
1140 CitadelServiceSMTP_MTA);
1143 CtdlRegisterServiceHook(config.c_smtps_port,
1148 CitadelServiceSMTPS_MTA);
1151 CtdlRegisterServiceHook(config.c_msa_port, /* SMTP MSA */
1156 CitadelServiceSMTP_MSA);
1158 CtdlRegisterServiceHook(0, /* local LMTP */
1163 CitadelServiceSMTP_LMTP);
1165 CtdlRegisterServiceHook(0, /* local LMTP */
1166 file_lmtp_unfiltered_socket,
1167 lmtp_unfiltered_greeting,
1170 CitadelServiceSMTP_LMTP_UNF);
1172 CtdlRegisterCleanupHook(smtp_cleanup);
1173 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1176 /* return our module name for the log */