citadel
About: Citadel is an advanced messaging and collaboration system for groupware and BBS applications (preferred OS: Linux).
  Fossies Dox: citadel.tar.gz  ("unofficial" and yet experimental doxygen-generated source code documentation)  

serv_smtp.c
Go to the documentation of this file.
1// This module is an SMTP and ESMTP server for the Citadel system.
2// It is compliant with all of the following:
3//
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
18//
19// The VRFY and EXPN commands have been removed from this implementation
20// because nobody uses these commands anymore, except for spammers.
21//
22// Copyright (c) 1998-2021 by the citadel.org team
23//
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.
26//
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.
31
32#include "sysdep.h"
33#include <stdlib.h>
34#include <unistd.h>
35#include <stdio.h>
36#include <termios.h>
37#include <fcntl.h>
38#include <signal.h>
39#include <pwd.h>
40#include <errno.h>
41#include <sys/types.h>
42#include <syslog.h>
43#include <time.h>
44#include <sys/wait.h>
45#include <ctype.h>
46#include <string.h>
47#include <limits.h>
48#include <sys/socket.h>
49#include <netinet/in.h>
50#include <arpa/inet.h>
51#include <libcitadel.h>
52#include "citadel.h"
53#include "server.h"
54#include "citserver.h"
55#include "support.h"
56#include "config.h"
57#include "control.h"
58#include "user_ops.h"
59#include "room_ops.h"
60#include "database.h"
61#include "msgbase.h"
62#include "internet_addressing.h"
63#include "genstamp.h"
64#include "domain.h"
65#include "clientsocket.h"
66#include "locate_host.h"
67#include "citadel_dirs.h"
68#include "ctdl_module.h"
69
70#include "smtp_util.h"
71
72enum { /* Command states for login authentication */
77};
78
82 LHLO
83};
84
85
86/*
87 * Here's where our SMTP session begins its happy day.
88 */
89void smtp_greeting(int is_msa) {
90 char message_to_spammer[1024];
91
92 strcpy(CC->cs_clientname, "SMTP session");
93 CC->internal_pgm = 1;
94 CC->cs_flags |= CS_STEALTH;
95 CC->session_specific_data = malloc(sizeof(struct citsmtp));
96 memset(SMTP, 0, sizeof(struct citsmtp));
97 SMTP->is_msa = is_msa;
98 SMTP->Cmd = NewStrBufPlain(NULL, SIZ);
99 SMTP->helo_node = NewStrBuf();
100 SMTP->from = NewStrBufPlain(NULL, SIZ);
101 SMTP->recipients = NewStrBufPlain(NULL, SIZ);
102 SMTP->OneRcpt = NewStrBufPlain(NULL, SIZ);
103 SMTP->preferred_sender_email = NULL;
104 SMTP->preferred_sender_name = NULL;
105
106 /* If this config option is set, reject connections from problem
107 * addresses immediately instead of after they execute a RCPT
108 */
109 if ( (CtdlGetConfigInt("c_rbl_at_greeting")) && (SMTP->is_msa == 0) ) {
110 if (rbl_check(CC->cs_addr, message_to_spammer)) {
112 cprintf("421 %s\r\n", message_to_spammer);
113 else
114 cprintf("550 %s\r\n", message_to_spammer);
115 CC->kill_me = KILLME_SPAMMER;
116 /* no need to free_recipients(valid), it's not allocated yet */
117 return;
118 }
119 }
120
121 /* Otherwise we're either clean or we check later. */
122
123 if (CC->nologin==1) {
124 cprintf("451 Too many connections are already open; please try again later.\r\n");
126 /* no need to free_recipients(valid), it's not allocated yet */
127 return;
128 }
129
130 /* Note: the FQDN *must* appear as the first thing after the 220 code.
131 * Some clients (including citmail.c) depend on it being there.
132 */
133 cprintf("220 %s ESMTP Citadel server ready.\r\n", CtdlGetConfigStr("c_fqdn"));
134}
135
136
137/*
138 * SMTPS is just like SMTP, except it goes crypto right away.
139 */
140void smtps_greeting(void) {
141 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
142#ifdef HAVE_OPENSSL
143 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
144#endif
145 smtp_greeting(0);
146}
147
148
149/*
150 * SMTP MSA port requires authentication.
151 */
153 smtp_greeting(1);
154}
155
156
157/*
158 * LMTP is like SMTP but with some extra bonus footage added.
159 */
160void lmtp_greeting(void) {
161
162 smtp_greeting(0);
163 SMTP->is_lmtp = 1;
164}
165
166
167/*
168 * Generic SMTP MTA greeting
169 */
171 smtp_greeting(0);
172}
173
174
175/*
176 * We also have an unfiltered LMTP socket that bypasses spam filters.
177 */
179 smtp_greeting(0);
180 SMTP->is_lmtp = 1;
181 SMTP->is_unfiltered = 1;
182}
183
184
185/*
186 * Login greeting common to all auth methods
187 */
189 cprintf("235 Hello, %s\r\n", CC->user.fullname);
190 syslog(LOG_INFO, "serv_smtp: SMTP authenticated %s", CC->user.fullname);
191 CC->internal_pgm = 0;
192 CC->cs_flags &= ~CS_STEALTH;
193}
194
195
196/*
197 * Implement HELO and EHLO commands.
198 *
199 * which_command: 0=HELO, 1=EHLO, 2=LHLO
200 */
201void smtp_hello(int which_command) {
202
203 if (StrLength(SMTP->Cmd) >= 6) {
204 StrBufAppendBuf(SMTP->helo_node, SMTP->Cmd, 5);
205 }
206
207 if ( (which_command != LHLO) && (SMTP->is_lmtp) ) {
208 cprintf("500 Only LHLO is allowed when running LMTP\r\n");
209 return;
210 }
211
212 if ( (which_command == LHLO) && (SMTP->is_lmtp == 0) ) {
213 cprintf("500 LHLO is only allowed when running LMTP\r\n");
214 return;
215 }
216
217 if (which_command == HELO) {
218 cprintf("250 Hello %s (%s [%s])\r\n",
219 ChrPtr(SMTP->helo_node),
220 CC->cs_host,
221 CC->cs_addr
222 );
223 }
224 else {
225 if (which_command == EHLO) {
226 cprintf("250-Hello %s (%s [%s])\r\n",
227 ChrPtr(SMTP->helo_node),
228 CC->cs_host,
229 CC->cs_addr
230 );
231 }
232 else {
233 cprintf("250-Greetings and joyous salutations.\r\n");
234 }
235 cprintf("250-HELP\r\n");
236 cprintf("250-SIZE %ld\r\n", CtdlGetConfigLong("c_maxmsglen"));
237
238#ifdef HAVE_OPENSSL
239 /*
240 * Offer TLS, but only if TLS is not already active.
241 * Furthermore, only offer TLS when running on
242 * the SMTP-MSA port, not on the SMTP-MTA port, due to
243 * questionable reliability of TLS in certain sending MTA's.
244 */
245 if ( (!CC->redirect_ssl) && (SMTP->is_msa) ) {
246 cprintf("250-STARTTLS\r\n");
247 }
248#endif /* HAVE_OPENSSL */
249
250 cprintf("250-AUTH LOGIN PLAIN\r\n"
251 "250-AUTH=LOGIN PLAIN\r\n"
252 "250 8BITMIME\r\n"
253 );
254 }
255}
256
257
258/*
259 * Backend function for smtp_webcit_preferences_hack().
260 * Look at a message and determine if it's the preferences file.
261 */
262void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata) {
263 struct CtdlMessage *msg;
264 char **webcit_conf = (char **) userdata;
265
266 if (*webcit_conf) {
267 return; // already got it
268 }
269
270 msg = CtdlFetchMessage(msgnum, 1);
271 if (msg == NULL) {
272 return;
273 }
274
275 if ( !CM_IsEmpty(msg, eMsgSubject) && (!strcasecmp(msg->cm_fields[eMsgSubject], "__ WebCit Preferences __"))) {
276 /* This is it! Change ownership of the message text so it doesn't get freed. */
277 *webcit_conf = (char *)msg->cm_fields[eMesageText];
278 msg->cm_fields[eMesageText] = NULL;
279 }
280 CM_Free(msg);
281}
282
283
284/*
285 * The configuration item for the user's preferred display name for outgoing email is, unfortunately,
286 * stored in the account's WebCit configuration. We have to fetch it now.
287 */
289 char config_roomname[ROOMNAMELEN];
290 char *webcit_conf = NULL;
291
292 snprintf(config_roomname, sizeof config_roomname, "%010ld.%s", CC->user.usernum, USERCONFIGROOM);
293 if (CtdlGetRoom(&CC->room, config_roomname) != 0) {
294 return;
295 }
296
297 /*
298 * Find the WebCit configuration message
299 */
300
301 CtdlForEachMessage(MSGS_ALL, 1, NULL, NULL, NULL, smtp_webcit_preferences_hack_backend, (void *)&webcit_conf);
302
303 if (!webcit_conf) {
304 return;
305 }
306
307 /* Parse the webcit configuration and attempt to do something useful with it */
308 char *str = webcit_conf;
309 char *saveptr = str;
310 char *this_line = NULL;
311 while (this_line = strtok_r(str, "\n", &saveptr), this_line != NULL) {
312 str = NULL;
313 if (!strncasecmp(this_line, "defaultfrom|", 12)) {
314 SMTP->preferred_sender_email = NewStrBufPlain(&this_line[12], -1);
315 }
316 if (!strncasecmp(this_line, "defaultname|", 12)) {
317 SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
318 }
319 if ((!strncasecmp(this_line, "defaultname|", 12)) && (SMTP->preferred_sender_name == NULL)) {
320 SMTP->preferred_sender_name = NewStrBufPlain(&this_line[12], -1);
321 }
322
323 }
324 free(webcit_conf);
325}
326
327
328/*
329 * Implement HELP command.
330 */
331void smtp_help(void) {
332 cprintf("214 RTFM http://www.ietf.org/rfc/rfc2821.txt\r\n");
333}
334
335
336/*
337 *
338 */
339void smtp_get_user(int offset) {
340 char buf[SIZ];
341
342 StrBuf *UserName = NewStrBufDup(SMTP->Cmd);
343 StrBufCutLeft(UserName, offset);
344 StrBufDecodeBase64(UserName);
345
346 if (CtdlLoginExistingUser(ChrPtr(UserName)) == login_ok) {
347 size_t len = CtdlEncodeBase64(buf, "Password:", 9, 0);
348
349 if (buf[len - 1] == '\n') {
350 buf[len - 1] = '\0';
351 }
352 cprintf("334 %s\r\n", buf);
353 SMTP->command_state = smtp_password;
354 }
355 else {
356 cprintf("500 No such user.\r\n");
357 SMTP->command_state = smtp_command;
358 }
359 FreeStrBuf(&UserName);
360}
361
362
363/*
364 *
365 */
367{
368 char password[SIZ];
369
370 memset(password, 0, sizeof(password));
371 StrBufDecodeBase64(SMTP->Cmd);
372 syslog(LOG_DEBUG, "serv_smtp: trying <%s>", password);
373 if (CtdlTryPassword(SKEY(SMTP->Cmd)) == pass_ok) {
375 }
376 else {
377 cprintf("535 Authentication failed.\r\n");
378 }
379 SMTP->command_state = smtp_command;
380}
381
382
383/*
384 * Back end for PLAIN auth method (either inline or multistate)
385 */
386void smtp_try_plain(void) {
387 const char*decoded_authstring;
388 char ident[256] = "";
389 char user[256] = "";
390 char pass[256] = "";
391 int result;
392
393 long decoded_len;
394 long len = 0;
395 long plen = 0;
396
397 memset(pass, 0, sizeof(pass));
398 decoded_len = StrBufDecodeBase64(SMTP->Cmd);
399
400 if (decoded_len > 0) {
401 decoded_authstring = ChrPtr(SMTP->Cmd);
402
403 len = safestrncpy(ident, decoded_authstring, sizeof ident);
404
405 decoded_len -= len - 1;
406 decoded_authstring += len + 1;
407
408 if (decoded_len > 0) {
409 len = safestrncpy(user, decoded_authstring, sizeof user);
410
411 decoded_authstring += len + 1;
412 decoded_len -= len - 1;
413 }
414
415 if (decoded_len > 0) {
416 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
417
418 if (plen < 0)
419 plen = sizeof(pass) - 1;
420 }
421 }
422
423 SMTP->command_state = smtp_command;
424
425 if (!IsEmptyStr(ident)) {
426 result = CtdlLoginExistingUser(ident);
427 }
428 else {
429 result = CtdlLoginExistingUser(user);
430 }
431
432 if (result == login_ok) {
433 if (CtdlTryPassword(pass, plen) == pass_ok) {
436 return;
437 }
438 }
439 cprintf("504 Authentication failed.\r\n");
440}
441
442
443/*
444 * Attempt to perform authenticated SMTP
445 */
446void smtp_auth(void) {
447 char username_prompt[64];
448 char method[64];
449 char encoded_authstring[1024];
450
451 if (CC->logged_in) {
452 cprintf("504 Already logged in.\r\n");
453 return;
454 }
455
456 if (StrLength(SMTP->Cmd) < 6) {
457 cprintf("501 Syntax error\r\n");
458 return;
459 }
460
461 extract_token(method, ChrPtr(SMTP->Cmd) + 5, 0, ' ', sizeof method);
462
463 if (!strncasecmp(method, "login", 5) ) {
464 if (StrLength(SMTP->Cmd) >= 12) {
465 syslog(LOG_DEBUG, "serv_smtp: username <%s> supplied inline", ChrPtr(SMTP->Cmd)+11);
466 smtp_get_user(11);
467 }
468 else {
469 size_t len = CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
470 if (username_prompt[len - 1] == '\n') {
471 username_prompt[len - 1] = '\0';
472 }
473 cprintf("334 %s\r\n", username_prompt);
474 SMTP->command_state = smtp_user;
475 }
476 return;
477 }
478
479 if (!strncasecmp(method, "plain", 5) ) {
480 long len;
481 if (num_tokens(ChrPtr(SMTP->Cmd) + 5, ' ') < 2) {
482 cprintf("334 \r\n");
483 SMTP->command_state = smtp_plain;
484 return;
485 }
486
487 len = extract_token(encoded_authstring,
488 ChrPtr(SMTP->Cmd) + 5,
489 1, ' ',
490 sizeof encoded_authstring);
491 StrBufPlain(SMTP->Cmd, encoded_authstring, len);
493 return;
494 }
495
496 cprintf("504 Unknown authentication method.\r\n");
497 return;
498}
499
500
501/*
502 * Implements the RSET (reset state) command.
503 * Currently this just zeroes out the state buffer. If pointers to data
504 * allocated with malloc() are ever placed in the state buffer, we have to
505 * be sure to free() them first!
506 *
507 * Set do_response to nonzero to output the SMTP RSET response code.
508 */
509void smtp_rset(int do_response) {
510 /*
511 * Our entire SMTP state is discarded when a RSET command is issued,
512 * but we need to preserve this one little piece of information, so
513 * we save it for later.
514 */
515
516 FlushStrBuf(SMTP->Cmd);
517 FlushStrBuf(SMTP->helo_node);
518 FlushStrBuf(SMTP->from);
519 FlushStrBuf(SMTP->recipients);
520 FlushStrBuf(SMTP->OneRcpt);
521
522 SMTP->command_state = 0;
523 SMTP->number_of_recipients = 0;
524 SMTP->delivery_mode = 0;
525 SMTP->message_originated_locally = 0;
526 SMTP->is_msa = 0;
527 /*
528 * we must remember is_lmtp & is_unfiltered.
529 */
530
531 /*
532 * It is somewhat ambiguous whether we want to log out when a RSET
533 * command is issued. Here's the code to do it. It is commented out
534 * because some clients (such as Pine) issue RSET commands before
535 * each message, but still expect to be logged in.
536 *
537 * if (CC->logged_in) {
538 * logout(CC);
539 * }
540 */
541
542 if (do_response) {
543 cprintf("250 Zap!\r\n");
544 }
545}
546
547
548/*
549 * Clear out the portions of the state buffer that need to be cleared out
550 * after the DATA command finishes.
551 */
552void smtp_data_clear(void) {
553 FlushStrBuf(SMTP->from);
554 FlushStrBuf(SMTP->recipients);
555 FlushStrBuf(SMTP->OneRcpt);
556 SMTP->number_of_recipients = 0;
557 SMTP->delivery_mode = 0;
558 SMTP->message_originated_locally = 0;
559}
560
561
562/*
563 * Implements the "MAIL FROM:" command
564 */
565void smtp_mail(void) {
566 char user[SIZ];
567 char node[SIZ];
568 char name[SIZ];
569
570 if (StrLength(SMTP->from) > 0) {
571 cprintf("503 Only one sender permitted\r\n");
572 return;
573 }
574
575 if (StrLength(SMTP->Cmd) < 6) {
576 cprintf("501 Syntax error\r\n");
577 return;
578 }
579
580 if (strncasecmp(ChrPtr(SMTP->Cmd) + 5, "From:", 5)) {
581 cprintf("501 Syntax error\r\n");
582 return;
583 }
584
585 StrBufAppendBuf(SMTP->from, SMTP->Cmd, 5);
586 StrBufTrim(SMTP->from);
587 if (strchr(ChrPtr(SMTP->from), '<') != NULL) {
588 StrBufStripAllBut(SMTP->from, '<', '>');
589 }
590
591 /* We used to reject empty sender names, until it was brought to our
592 * attention that RFC1123 5.2.9 requires that this be allowed. So now
593 * we allow it, but replace the empty string with a fake
594 * address so we don't have to contend with the empty string causing
595 * other code to fail when it's expecting something there.
596 */
597 if (StrLength(SMTP->from) == 0) {
598 StrBufPlain(SMTP->from, HKEY("someone@example.com"));
599 }
600
601 /* If this SMTP connection is from a logged-in user, force the 'from'
602 * to be the user's Internet e-mail address as Citadel knows it.
603 */
604 if (CC->logged_in) {
605 StrBufPlain(SMTP->from, CC->cs_inet_email, -1);
606 cprintf("250 Sender ok <%s>\r\n", ChrPtr(SMTP->from));
607 SMTP->message_originated_locally = 1;
608 return;
609 }
610
611 else if (SMTP->is_lmtp) {
612 /* Bypass forgery checking for LMTP */
613 }
614
615 /* Otherwise, make sure outsiders aren't trying to forge mail from
616 * this system (unless, of course, c_allow_spoofing is enabled)
617 */
618 else if (CtdlGetConfigInt("c_allow_spoofing") == 0) {
619 process_rfc822_addr(ChrPtr(SMTP->from), user, node, name);
620 syslog(LOG_DEBUG, "serv_smtp: claimed envelope sender is '%s' == '%s' @ '%s' ('%s')",
621 ChrPtr(SMTP->from), user, node, name
622 );
623 if (CtdlHostAlias(node) != hostalias_nomatch) {
624 cprintf("550 You must log in to send mail from %s\r\n", node);
625 FlushStrBuf(SMTP->from);
626 syslog(LOG_DEBUG, "serv_smtp: rejecting unauthenticated mail from %s", node);
627 return;
628 }
629 }
630
631 cprintf("250 Sender ok\r\n");
632}
633
634
635/*
636 * Implements the "RCPT To:" command
637 */
638void smtp_rcpt(void) {
639 char message_to_spammer[SIZ];
640 struct recptypes *valid = NULL;
641
642 if (StrLength(SMTP->from) == 0) {
643 cprintf("503 Need MAIL before RCPT\r\n");
644 return;
645 }
646
647 if (StrLength(SMTP->Cmd) < 6) {
648 cprintf("501 Syntax error\r\n");
649 return;
650 }
651
652 if (strncasecmp(ChrPtr(SMTP->Cmd) + 5, "To:", 3)) {
653 cprintf("501 Syntax error\r\n");
654 return;
655 }
656
657 if ( (SMTP->is_msa) && (!CC->logged_in) ) {
658 cprintf("550 You must log in to send mail on this port.\r\n");
659 FlushStrBuf(SMTP->from);
660 return;
661 }
662
663 FlushStrBuf(SMTP->OneRcpt);
664 StrBufAppendBuf(SMTP->OneRcpt, SMTP->Cmd, 8);
665 StrBufTrim(SMTP->OneRcpt);
666 StrBufStripAllBut(SMTP->OneRcpt, '<', '>');
667
668 if ( (StrLength(SMTP->OneRcpt) + StrLength(SMTP->recipients)) >= SIZ) {
669 cprintf("452 Too many recipients\r\n");
670 return;
671 }
672
673 // RBL check
674 if (
675 (!CC->logged_in) // Don't RBL authenticated users
676 && (!SMTP->is_lmtp) // Don't RBL LMTP clients
677 && (CtdlGetConfigInt("c_rbl_at_greeting") == 0) // Don't RBL if we did it at connection time
678 && (rbl_check(CC->cs_addr, message_to_spammer))
679 ) {
680 cprintf("550 %s\r\n", message_to_spammer);
681 return; // no need to free_recipients(valid)
682 } // because it hasn't been allocated yet
683
684 // This is a *preliminary* call to validate_recipients() to evaluate one recipient.
685 valid = validate_recipients(
686 (char *)ChrPtr(SMTP->OneRcpt),
688 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
689 );
690
691 // Any type of error thrown by validate_recipients() will make the SMTP transaction fail at this point.
692 if (valid->num_error != 0) {
693 cprintf("550 %s\r\n", valid->errormsg);
694 free_recipients(valid);
695 return;
696 }
697
698 if (
699 (valid->num_internet > 0) // If it's outbound Internet mail...
700 && (CC->logged_in) // ...and we're a logged-in user...
701 && (CtdlCheckInternetMailPermission(&CC->user)==0) // ...who does not have Internet mail rights...
702 ) {
703 cprintf("551 <%s> - you do not have permission to send Internet mail\r\n", ChrPtr(SMTP->OneRcpt));
704 free_recipients(valid);
705 return;
706 }
707
708 if (
709 (valid->num_internet > 0) // If it's outbound Internet mail...
710 && (SMTP->message_originated_locally == 0) // ...and also inbound Internet mail...
711 && (SMTP->is_lmtp == 0) /// ...and didn't arrive via LMTP...
712 ) {
713 cprintf("551 <%s> - relaying denied\r\n", ChrPtr(SMTP->OneRcpt));
714 free_recipients(valid);
715 return;
716 }
717
718 if (
719 (valid->num_room > 0) // If it's mail to a room (mailing list)...
720 && (SMTP->message_originated_locally == 0) // ...and also inbound Internet mail...
721 && (is_email_subscribed_to_list((char *)ChrPtr(SMTP->from), valid->recp_room) == 0) // ...and not a subscriber
722 ) {
723 cprintf("551 <%s> - This mailing list only accepts messages from subscribers.\r\n", ChrPtr(SMTP->OneRcpt));
724 free_recipients(valid);
725 return;
726 }
727
728 cprintf("250 RCPT ok <%s>\r\n", ChrPtr(SMTP->OneRcpt));
729 if (StrLength(SMTP->recipients) > 0) {
730 StrBufAppendBufPlain(SMTP->recipients, HKEY(","), 0);
731 }
732 StrBufAppendBuf(SMTP->recipients, SMTP->OneRcpt, 0);
733 SMTP->number_of_recipients ++;
734 if (valid != NULL) {
735 free_recipients(valid);
736 }
737}
738
739
740/*
741 * Implements the DATA command
742 */
743void smtp_data(void) {
744 StrBuf *body;
745 StrBuf *defbody;
746 struct CtdlMessage *msg = NULL;
747 long msgnum = (-1L);
748 char nowstamp[SIZ];
749 struct recptypes *valid;
750 int scan_errors;
751 int i;
752
753 if (StrLength(SMTP->from) == 0) {
754 cprintf("503 Need MAIL command first.\r\n");
755 return;
756 }
757
758 if (SMTP->number_of_recipients < 1) {
759 cprintf("503 Need RCPT command first.\r\n");
760 return;
761 }
762
763 cprintf("354 Transmit message now - terminate with '.' by itself\r\n");
764
765 datestring(nowstamp, sizeof nowstamp, time(NULL), DATESTRING_RFC822);
766 defbody = NewStrBufPlain(NULL, SIZ);
767
768 if (defbody != NULL) {
769 if (SMTP->is_lmtp && (CC->cs_UDSclientUID != -1)) {
770 StrBufPrintf(
771 defbody,
772 "Received: from %s (Citadel from userid %ld)\n"
773 " by %s; %s\n",
774 ChrPtr(SMTP->helo_node),
775 (long int) CC->cs_UDSclientUID,
776 CtdlGetConfigStr("c_fqdn"),
777 nowstamp);
778 }
779 else {
780 StrBufPrintf(
781 defbody,
782 "Received: from %s (%s [%s])\n"
783 " by %s; %s\n",
784 ChrPtr(SMTP->helo_node),
785 CC->cs_host,
786 CC->cs_addr,
787 CtdlGetConfigStr("c_fqdn"),
788 nowstamp);
789 }
790 }
791 body = CtdlReadMessageBodyBuf(HKEY("."), CtdlGetConfigLong("c_maxmsglen"), defbody, 1);
792 FreeStrBuf(&defbody);
793 if (body == NULL) {
794 cprintf("550 Unable to save message: internal error.\r\n");
795 return;
796 }
797
798 syslog(LOG_DEBUG, "serv_smtp: converting message...");
799 msg = convert_internet_message_buf(&body);
800
801 /* If the user is locally authenticated, FORCE the From: header to
802 * show up as the real sender. Yes, this violates the RFC standard,
803 * but IT MAKES SENSE. If you prefer strict RFC adherence over
804 * common sense, you can disable this in the configuration.
805 *
806 * We also set the "message room name" ('O' field) to MAILROOM
807 * (which is Mail> on most systems) to prevent it from getting set
808 * to something ugly like "0000058008.Sent Items>" when the message
809 * is read with a Citadel client.
810 */
811 if ( (CC->logged_in) && (CtdlGetConfigInt("c_rfc822_strict_from") != CFG_SMTP_FROM_NOFILTER) ) {
812 int validemail = 0;
813
814 if (!CM_IsEmpty(msg, erFc822Addr) &&
815 ((CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_CORRECT) ||
816 (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT) ) )
817 {
818 if (!IsEmptyStr(CC->cs_inet_email))
819 validemail = strcmp(CC->cs_inet_email, msg->cm_fields[erFc822Addr]) == 0;
820 if ((!validemail) &&
821 (!IsEmptyStr(CC->cs_inet_other_emails)))
822 {
823 int num_secondary_emails = 0;
824 int i;
825 num_secondary_emails = num_tokens(CC->cs_inet_other_emails, '|');
826 for (i=0; i < num_secondary_emails && !validemail; ++i) {
827 char buf[256];
828 extract_token(buf, CC->cs_inet_other_emails,i,'|',sizeof CC->cs_inet_other_emails);
829 validemail = strcmp(buf, msg->cm_fields[erFc822Addr]) == 0;
830 }
831 }
832 }
833
834 if (!validemail && (CtdlGetConfigInt("c_rfc822_strict_from") == CFG_SMTP_FROM_REJECT)) {
835 syslog(LOG_ERR, "serv_smtp: invalid sender '%s' - rejecting this message", msg->cm_fields[erFc822Addr]);
836 cprintf("550 Invalid sender '%s' - rejecting this message.\r\n", msg->cm_fields[erFc822Addr]);
837 return;
838 }
839
841 if (SMTP->preferred_sender_name != NULL)
842 CM_SetField(msg, eAuthor, SKEY(SMTP->preferred_sender_name));
843 else
844 CM_SetField(msg, eAuthor, CC->user.fullname, strlen(CC->user.fullname));
845
846 if (!validemail) {
847 if (SMTP->preferred_sender_email != NULL) {
848 CM_SetField(msg, erFc822Addr, SKEY(SMTP->preferred_sender_email));
849 }
850 else {
851 CM_SetField(msg, erFc822Addr, CC->cs_inet_email, strlen(CC->cs_inet_email));
852 }
853 }
854 }
855
856 /* Set the "envelope from" address */
857 CM_SetField(msg, eMessagePath, SKEY(SMTP->from));
858
859 /* Set the "envelope to" address */
860 CM_SetField(msg, eenVelopeTo, SKEY(SMTP->recipients));
861
862 /* Submit the message into the Citadel system. */
863 valid = validate_recipients(
864 (char *)ChrPtr(SMTP->recipients),
866 (SMTP->is_lmtp)? POST_LMTP: (CC->logged_in)? POST_LOGGED_IN: POST_EXTERNAL
867 );
868
869 /* If there are modules that want to scan this message before final
870 * submission (such as virus checkers or spam filters), call them now
871 * and give them an opportunity to reject the message.
872 */
873 if (SMTP->is_unfiltered) {
874 scan_errors = 0;
875 }
876 else {
877 scan_errors = PerformMessageHooks(msg, valid, EVT_SMTPSCAN);
878 }
879
880 if (scan_errors > 0) { /* We don't want this message! */
881
882 if (CM_IsEmpty(msg, eErrorMsg)) {
883 CM_SetField(msg, eErrorMsg, HKEY("Message rejected by filter"));
884 }
885
886 StrBufPrintf(SMTP->OneRcpt, "550 %s\r\n", msg->cm_fields[eErrorMsg]);
887 }
888
889 else { /* Ok, we'll accept this message. */
890 msgnum = CtdlSubmitMsg(msg, valid, "");
891 if (msgnum > 0L) {
892 StrBufPrintf(SMTP->OneRcpt, "250 Message accepted.\r\n");
893 }
894 else {
895 StrBufPrintf(SMTP->OneRcpt, "550 Internal delivery error\r\n");
896 }
897 }
898
899 /* For SMTP and ESMTP, just print the result message. For LMTP, we
900 * have to print one result message for each recipient. Since there
901 * is nothing in Citadel which would cause different recipients to
902 * have different results, we can get away with just spitting out the
903 * same message once for each recipient.
904 */
905 if (SMTP->is_lmtp) {
906 for (i=0; i<SMTP->number_of_recipients; ++i) {
907 cputbuf(SMTP->OneRcpt);
908 }
909 }
910 else {
911 cputbuf(SMTP->OneRcpt);
912 }
913
914 /* Write something to the syslog(which may or may not be where the
915 * rest of the Citadel logs are going; some sysadmins want LOG_MAIL).
916 */
917 syslog((LOG_MAIL | LOG_INFO),
918 "%ld: from=<%s>, nrcpts=%d, relay=%s [%s], stat=%s",
919 msgnum,
920 ChrPtr(SMTP->from),
921 SMTP->number_of_recipients,
922 CC->cs_host,
923 CC->cs_addr,
924 ChrPtr(SMTP->OneRcpt)
925 );
926
927 /* Clean up */
928 CM_Free(msg);
929 free_recipients(valid);
930 smtp_data_clear(); /* clear out the buffers now */
931}
932
933
934/*
935 * Implements the STARTTLS command
936 */
937void smtp_starttls(void) {
938 char ok_response[SIZ];
939 char nosup_response[SIZ];
940 char error_response[SIZ];
941
942 sprintf(ok_response, "220 Begin TLS negotiation now\r\n");
943 sprintf(nosup_response, "554 TLS not supported here\r\n");
944 sprintf(error_response, "554 Internal error\r\n");
945 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
946 smtp_rset(0);
947}
948
949
950/*
951 * Implements the NOOP (NO OPeration) command
952 */
953void smtp_noop(void) {
954 cprintf("250 NOOP\r\n");
955}
956
957
958/*
959 * Implements the QUIT command
960 */
961void smtp_quit(void) {
962 cprintf("221 Goodbye...\r\n");
963 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
964}
965
966
967/*
968 * Main command loop for SMTP server sessions.
969 */
971 static const ConstStr AuthPlainStr = {HKEY("AUTH PLAIN")};
972
973 if (SMTP == NULL) {
974 syslog(LOG_ERR, "serv_smtp: Session SMTP data is null. WTF? We will crash now.");
975 abort();
976 }
977
978 time(&CC->lastcmd);
979 if (CtdlClientGetLine(SMTP->Cmd) < 1) {
980 syslog(LOG_INFO, "SMTP: client disconnected: ending session.");
982 return;
983 }
984
985 if (SMTP->command_state == smtp_user) {
986 if (!strncmp(ChrPtr(SMTP->Cmd), AuthPlainStr.Key, AuthPlainStr.len)) {
988 }
989 else {
990 smtp_get_user(0);
991 }
992 return;
993 }
994
995 else if (SMTP->command_state == smtp_password) {
997 return;
998 }
999
1000 else if (SMTP->command_state == smtp_plain) {
1002 return;
1003 }
1004
1005 syslog(LOG_DEBUG, "serv_smtp: client sent command <%s>", ChrPtr(SMTP->Cmd));
1006
1007 if (!strncasecmp(ChrPtr(SMTP->Cmd), "NOOP", 4)) {
1008 smtp_noop();
1009 return;
1010 }
1011
1012 if (!strncasecmp(ChrPtr(SMTP->Cmd), "QUIT", 4)) {
1013 smtp_quit();
1014 return;
1015 }
1016
1017 if (!strncasecmp(ChrPtr(SMTP->Cmd), "HELO", 4)) {
1019 return;
1020 }
1021
1022 if (!strncasecmp(ChrPtr(SMTP->Cmd), "EHLO", 4)) {
1024 return;
1025 }
1026
1027 if (!strncasecmp(ChrPtr(SMTP->Cmd), "LHLO", 4)) {
1029 return;
1030 }
1031
1032 if (!strncasecmp(ChrPtr(SMTP->Cmd), "RSET", 4)) {
1033 smtp_rset(1);
1034 return;
1035 }
1036
1037 if (!strncasecmp(ChrPtr(SMTP->Cmd), "AUTH", 4)) {
1038 smtp_auth();
1039 return;
1040 }
1041
1042 if (!strncasecmp(ChrPtr(SMTP->Cmd), "DATA", 4)) {
1043 smtp_data();
1044 return;
1045 }
1046
1047 if (!strncasecmp(ChrPtr(SMTP->Cmd), "HELP", 4)) {
1048 smtp_help();
1049 return;
1050 }
1051
1052 if (!strncasecmp(ChrPtr(SMTP->Cmd), "MAIL", 4)) {
1053 smtp_mail();
1054 return;
1055 }
1056
1057 if (!strncasecmp(ChrPtr(SMTP->Cmd), "RCPT", 4)) {
1058 smtp_rcpt();
1059 return;
1060 }
1061#ifdef HAVE_OPENSSL
1062 if (!strncasecmp(ChrPtr(SMTP->Cmd), "STARTTLS", 8)) {
1063 smtp_starttls();
1064 return;
1065 }
1066#endif
1067
1068 cprintf("502 I'm afraid I can't do that.\r\n");
1069}
1070
1071
1072/*****************************************************************************/
1073/* MODULE INITIALIZATION STUFF */
1074/*****************************************************************************/
1075/*
1076 * This cleanup function blows away the temporary memory used by
1077 * the SMTP server.
1078 */
1080{
1081 /* Don't do this stuff if this is not an SMTP session! */
1082 if (CC->h_command_function != smtp_command_loop) return;
1083
1084 syslog(LOG_DEBUG, "Performing SMTP cleanup hook");
1085
1086 FreeStrBuf(&SMTP->Cmd);
1087 FreeStrBuf(&SMTP->helo_node);
1088 FreeStrBuf(&SMTP->from);
1089 FreeStrBuf(&SMTP->recipients);
1090 FreeStrBuf(&SMTP->OneRcpt);
1091 FreeStrBuf(&SMTP->preferred_sender_email);
1092 FreeStrBuf(&SMTP->preferred_sender_name);
1093
1094 free(SMTP);
1095}
1096
1097const char *CitadelServiceSMTP_MTA="SMTP-MTA";
1098const char *CitadelServiceSMTPS_MTA="SMTPs-MTA";
1099const char *CitadelServiceSMTP_MSA="SMTP-MSA";
1100const char *CitadelServiceSMTP_LMTP="LMTP";
1101const char *CitadelServiceSMTP_LMTP_UNF="LMTP-UnF";
1102
1103
1105{
1106 if (!threading) {
1107 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtp_port"), /* SMTP MTA */
1108 NULL,
1111 NULL,
1113
1114#ifdef HAVE_OPENSSL
1115 CtdlRegisterServiceHook(CtdlGetConfigInt("c_smtps_port"), /* SMTPS MTA */
1116 NULL,
1119 NULL,
1121#endif
1122
1123 CtdlRegisterServiceHook(CtdlGetConfigInt("c_msa_port"), /* SMTP MSA */
1124 NULL,
1127 NULL,
1129
1130 CtdlRegisterServiceHook(0, /* local LMTP */
1134 NULL,
1136
1137 CtdlRegisterServiceHook(0, /* local LMTP */
1141 NULL,
1143
1145 }
1146
1147 /* return our module name for the log */
1148 return "smtp";
1149}
#define ROOMNAMELEN
Definition: citadel.h:56
#define file_lmtp_unfiltered_socket
Definition: citadel_dirs.h:27
#define file_lmtp_socket
Definition: citadel_dirs.h:26
char * CtdlGetConfigStr(char *key)
Definition: config.c:384
int CtdlGetConfigInt(char *key)
Definition: config.c:417
long CtdlGetConfigLong(char *key)
Definition: config.c:428
#define CC
Definition: context.h:140
void CtdlModuleStartCryptoMsgs(char *ok_response, char *nosup_response, char *error_response)
int CtdlGetRoom(struct ctdlroom *qrbuf, const char *room_name)
Definition: room_ops.c:342
void CtdlRegisterServiceHook(int tcp_port, char *sockpath, void(*h_greeting_function)(void), void(*h_command_function)(void), void(*h_async_function)(void), const char *ServiceName)
void CtdlRegisterSessionHook(void(*fcn_ptr)(void), int EventType, int Priority)
@ pass_ok
Definition: ctdl_module.h:290
int CtdlTryPassword(const char *password, long len)
Definition: user_ops.c:864
@ login_ok
Definition: ctdl_module.h:302
int CtdlLoginExistingUser(const char *username)
Definition: user_ops.c:533
#define PRIO_STOP
Definition: ctdl_module.h:87
#define CTDL_MODULE_INIT(module_name)
Definition: ctdl_module.h:50
long datestring(char *buf, size_t n, time_t xtime, int which_format)
Definition: genstamp.c:26
@ DATESTRING_RFC822
Definition: genstamp.h:5
struct CtdlMessage * convert_internet_message_buf(StrBuf **rfc822)
struct recptypes * validate_recipients(char *supplied_recipients, const char *RemoteIdentifier, int Flags)
void free_recipients(struct recptypes *valid)
int CtdlHostAlias(char *fqdn)
void process_rfc822_addr(const char *rfc822, char *user, char *node, char *name)
int is_email_subscribed_to_list(char *email, char *room_name)
@ hostalias_nomatch
int rbl_check(char *cs_addr, char *message_to_spammer)
Definition: locate_host.c:233
void CM_Free(struct CtdlMessage *msg)
Definition: msgbase.c:310
StrBuf * CtdlReadMessageBodyBuf(char *terminator, long tlen, size_t maxlen, StrBuf *exist, int crlf)
Definition: msgbase.c:2976
int CtdlForEachMessage(int mode, long ref, char *search_string, char *content_type, struct CtdlMessage *compare, ForEachMsgCallback CallBack, void *userdata)
Definition: msgbase.c:626
struct CtdlMessage * CtdlFetchMessage(long msgnum, int with_body)
Definition: msgbase.c:1135
int CM_IsEmpty(struct CtdlMessage *Msg, eMsgField which)
Definition: msgbase.c:137
long CtdlSubmitMsg(struct CtdlMessage *msg, struct recptypes *recps, const char *force)
Definition: msgbase.c:2603
void CM_SetField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
Definition: msgbase.c:142
@ MSGS_ALL
Definition: msgbase.h:6
void * malloc(size_t)
void free(void *)
@ POST_LMTP
Definition: room_ops.h:16
@ POST_LOGGED_IN
Definition: room_ops.h:13
@ POST_EXTERNAL
Definition: room_ops.h:14
int PerformMessageHooks(struct CtdlMessage *msg, struct recptypes *recps, int EventType)
const char * CitadelServiceSMTP_MTA
Definition: serv_smtp.c:1097
void smtp_rset(int do_response)
Definition: serv_smtp.c:509
void smtp_quit(void)
Definition: serv_smtp.c:961
void smtp_help(void)
Definition: serv_smtp.c:331
void smtp_get_user(int offset)
Definition: serv_smtp.c:339
void lmtp_unfiltered_greeting(void)
Definition: serv_smtp.c:178
void smtp_try_plain(void)
Definition: serv_smtp.c:386
void smtp_auth(void)
Definition: serv_smtp.c:446
const char * CitadelServiceSMTPS_MTA
Definition: serv_smtp.c:1098
void smtp_greeting(int is_msa)
Definition: serv_smtp.c:89
const char * CitadelServiceSMTP_LMTP
Definition: serv_smtp.c:1100
void smtp_cleanup_function(void)
Definition: serv_smtp.c:1079
void smtp_rcpt(void)
Definition: serv_smtp.c:638
void smtp_get_pass(void)
Definition: serv_smtp.c:366
void smtp_data_clear(void)
Definition: serv_smtp.c:552
void smtp_auth_greeting(void)
Definition: serv_smtp.c:188
void smtp_mail(void)
Definition: serv_smtp.c:565
SMTP_FLAGS
Definition: serv_smtp.c:79
@ HELO
Definition: serv_smtp.c:80
@ EHLO
Definition: serv_smtp.c:81
@ LHLO
Definition: serv_smtp.c:82
void lmtp_greeting(void)
Definition: serv_smtp.c:160
void smtp_starttls(void)
Definition: serv_smtp.c:937
@ smtp_password
Definition: serv_smtp.c:75
@ smtp_plain
Definition: serv_smtp.c:76
@ smtp_user
Definition: serv_smtp.c:74
@ smtp_command
Definition: serv_smtp.c:73
void smtp_webcit_preferences_hack(void)
Definition: serv_smtp.c:288
const char * CitadelServiceSMTP_LMTP_UNF
Definition: serv_smtp.c:1101
void smtp_hello(int which_command)
Definition: serv_smtp.c:201
void smtp_msa_greeting(void)
Definition: serv_smtp.c:152
void smtp_noop(void)
Definition: serv_smtp.c:953
void smtp_webcit_preferences_hack_backend(long msgnum, void *userdata)
Definition: serv_smtp.c:262
void smtp_data(void)
Definition: serv_smtp.c:743
void smtps_greeting(void)
Definition: serv_smtp.c:140
void smtp_command_loop(void)
Definition: serv_smtp.c:970
const char * CitadelServiceSMTP_MSA
Definition: serv_smtp.c:1099
void smtp_mta_greeting(void)
Definition: serv_smtp.c:170
#define EVT_STOP
Definition: server.h:212
@ eMessagePath
Definition: server.h:317
@ eenVelopeTo
Definition: server.h:321
@ eErrorMsg
Definition: server.h:324
@ eMesageText
Definition: server.h:315
@ erFc822Addr
Definition: server.h:310
@ eAuthor
Definition: server.h:307
@ eMsgSubject
Definition: server.h:320
@ eOriginalRoom
Definition: server.h:316
@ KILLME_SPAMMER
Definition: server.h:105
@ KILLME_CLIENT_DISCONNECTED
Definition: server.h:90
@ KILLME_CLIENT_LOGGED_OUT
Definition: server.h:88
@ KILLME_MAX_SESSIONS_EXCEEDED
Definition: server.h:93
@ KILLME_NO_CRYPTO
Definition: server.h:100
#define CS_STEALTH
Definition: server.h:110
#define EVT_SMTPSCAN
Definition: server.h:233
const char * smtp_get_Recipients(void)
Definition: smtp_util.c:53
#define SMTP
Definition: smtp_util.h:33
int snprintf(char *buf, size_t max, const char *fmt,...)
Definition: snprintf.c:69
char * cm_fields[256]
Definition: server.h:37
char * recp_room
Definition: server.h:57
int num_internet
Definition: server.h:50
int num_room
Definition: server.h:52
int num_error
Definition: server.h:53
char * errormsg
Definition: server.h:54
#define USERCONFIGROOM
Definition: sysconfig.h:64
#define MAILROOM
Definition: sysconfig.h:61
#define SIZ
Definition: sysconfig.h:33
int CtdlClientGetLine(StrBuf *Target)
Definition: sysdep.c:518
void cprintf(const char *format,...)
Definition: sysdep.c:381
void cputbuf(const StrBuf *Buf)
Definition: sysdep.c:374
int server_shutting_down
Definition: threads.c:31
int CtdlCheckInternetMailPermission(struct ctdluser *who)
Definition: user_ops.c:365