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