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