1 // This module is an SMTP and ESMTP server for the Citadel system.
2 // It is compliant with all of the following:
4 // RFC 821 - Simple Mail Transfer Protocol
5 // RFC 876 - Survey of SMTP Implementations
6 // RFC 1047 - Duplicate messages and SMTP
7 // RFC 1652 - 8 bit MIME
8 // RFC 1869 - Extended Simple Mail Transfer Protocol
9 // RFC 1870 - SMTP Service Extension for Message Size Declaration
10 // RFC 2033 - Local Mail Transfer Protocol
11 // RFC 2197 - SMTP Service Extension for Command Pipelining
12 // RFC 2476 - Message Submission
13 // RFC 2487 - SMTP Service Extension for Secure SMTP over TLS
14 // RFC 2554 - SMTP Service Extension for Authentication
15 // RFC 2821 - Simple Mail Transfer Protocol
16 // RFC 2822 - Internet Message Format
17 // RFC 2920 - SMTP Service Extension for Command Pipelining
19 // The VRFY and EXPN commands have been removed from this implementation
20 // because nobody uses these commands anymore, except for spammers.
22 // Copyright (c) 1998-2023 by the citadel.org team
24 // This program is open source software; you can redistribute it and/or modify
25 // it under the terms of the GNU General Public License version 3.
27 // This program is distributed in the hope that it will be useful,
28 // but WITHOUT ANY WARRANTY; without even the implied warranty of
29 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 // GNU General Public License for more details.
32 #include "../../sysdep.h"
41 #include <sys/types.h>
48 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
52 #include <libcitadel.h>
53 #include "../../citadel_defs.h"
54 #include "../../server.h"
55 #include "../../citserver.h"
56 #include "../../support.h"
57 #include "../../config.h"
58 #include "../../control.h"
59 #include "../../user_ops.h"
60 #include "../../room_ops.h"
61 #include "../../database.h"
62 #include "../../msgbase.h"
63 #include "../../internet_addressing.h"
64 #include "../../genstamp.h"
65 #include "../../domain.h"
66 #include "../../clientsocket.h"
67 #include "../../locate_host.h"
68 #include "../../citadel_dirs.h"
69 #include "../../ctdl_module.h"
71 #include "smtp_util.h"
73 enum { // Command states for login authentication
87 // Here's where our SMTP session begins its happy day.
88 void smtp_greeting(int is_msa) {
89 char message_to_spammer[1024];
91 strcpy(CC->cs_clientname, "SMTP session");
93 CC->cs_flags |= CS_STEALTH;
94 CC->session_specific_data = malloc(sizeof(struct citsmtp));
95 memset(SMTP, 0, sizeof(struct citsmtp));
96 SMTP->is_msa = is_msa;
97 SMTP->Cmd = NewStrBufPlain(NULL, SIZ);
98 SMTP->helo_node = NewStrBuf();
99 SMTP->from = NewStrBufPlain(NULL, SIZ);
100 SMTP->recipients = NewStrBufPlain(NULL, SIZ);
101 SMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
102 SMTP->preferred_sender_email = NULL;
103 SMTP->preferred_sender_name = NULL;
105 // If this config option is set, reject connections from problem
106 // addresses immediately instead of after they execute a RCPT
107 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (SMTP->is_msa == 0) ) {
108 if (rbl_check(CC->cs_addr, message_to_spammer)) {
109 if (server_shutting_down)
110 cprintf("421 %s\r\n", message_to_spammer);
112 cprintf("550 %s\r\n", message_to_spammer);
113 CC->kill_me = KILLME_SPAMMER;
114 // no need to free_recipients(valid), it's not allocated yet
119 // Otherwise we're either clean or we check later.
121 if (CC->nologin==1) {
122 cprintf("451 Too many connections are already open; please try again later.\r\n");
123 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
124 // no need to free_recipients(valid), it's not allocated yet
128 // Note: the FQDN *must* appear as the first thing after the 220 code.
129 // Some clients (including citmail.c) depend on it being there.
130 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
134 // SMTPS is just like SMTP, except it goes crypto right away.
135 void smtps_greeting(void) {
136 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
138 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; // kill session if no crypto
144 // SMTP MSA port requires authentication.
145 void smtp_msa_greeting(void) {
150 // LMTP is like SMTP but with some extra bonus footage added.
151 void lmtp_greeting(void) {
158 // Generic SMTP MTA greeting
159 void smtp_mta_greeting(void) {
164 // We also have an unfiltered LMTP socket that bypasses spam filters.
165 void lmtp_unfiltered_greeting(void) {
168 SMTP->is_unfiltered = 1;
172 // Login greeting common to all auth methods
173 void smtp_auth_greeting(void) {
174 cprintf("235 Hello, %s\r\n", CC->user.fullname);
175 syslog(LOG_INFO, "serv_smtp: SMTP authenticated %s", CC->user.fullname);
176 CC->internal_pgm = 0;
177 CC->cs_flags &= ~CS_STEALTH;
181 // Implement HELO and EHLO commands.
182 // which_command: 0=HELO, 1=EHLO, 2=LHLO
183 void smtp_hello(int which_command) {
185 if (StrLength(SMTP->Cmd) >= 6) {
186 FlushStrBuf(SMTP->helo_node);
187 StrBufAppendBuf(SMTP->helo_node, SMTP->Cmd, 5);
190 if ( (which_command != LHLO) && (SMTP->is_lmtp) ) {
191 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
195 if ( (which_command == LHLO) && (SMTP->is_lmtp == 0) ) {
196 cprintf("500 LHLO is only allowed when running LMTP\r\n");
200 if (which_command == HELO) {
201 cprintf("250 Hello %s (%s [%s])\r\n",
202 ChrPtr(SMTP->helo_node),
208 if (which_command == EHLO) {
209 cprintf("250-Hello %s (%s [%s])\r\n", ChrPtr(SMTP->helo_node), CC->cs_host, CC->cs_addr);
212 cprintf("250-Greetings and joyous salutations.\r\n");
214 cprintf("250-HELP\r\n");
215 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
218 // Offer the STARTTLS option...
219 if ( (!CC->redirect_ssl) // not if we're already TLS
220 && ( (SMTP->is_msa) // Always on port 587
221 || (CtdlGetConfigInt("smtp_advertise_starttls") != 0) // On port 25 only if enabled
224 cprintf("250-STARTTLS\r\n");
228 cprintf("250-AUTH LOGIN PLAIN\r\n"
229 "250-AUTH=LOGIN PLAIN\r\n"
236 // Backend function for smtp_webcit_preferences_hack().
237 // Look at a message and determine if it's the preferences file.
238 void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
239 struct CtdlMessage *msg;
240 char **webcit_conf = (char **) userdata;
243 return; // already got it
246 msg = CtdlFetchMessage(msgnum, 1);
251 if ( !CM_IsEmpty(msg, eMsgSubject) && (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __"))) {
252 // This is it! Change ownership of the message text so it doesn't get freed.
253 *webcit_conf = (char *)msg->cm_fields[eMessageText];
254 msg->cm_fields[eMessageText] = NULL;
260 // The configuration item for the user's preferred display name for outgoing email is, unfortunately,
261 // stored in the account's WebCit configuration. We have to fetch it now.
262 void smtp_webcit_preferences_hack(void) {
263 char config_roomname[ROOMNAMELEN];
264 char *webcit_conf = NULL;
266 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CC->user.usernum, USERCONFIGROOM);
267 if (CtdlGetRoom(&CC->room, config_roomname) != 0) {
271 // Find the WebCit configuration message
272 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
278 // Parse the webcit configuration and attempt to do something useful with it
279 char *str = webcit_conf;
281 char *this_line = NULL;
282 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
284 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
285 SMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
287 if (!strncasecmp(this_line, "defaultname|", 12)) {
288 SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
290 if ((!strncasecmp(this_line, "defaultname|", 12)) && (SMTP->preferred_sender_name == NULL)) {
291 SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
299 // Implement HELP command.
300 void smtp_help(void) {
301 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
305 void smtp_get_user(int offset) {
308 StrBuf *UserName = NewStrBufDup(SMTP->Cmd);
309 StrBufCutLeft(UserName, offset);
310 StrBufDecodeBase64(UserName);
312 if (CtdlLoginExistingUser(ChrPtr(UserName)) == login_ok) {
313 size_t len = CtdlEncodeBase64(buf, "Password:", 9, BASE64_NO_LINEBREAKS);
315 if (buf[len - 1] == '\n') {
318 cprintf("334 %s\r\n", buf);
319 SMTP->command_state = smtp_password;
322 cprintf("500 No such user.\r\n");
323 SMTP->command_state = smtp_command;
325 FreeStrBuf(&UserName);
329 void smtp_get_pass(void) {
332 memset(password, 0, sizeof(password));
333 StrBufDecodeBase64(SMTP->Cmd);
334 syslog(LOG_DEBUG, "serv_smtp: trying <%s>", password);
335 if (CtdlTryPassword(SKEY(SMTP->Cmd)) == pass_ok) {
336 smtp_auth_greeting();
339 cprintf("535 Authentication failed.\r\n");
341 SMTP->command_state = smtp_command;
345 // Back end for PLAIN auth method (either inline or multistate)
346 void smtp_try_plain(void) {
347 const char*decoded_authstring;
348 char ident[256] = "";
357 memset(pass, 0, sizeof(pass));
358 decoded_len = StrBufDecodeBase64(SMTP->Cmd);
360 if (decoded_len > 0) {
361 decoded_authstring = ChrPtr(SMTP->Cmd);
363 len = safestrncpy(ident, decoded_authstring, sizeof ident);
365 decoded_len -= len - 1;
366 decoded_authstring += len + 1;
368 if (decoded_len > 0) {
369 len = safestrncpy(user, decoded_authstring, sizeof user);
371 decoded_authstring += len + 1;
372 decoded_len -= len - 1;
375 if (decoded_len > 0) {
376 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
379 plen = sizeof(pass) - 1;
383 SMTP->command_state = smtp_command;
385 if (!IsEmptyStr(ident)) {
386 result = CtdlLoginExistingUser(ident);
389 result = CtdlLoginExistingUser(user);
392 if (result == login_ok) {
393 if (CtdlTryPassword(pass, plen) == pass_ok) {
394 smtp_webcit_preferences_hack();
395 smtp_auth_greeting();
399 cprintf("504 Authentication failed.\r\n");
403 // Attempt to perform authenticated SMTP
404 void smtp_auth(void) {
405 char username_prompt[64];
407 char encoded_authstring[1024];
410 cprintf("504 Already logged in.\r\n");
414 if (StrLength(SMTP->Cmd) < 6) {
415 cprintf("501 Syntax error\r\n");
419 extract_token(method, ChrPtr(SMTP->Cmd) + 5, 0, ' ', sizeof method);
421 if (!strncasecmp(method, "login", 5) ) {
422 if (StrLength(SMTP->Cmd) >= 12) {
423 syslog(LOG_DEBUG, "serv_smtp: username <%s> supplied inline", ChrPtr(SMTP->Cmd)+11);
427 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, BASE64_NO_LINEBREAKS);
428 if (username_prompt[len - 1] == '\n') {
429 username_prompt[len - 1] = '\0';
431 cprintf("334 %s\r\n", username_prompt);
432 SMTP->command_state = smtp_user;
437 if (!strncasecmp(method, "plain", 5) ) {
439 if (num_tokens(ChrPtr(SMTP->Cmd) + 5, ' ') < 2) {
441 SMTP->command_state = smtp_plain;
445 len = extract_token(encoded_authstring, ChrPtr(SMTP->Cmd) + 5, 1, ' ', sizeof encoded_authstring);
446 StrBufPlain(SMTP->Cmd, encoded_authstring, len);
451 cprintf("504 Unknown authentication method.\r\n");
456 // Implements the RSET (reset state) command.
457 // Currently this just zeroes out the state buffer. If pointers to data
458 // allocated with malloc() are ever placed in the state buffer, we have to
459 // be sure to free() them first!
461 // Set do_response to nonzero to output the SMTP RSET response code.
462 void smtp_rset(int do_response) {
463 FlushStrBuf(SMTP->Cmd);
464 FlushStrBuf(SMTP->helo_node);
465 FlushStrBuf(SMTP->from);
466 FlushStrBuf(SMTP->recipients);
467 FlushStrBuf(SMTP->OneRcpt);
469 SMTP->command_state = 0;
470 SMTP->number_of_recipients = 0;
471 SMTP->delivery_mode = 0;
472 SMTP->message_originated_locally = 0;
474 // is_lmtp and is_unfiltered should not be cleared.
477 cprintf("250 Zap!\r\n");
482 // Clear out the portions of the state buffer that need to be cleared out
483 // after the DATA command finishes.
484 void smtp_data_clear(void) {
485 FlushStrBuf(SMTP->from);
486 FlushStrBuf(SMTP->recipients);
487 FlushStrBuf(SMTP->OneRcpt);
488 SMTP->number_of_recipients = 0;
489 SMTP->delivery_mode = 0;
490 SMTP->message_originated_locally = 0;
494 // Implements the "MAIL FROM:" command
495 void smtp_mail(void) {
500 if (StrLength(SMTP->from) > 0) {
501 cprintf("503 Only one sender permitted\r\n");
505 if (StrLength(SMTP->Cmd) < 6) {
506 cprintf("501 Syntax error\r\n");
510 if (strncasecmp(ChrPtr(SMTP->Cmd) + 5, "From:", 5)) {
511 cprintf("501 Syntax error\r\n");
515 StrBufAppendBuf(SMTP->from, SMTP->Cmd, 5);
516 StrBufTrim(SMTP->from);
517 if (strchr(ChrPtr(SMTP->from), '<') != NULL) {
518 StrBufStripAllBut(SMTP->from, '<', '>');
521 // We used to reject empty sender names, until it was brought to our
522 // attention that RFC1123 5.2.9 requires that this be allowed. So now
523 // we allow it, but replace the empty string with a fake
524 // address so we don't have to contend with the empty string causing
525 // other code to fail when it's expecting something there.
526 if (StrLength(SMTP->from) == 0) {
527 StrBufPlain(SMTP->from, HKEY("someone@example.com"));
530 // If this SMTP connection is from a logged-in user, force the 'from'
531 // to be the user's Internet e-mail address as Citadel knows it.
533 StrBufPlain(SMTP->from, CC->cs_inet_email, -1);
534 cprintf("250 Sender ok <%s>\r\n", ChrPtr(SMTP->from));
535 SMTP->message_originated_locally = 1;
539 else if (SMTP->is_lmtp) {
540 // Bypass forgery checking for LMTP
543 // Otherwise, make sure outsiders aren't trying to forge mail from
544 // this system (unless, of course, c_allow_spoofing is enabled)
545 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
546 process_rfc822_addr(ChrPtr(SMTP->from), user, node, name);
547 syslog(LOG_DEBUG, "serv_smtp: claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
548 ChrPtr(SMTP->from), user, node, name
550 if (CtdlHostAlias(node) != hostalias_nomatch) {
551 cprintf("550 You must log in to send mail from %s\r\n", node);
552 FlushStrBuf(SMTP->from);
553 syslog(LOG_DEBUG, "serv_smtp: rejecting unauthenticated mail from %s", node);
558 cprintf("250 Sender ok\r\n");
562 // Implements the "RCPT To:" command
563 void smtp_rcpt(void) {
564 char message_to_spammer[SIZ];
565 struct recptypes *valid = NULL;
567 if (StrLength(SMTP->from) == 0) {
568 cprintf("503 Need MAIL before RCPT\r\n");
572 if (StrLength(SMTP->Cmd) < 6) {
573 cprintf("501 Syntax error\r\n");
577 if (strncasecmp(ChrPtr(SMTP->Cmd) + 5, "To:", 3)) {
578 cprintf("501 Syntax error\r\n");
582 if ( (SMTP->is_msa) && (!CC->logged_in) ) {
583 cprintf("550 You must log in to send mail on this port.\r\n");
584 FlushStrBuf(SMTP->from);
588 FlushStrBuf(SMTP->OneRcpt);
589 StrBufAppendBuf(SMTP->OneRcpt, SMTP->Cmd, 8);
590 StrBufTrim(SMTP->OneRcpt);
591 StrBufStripAllBut(SMTP->OneRcpt, '<', '>');
593 if ( (StrLength(SMTP->OneRcpt) + StrLength(SMTP->recipients)) >= SIZ) {
594 cprintf("452 Too many recipients\r\n");
600 (!CC->logged_in) // Don't RBL authenticated users
601 && (!SMTP->is_lmtp) // Don't RBL LMTP clients
602 && (CtdlGetConfigInt("c_rbl_at_greeting") == 0) // Don't RBL if we did it at connection time
603 && (rbl_check(CC->cs_addr, message_to_spammer))
605 cprintf("550 %s\r\n", message_to_spammer);
606 return; // no need to free_recipients(valid)
607 } // because it hasn't been allocated yet
609 // This is a *preliminary* call to validate_recipients() to evaluate one recipient.
610 valid = validate_recipients(
611 (char *)ChrPtr(SMTP->OneRcpt),
612 smtp_get_Recipients(),
613 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
616 // Any type of error thrown by validate_recipients() will make the SMTP transaction fail at this point.
617 if (valid->num_error != 0) {
618 cprintf("550 %s\r\n", valid->errormsg);
619 free_recipients(valid);
624 (valid->num_internet > 0) // If it's outbound Internet mail...
625 && (CC->logged_in) // ...and we're a logged-in user...
626 && (CtdlCheckInternetMailPermission(&CC->user)==0) // ...who does not have Internet mail rights...
628 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n", ChrPtr(SMTP->OneRcpt));
629 free_recipients(valid);
634 (valid->num_internet > 0) // If it's outbound Internet mail...
635 && (SMTP->message_originated_locally == 0) // ...and also inbound Internet mail...
636 && (SMTP->is_lmtp == 0) /// ...and didn't arrive via LMTP...
638 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(SMTP->OneRcpt));
639 free_recipients(valid);
644 (valid->num_room > 0) // If it's mail to a room (mailing list)...
645 && (SMTP->message_originated_locally == 0) // ...and also inbound Internet mail...
646 && (is_email_subscribed_to_list((char *)ChrPtr(SMTP->from), valid->recp_room) == 0) // ...and not a subscriber
648 cprintf("551 <%s> - The message is not from a list member\r\n", ChrPtr(SMTP->OneRcpt));
649 free_recipients(valid);
653 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(SMTP->OneRcpt));
654 if (StrLength(SMTP->recipients) > 0) {
655 StrBufAppendBufPlain(SMTP->recipients, HKEY(","), 0);
657 StrBufAppendBuf(SMTP->recipients, SMTP->OneRcpt, 0);
658 SMTP->number_of_recipients ++;
660 free_recipients(valid);
665 // Implements the DATA command
666 void smtp_data(void) {
669 struct CtdlMessage *msg = NULL;
672 struct recptypes *valid;
676 if (StrLength(SMTP->from) == 0) {
677 cprintf("503 Need MAIL command first.\r\n");
681 if (SMTP->number_of_recipients < 1) {
682 cprintf("503 Need RCPT command first.\r\n");
686 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
688 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
689 defbody = NewStrBufPlain(NULL, SIZ);
691 if (defbody != NULL) {
692 if (SMTP->is_lmtp && (CC->cs_UDSclientUID != -1)) {
695 "Received: from %s (Citadel from userid %ld)\n"
697 ChrPtr(SMTP->helo_node),
698 (long int) CC->cs_UDSclientUID,
699 CtdlGetConfigStr("c_fqdn"),
705 "Received: from %s (%s [%s])\n"
707 ChrPtr(SMTP->helo_node),
710 CtdlGetConfigStr("c_fqdn"),
714 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1);
715 FreeStrBuf(&defbody);
717 cprintf("550 Unable to save message: internal error.\r\n");
721 syslog(LOG_DEBUG, "serv_smtp: converting message...");
722 msg = convert_internet_message_buf(&body);
724 // If the user is locally authenticated, FORCE the From: header to
725 // show up as the real sender. Yes, this violates the RFC standard,
726 // but IT MAKES SENSE. If you prefer strict RFC adherence over
727 // common sense, you can disable this in the configuration.
729 // We also set the "message room name" ('O' field) to MAILROOM
730 // (which is Mail> on most systems) to prevent it from getting set
731 // to something ugly like "0000058008.Sent Items>" when the message
732 // is read with a Citadel client.
734 if ( (CC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
737 if (!CM_IsEmpty(msg, erFc822Addr) &&
738 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
739 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
741 if (!IsEmptyStr(CC->cs_inet_email)) {
742 validemail = strcmp(CC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
744 if ((!validemail) && (!IsEmptyStr(CC->cs_inet_other_emails))) {
745 int num_secondary_emails = 0;
747 num_secondary_emails = num_tokens(CC->cs_inet_other_emails, '|');
748 for (i=0; i < num_secondary_emails && !validemail; ++i) {
750 extract_token(buf, CC->cs_inet_other_emails,i,'|',sizeof CC->cs_inet_other_emails);
751 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
756 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
757 syslog(LOG_ERR, "serv_smtp: invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
758 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
762 CM_SetField(msg, eOriginalRoom, MAILROOM);
763 if (SMTP->preferred_sender_name != NULL)
764 CM_SetField(msg, eAuthor, ChrPtr(SMTP->preferred_sender_name));
766 CM_SetField(msg, eAuthor, CC->user.fullname);
769 if (SMTP->preferred_sender_email != NULL) {
770 CM_SetField(msg, erFc822Addr, ChrPtr(SMTP->preferred_sender_email));
773 CM_SetField(msg, erFc822Addr, CC->cs_inet_email);
778 // Set the "envelope from" address
779 CM_SetField(msg, eMessagePath, ChrPtr(SMTP->from));
781 // Set the "envelope to" address
782 CM_SetField(msg, eenVelopeTo, ChrPtr(SMTP->recipients));
784 // Submit the message into the Citadel system.
785 valid = validate_recipients(
786 (char *)ChrPtr(SMTP->recipients),
787 smtp_get_Recipients(),
788 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
791 // If there are modules that want to scan this message before final
792 // submission (such as virus checkers or spam filters), call them now
793 // and give them an opportunity to reject the message.
794 if (SMTP->is_unfiltered) {
798 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
801 if (scan_errors > 0) { // We don't want this message!
803 if (CM_IsEmpty(msg, eErrorMsg)) {
804 CM_SetField(msg, eErrorMsg, "Message rejected by filter");
807 StrBufPrintf(SMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
810 else { // Ok, we'll accept this message.
811 msgnum = CtdlSubmitMsg(msg, valid, "");
813 StrBufPrintf(SMTP->OneRcpt, "250 Message accepted.\r\n");
816 StrBufPrintf(SMTP->OneRcpt, "550 Internal delivery error\r\n");
820 // For SMTP and ESMTP, just print the result message. For LMTP, we
821 // have to print one result message for each recipient. Since there
822 // is nothing in Citadel which would cause different recipients to
823 // have different results, we can get away with just spitting out the
824 // same message once for each recipient.
826 for (i=0; i<SMTP->number_of_recipients; ++i) {
827 cputbuf(SMTP->OneRcpt);
831 cputbuf(SMTP->OneRcpt);
834 // Write something to the syslog(which may or may not be where the
835 // rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
836 syslog((LOG_MAIL | LOG_INFO),
837 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
840 SMTP->number_of_recipients,
843 ChrPtr(SMTP->OneRcpt)
848 free_recipients(valid);
849 smtp_data_clear(); // clear out the buffers now
853 // Implements the STARTTLS command
854 void smtp_starttls(void) {
855 char ok_response[SIZ];
856 char nosup_response[SIZ];
857 char error_response[SIZ];
859 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
860 sprintf(nosup_response, "554 TLS not supported here\r\n");
861 sprintf(error_response, "554 Internal error\r\n");
862 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
867 // Implements the NOOP (NO OPeration) command
868 void smtp_noop(void) {
869 cprintf("250 NOOP\r\n");
873 // Implements the QUIT command
874 void smtp_quit(void) {
875 cprintf("221 Goodbye...\r\n");
876 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
880 // Main command loop for SMTP server sessions.
881 void smtp_command_loop(void) {
882 static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
884 assert(SMTP != NULL);
887 if (CtdlClientGetLine(SMTP->Cmd) < 1) {
888 syslog(LOG_INFO, "SMTP: client disconnected: ending session.");
889 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
893 if (SMTP->command_state == smtp_user) {
894 if (!strncmp(ChrPtr(SMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len)) {
903 else if (SMTP->command_state == smtp_password) {
908 else if (SMTP->command_state == smtp_plain) {
913 syslog(LOG_DEBUG, "serv_smtp: client sent command <%s>", ChrPtr(SMTP->Cmd));
915 if (!strncasecmp(ChrPtr(SMTP->Cmd), "NOOP", 4)) {
920 if (!strncasecmp(ChrPtr(SMTP->Cmd), "QUIT", 4)) {
925 if (!strncasecmp(ChrPtr(SMTP->Cmd), "HELO", 4)) {
930 if (!strncasecmp(ChrPtr(SMTP->Cmd), "EHLO", 4)) {
935 if (!strncasecmp(ChrPtr(SMTP->Cmd), "LHLO", 4)) {
940 if (!strncasecmp(ChrPtr(SMTP->Cmd), "RSET", 4)) {
945 if (!strncasecmp(ChrPtr(SMTP->Cmd), "AUTH", 4)) {
950 if (!strncasecmp(ChrPtr(SMTP->Cmd), "DATA", 4)) {
955 if (!strncasecmp(ChrPtr(SMTP->Cmd), "HELP", 4)) {
960 if (!strncasecmp(ChrPtr(SMTP->Cmd), "MAIL", 4)) {
965 if (!strncasecmp(ChrPtr(SMTP->Cmd), "RCPT", 4)) {
970 if (!strncasecmp(ChrPtr(SMTP->Cmd), "STARTTLS", 8)) {
976 cprintf("502 I'm afraid I can't do that.\r\n");
980 // *****************************************************************************
981 // * MODULE INITIALIZATION STUFF *
982 // *****************************************************************************
984 // This cleanup function blows away the temporary memory used by
986 void smtp_cleanup_function(void) {
987 // Don't do this stuff if this is not an SMTP session!
988 if (CC->h_command_function != smtp_command_loop) return;
990 syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
992 FreeStrBuf(&SMTP->Cmd);
993 FreeStrBuf(&SMTP->helo_node);
994 FreeStrBuf(&SMTP->from);
995 FreeStrBuf(&SMTP->recipients);
996 FreeStrBuf(&SMTP->OneRcpt);
997 FreeStrBuf(&SMTP->preferred_sender_email);
998 FreeStrBuf(&SMTP->preferred_sender_name);
1003 const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1004 const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1005 const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1006 const char *CitadelServiceSMTP_LMTP="LMTP";
1007 const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1010 // Initialization function, called from modules_init.c
1011 char *ctdl_module_init_smtp(void) {
1013 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"), // SMTP MTA
1018 CitadelServiceSMTP_MTA);
1021 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"), // SMTPS MTA
1026 CitadelServiceSMTPS_MTA);
1029 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"), // SMTP MSA
1034 CitadelServiceSMTP_MSA);
1036 CtdlRegisterServiceHook(0, // local LMTP
1041 CitadelServiceSMTP_LMTP);
1043 CtdlRegisterServiceHook(0, // local LMTP
1044 file_lmtp_unfiltered_socket,
1045 lmtp_unfiltered_greeting,
1048 CitadelServiceSMTP_LMTP_UNF);
1050 CtdlRegisterSessionHook(smtp_cleanup_function, EVT_STOP, PRIO_STOP + 250);
1053 // return our module name for the log