5dacdabb38891bbc3041c8d4f5585dfdc982cd76
[citadel.git] / citadel / serv_smtp.c
1 /* $Id$ */
2
3 #include "sysdep.h"
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <stdio.h>
7 #include <fcntl.h>
8 #include <signal.h>
9 #include <pwd.h>
10 #include <errno.h>
11 #include <sys/types.h>
12 #include <sys/time.h>
13 #include <sys/wait.h>
14 #include <string.h>
15 #include <limits.h>
16 #include "citadel.h"
17 #include "server.h"
18 #include <time.h>
19 #include "sysdep_decls.h"
20 #include "citserver.h"
21 #include "support.h"
22 #include "config.h"
23 #include "dynloader.h"
24 #include "room_ops.h"
25 #include "user_ops.h"
26 #include "policy.h"
27 #include "database.h"
28 #include "msgbase.h"
29 #include "tools.h"
30 #include "internet_addressing.h"
31 #include "genstamp.h"
32
33
34 struct citsmtp {                /* Information about the current session */
35         int command_state;
36         struct usersupp vrfy_buffer;
37         int vrfy_count;
38         char vrfy_match[256];
39         char from[256];
40         int number_of_recipients;
41         int delivery_mode;
42 };
43
44 enum {                          /* Command states for login authentication */
45         smtp_command,
46         smtp_user,
47         smtp_password
48 };
49
50 enum {                          /* Delivery modes */
51         smtp_deliver_local,
52         smtp_deliver_remote
53 };
54
55 #define SMTP            ((struct citsmtp *)CtdlGetUserData(SYM_SMTP))
56 #define SMTP_RECP       ((char *)CtdlGetUserData(SYM_SMTP_RECP))
57
58 long SYM_SMTP;
59 long SYM_SMTP_RECP;
60
61 /*
62  * Here's where our SMTP session begins its happy day.
63  */
64 void smtp_greeting(void) {
65
66         strcpy(CC->cs_clientname, "SMTP session");
67         CC->internal_pgm = 1;
68         CC->cs_flags |= CS_STEALTH;
69         CtdlAllocUserData(SYM_SMTP, sizeof(struct citsmtp));
70         CtdlAllocUserData(SYM_SMTP_RECP, 256);
71         sprintf(SMTP_RECP, "%s", "");
72
73         cprintf("220 Welcome to the Citadel/UX ESMTP server at %s\r\n",
74                 config.c_fqdn);
75 }
76
77
78 /*
79  * Implement HELO and EHLO commands.
80  */
81 void smtp_hello(char *argbuf, int is_esmtp) {
82
83         if (!is_esmtp) {
84                 cprintf("250 Greetings and joyous salutations.\r\n");
85         }
86         else {
87                 cprintf("250-Greetings and joyous salutations.\r\n");
88                 cprintf("250-HELP\r\n");
89                 cprintf("250-SIZE %ld\r\n", config.c_maxmsglen);
90                 cprintf("250 AUTH=LOGIN\r\n");
91         }
92 }
93
94
95 /*
96  * Implement HELP command.
97  */
98 void smtp_help(void) {
99         cprintf("214-Here's the frequency, Kenneth:\r\n");
100         cprintf("214-    DATA\r\n");
101         cprintf("214-    EHLO\r\n");
102         cprintf("214-    EXPN\r\n");
103         cprintf("214-    HELO\r\n");
104         cprintf("214-    HELP\r\n");
105         cprintf("214-    MAIL\r\n");
106         cprintf("214-    NOOP\r\n");
107         cprintf("214-    QUIT\r\n");
108         cprintf("214-    RCPT\r\n");
109         cprintf("214-    RSET\r\n");
110         cprintf("214-    VRFY\r\n");
111         cprintf("214 I could tell you more, but then I'd have to kill you.\r\n");
112 }
113
114
115 /*
116  *
117  */
118 void smtp_get_user(char *argbuf) {
119         char buf[256];
120         char username[256];
121
122         decode_base64(username, argbuf);
123         lprintf(9, "Trying <%s>\n", username);
124         if (CtdlLoginExistingUser(username) == login_ok) {
125                 encode_base64(buf, "Password:");
126                 cprintf("334 %s\r\n", buf);
127                 SMTP->command_state = smtp_password;
128         }
129         else {
130                 cprintf("500 No such user.\r\n");
131                 SMTP->command_state = smtp_command;
132         }
133 }
134
135
136 /*
137  *
138  */
139 void smtp_get_pass(char *argbuf) {
140         char password[256];
141
142         decode_base64(password, argbuf);
143         lprintf(9, "Trying <%s>\n", password);
144         if (CtdlTryPassword(password) == pass_ok) {
145                 cprintf("235 Authentication successful.\r\n");
146                 lprintf(9, "SMTP auth login successful\n");
147                 CC->internal_pgm = 0;
148                 CC->cs_flags &= ~CS_STEALTH;
149         }
150         else {
151                 cprintf("500 Authentication failed.\r\n");
152         }
153         SMTP->command_state = smtp_command;
154 }
155
156
157 /*
158  *
159  */
160 void smtp_auth(char *argbuf) {
161         char buf[256];
162
163         if (strncasecmp(argbuf, "login", 5) ) {
164                 cprintf("550 We only support LOGIN authentication.\r\n");
165                 return;
166         }
167
168         if (strlen(argbuf) >= 7) {
169                 smtp_get_user(&argbuf[6]);
170         }
171
172         else {
173                 encode_base64(buf, "Username:");
174                 cprintf("334 %s\r\n", buf);
175                 SMTP->command_state = smtp_user;
176         }
177 }
178
179
180 /*
181  * Back end for smtp_vrfy() command
182  */
183 void smtp_vrfy_backend(struct usersupp *us, void *data) {
184
185         if (!fuzzy_match(us, SMTP->vrfy_match)) {
186                 ++SMTP->vrfy_count;
187                 memcpy(&SMTP->vrfy_buffer, us, sizeof(struct usersupp));
188         }
189 }
190
191
192 /* 
193  * Implements the VRFY (verify user name) command.
194  * Performs fuzzy match on full user names.
195  */
196 void smtp_vrfy(char *argbuf) {
197         SMTP->vrfy_count = 0;
198         strcpy(SMTP->vrfy_match, argbuf);
199         ForEachUser(smtp_vrfy_backend, NULL);
200
201         if (SMTP->vrfy_count < 1) {
202                 cprintf("550 String does not match anything.\r\n");
203         }
204         else if (SMTP->vrfy_count == 1) {
205                 cprintf("250 %s <cit%ld@%s>\r\n",
206                         SMTP->vrfy_buffer.fullname,
207                         SMTP->vrfy_buffer.usernum,
208                         config.c_fqdn);
209         }
210         else if (SMTP->vrfy_count > 1) {
211                 cprintf("553 Request ambiguous: %d users matched.\r\n",
212                         SMTP->vrfy_count);
213         }
214
215 }
216
217
218
219 /*
220  * Back end for smtp_expn() command
221  */
222 void smtp_expn_backend(struct usersupp *us, void *data) {
223
224         if (!fuzzy_match(us, SMTP->vrfy_match)) {
225
226                 if (SMTP->vrfy_count >= 1) {
227                         cprintf("250-%s <cit%ld@%s>\r\n",
228                                 SMTP->vrfy_buffer.fullname,
229                                 SMTP->vrfy_buffer.usernum,
230                                 config.c_fqdn);
231                 }
232
233                 ++SMTP->vrfy_count;
234                 memcpy(&SMTP->vrfy_buffer, us, sizeof(struct usersupp));
235         }
236 }
237
238
239 /* 
240  * Implements the EXPN (expand user name) command.
241  * Performs fuzzy match on full user names.
242  */
243 void smtp_expn(char *argbuf) {
244         SMTP->vrfy_count = 0;
245         strcpy(SMTP->vrfy_match, argbuf);
246         ForEachUser(smtp_expn_backend, NULL);
247
248         if (SMTP->vrfy_count < 1) {
249                 cprintf("550 String does not match anything.\r\n");
250         }
251         else if (SMTP->vrfy_count >= 1) {
252                 cprintf("250 %s <cit%ld@%s>\r\n",
253                         SMTP->vrfy_buffer.fullname,
254                         SMTP->vrfy_buffer.usernum,
255                         config.c_fqdn);
256         }
257 }
258
259
260 /*
261  * Implements the RSET (reset state) command.
262  * Currently this just zeroes out the state buffer.  If pointers to data
263  * allocated with mallok() are ever placed in the state buffer, we have to
264  * be sure to phree() them first!
265  */
266 void smtp_rset(void) {
267         memset(SMTP, 0, sizeof(struct citsmtp));
268         if (CC->logged_in) logout(CC);
269         cprintf("250 Zap!\r\n");
270 }
271
272
273
274 /*
275  * Implements the "MAIL From:" command
276  */
277 void smtp_mail(char *argbuf) {
278         char user[256];
279         char node[256];
280         int cvt;
281
282         if (strlen(SMTP->from) != 0) {
283                 cprintf("503 Only one sender permitted\r\n");
284                 return;
285         }
286
287         if (strncasecmp(argbuf, "From:", 5)) {
288                 cprintf("501 Syntax error\r\n");
289                 return;
290         }
291
292         strcpy(SMTP->from, &argbuf[5]);
293         striplt(SMTP->from);
294
295         if (strlen(SMTP->from) == 0) {
296                 cprintf("501 Empty sender name is not permitted\r\n");
297                 return;
298         }
299
300
301         /* If this SMTP connection is from a logged-in user, make sure that
302          * the user only sends email from his/her own address.
303          */
304         if (CC->logged_in) {
305                 cvt = convert_internet_address(user, node, SMTP->from);
306                 lprintf(9, "cvt=%d, citaddr=<%s@%s>\n", cvt, user, node);
307                 if ( (cvt != 0) || (strcasecmp(user, CC->usersupp.fullname))) {
308                         cprintf("550 <%s> is not your address.\r\n", SMTP->from);
309                         strcpy(SMTP->from, "");
310                         return;
311                 }
312         }
313
314         /* Otherwise, make sure outsiders aren't trying to forge mail from
315          * this system.
316          */
317         else {
318                 cvt = convert_internet_address(user, node, SMTP->from);
319                 lprintf(9, "cvt=%d, citaddr=<%s@%s>\n", cvt, user, node);
320                 if (!strcasecmp(node, config.c_nodename)) { /* FIX use fcn */
321                         cprintf("550 You must log in to send mail from %s\r\n",
322                                 config.c_fqdn);
323                         strcpy(SMTP->from, "");
324                         return;
325                 }
326         }
327
328         cprintf("250 Sender ok.  Groovy.\r\n");
329 }
330
331
332
333 /*
334  * Implements the "RCPT To:" command
335  */
336 void smtp_rcpt(char *argbuf) {
337         int cvt;
338         char user[256];
339         char node[256];
340         char recp[256];
341         int is_spam = 0;        /* FIX implement anti-spamming */
342
343         if (strlen(SMTP->from) == 0) {
344                 cprintf("503 MAIL first, then RCPT.  Duh.\r\n");
345                 return;
346         }
347
348         if (strncasecmp(argbuf, "To:", 3)) {
349                 cprintf("501 Syntax error\r\n");
350                 return;
351         }
352
353         strcpy(recp, &argbuf[3]);
354         striplt(recp);
355         alias(recp);
356
357         cvt = convert_internet_address(user, node, recp);
358         sprintf(recp, "%s@%s", user, node);
359
360
361         switch(cvt) {
362                 case rfc822_address_locally_validated:
363                         cprintf("250 %s is a valid recipient.\r\n", user);
364                         ++SMTP->number_of_recipients;
365                         CtdlReallocUserData(SYM_SMTP_RECP,
366                                 strlen(SMTP_RECP) + 1024 );
367                         strcat(SMTP_RECP, "local|");
368                         strcat(SMTP_RECP, user);
369                         strcat(SMTP_RECP, "|0\n");
370                         return;
371
372                 case rfc822_room_delivery:
373                         cprintf("250 Delivering to room '%s'\r\n", user);
374                         ++SMTP->number_of_recipients;
375                         CtdlReallocUserData(SYM_SMTP_RECP,
376                                 strlen(SMTP_RECP) + 1024 );
377                         strcat(SMTP_RECP, "room|");
378                         strcat(SMTP_RECP, user);
379                         strcat(SMTP_RECP, "|0\n");
380                         return;
381
382                 case rfc822_no_such_user:
383                         cprintf("550 %s: no such user\r\n", recp);
384                         return;
385
386                 case rfc822_address_invalid:
387                         if (is_spam) {
388                                 cprintf("551 Away with thee, spammer!\r\n");
389                         }
390                         else {
391                                 cprintf("250 Remote recipient %s ok\r\n", recp);
392                                 ++SMTP->number_of_recipients;
393                                 CtdlReallocUserData(SYM_SMTP_RECP,
394                                         strlen(SMTP_RECP) + 1024 );
395                                 strcat(SMTP_RECP, "remote|");
396                                 strcat(SMTP_RECP, recp);
397                                 strcat(SMTP_RECP, "|0\n");
398                                 return;
399                         }
400                         return;
401         }
402
403         cprintf("599 Unknown error\r\n");
404 }
405
406
407
408
409
410 /*
411  * Back end for smtp_data()  ... this does the actual delivery of the message
412  * Returns 0 on success, nonzero on failure
413  */
414 int smtp_message_delivery(struct CtdlMessage *msg) {
415         char user[1024];
416         char node[1024];
417         char name[1024];
418         char buf[1024];
419         char dtype[1024];
420         char room[1024];
421         int successful_saves = 0;       /* number of successful local saves */
422         int failed_saves = 0;           /* number of failed deliveries */
423         int remote_spools = 0;          /* number of copies to send out */
424         long msgid = (-1L);
425         int i;
426         struct usersupp userbuf;
427         char *instr;                    /* Remote delivery instructions */
428         struct CtdlMessage *imsg;
429
430         lprintf(9, "smtp_message_delivery() called\n");
431
432         /* Fill in 'from' fields with envelope information if missing */
433         process_rfc822_addr(SMTP->from, user, node, name);
434         if (msg->cm_fields['A']==NULL) msg->cm_fields['A'] = strdoop(user);
435         if (msg->cm_fields['N']==NULL) msg->cm_fields['N'] = strdoop(node);
436         if (msg->cm_fields['H']==NULL) msg->cm_fields['H'] = strdoop(name);
437
438         /* Save the message in the queue */
439         msgid = CtdlSaveMsg(msg,
440                 "",
441                 SMTP_SPOOLOUT_ROOM,
442                 MES_LOCAL,
443                 1);
444         ++successful_saves;
445
446         instr = mallok(1024);
447         sprintf(instr, "Content-type: %s\n\nmsgid|%ld\n",
448                 SPOOLMIME, msgid);
449
450         for (i=0; i<SMTP->number_of_recipients; ++i) {
451                 extract_token(buf, SMTP_RECP, i, '\n');
452                 extract(dtype, buf, 0);
453
454                 /* Stuff local mailboxes */
455                 if (!strcasecmp(dtype, "local")) {
456                         extract(user, buf, 1);
457                         if (getuser(&userbuf, user) == 0) {
458                                 MailboxName(room, &userbuf, MAILROOM);
459                                 CtdlSaveMsgPointerInRoom(room, msgid, 0);
460                                 ++successful_saves;
461                         }
462                         else {
463                                 ++failed_saves;
464                         }
465                 }
466
467                 /* Delivery to local non-mailbox rooms */
468                 if (!strcasecmp(dtype, "room")) {
469                         extract(room, buf, 1);
470                         CtdlSaveMsgPointerInRoom(room, msgid, 0);
471                         ++successful_saves;
472                 }
473
474                 /* Remote delivery */
475                 if (!strcasecmp(dtype, "remote")) {
476                         extract(user, buf, 1);
477                         instr = reallok(instr, strlen(instr) + 1024);
478                         sprintf(&instr[strlen(instr)],
479                                 "remote|%s|0\n",
480                                 user);
481                         ++remote_spools;
482                 }
483
484         }
485
486         /* If there are remote spools to be done, save the instructions */
487         if (remote_spools > 0) {
488                 imsg = mallok(sizeof(struct CtdlMessage));
489                 memset(imsg, 0, sizeof(struct CtdlMessage));
490                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
491                 imsg->cm_anon_type = MES_NORMAL;
492                 imsg->cm_format_type = FMT_RFC822;
493                 imsg->cm_fields['M'] = instr;
494                 CtdlSaveMsg(imsg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL, 1);
495                 CtdlFreeMessage(imsg);
496         }
497
498         /* If there are no remote spools, delete the message */ 
499         else {
500                 phree(instr);   /* only needed here, because CtdlSaveMsg()
501                                  * would free this buffer otherwise */
502                 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgid, NULL); 
503         }
504
505         return(failed_saves);
506 }
507
508
509
510 /*
511  * Implements the DATA command
512  */
513 void smtp_data(void) {
514         char *body;
515         struct CtdlMessage *msg;
516         int retval;
517         char nowstamp[256];
518
519         if (strlen(SMTP->from) == 0) {
520                 cprintf("503 Need MAIL command first.\r\n");
521                 return;
522         }
523
524         if (SMTP->number_of_recipients < 1) {
525                 cprintf("503 Need RCPT command first.\r\n");
526                 return;
527         }
528
529         cprintf("354 Transmit message now; terminate with '.' by itself\r\n");
530         
531         generate_rfc822_datestamp(nowstamp, time(NULL));
532         body = mallok(4096);
533         if (body != NULL) sprintf(body,
534                 "Received: from %s\n"
535                 "       by %s;\n"
536                 "       %s\n",
537                         "FIX.FIX.com",
538                         config.c_fqdn,
539                         nowstamp);
540         
541         body = CtdlReadMessageBody(".", config.c_maxmsglen, body);
542         if (body == NULL) {
543                 cprintf("550 Unable to save message text: internal error.\r\n");
544                 return;
545         }
546
547         lprintf(9, "Converting message...\n");
548         msg = convert_internet_message(body);
549
550         /* If the user is locally authenticated, FORCE the From: header to
551          * show up as the real sender
552          */
553         if (CC->logged_in) {
554                 if (msg->cm_fields['A'] != NULL) phree(msg->cm_fields['A']);
555                 if (msg->cm_fields['N'] != NULL) phree(msg->cm_fields['N']);
556                 if (msg->cm_fields['H'] != NULL) phree(msg->cm_fields['H']);
557                 msg->cm_fields['A'] = strdoop(CC->usersupp.fullname);
558                 msg->cm_fields['N'] = strdoop(config.c_nodename);
559                 msg->cm_fields['H'] = strdoop(config.c_humannode);
560         }
561
562         retval = smtp_message_delivery(msg);
563         CtdlFreeMessage(msg);
564
565         if (!retval) {
566                 cprintf("250 Message accepted for delivery.\r\n");
567         }
568         else {
569                 cprintf("550 Internal delivery errors: %d\r\n", retval);
570         }
571 }
572
573
574
575
576 /* 
577  * Main command loop for SMTP sessions.
578  */
579 void smtp_command_loop(void) {
580         char cmdbuf[256];
581
582         time(&CC->lastcmd);
583         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
584         if (client_gets(cmdbuf) < 1) {
585                 lprintf(3, "SMTP socket is broken.  Ending session.\n");
586                 CC->kill_me = 1;
587                 return;
588         }
589         lprintf(5, "citserver[%3d]: %s\n", CC->cs_pid, cmdbuf);
590         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
591
592         if (SMTP->command_state == smtp_user) {
593                 smtp_get_user(cmdbuf);
594         }
595
596         else if (SMTP->command_state == smtp_password) {
597                 smtp_get_pass(cmdbuf);
598         }
599
600         else if (!strncasecmp(cmdbuf, "AUTH", 4)) {
601                 smtp_auth(&cmdbuf[5]);
602         }
603
604         else if (!strncasecmp(cmdbuf, "DATA", 4)) {
605                 smtp_data();
606         }
607
608         else if (!strncasecmp(cmdbuf, "EHLO", 4)) {
609                 smtp_hello(&cmdbuf[5], 1);
610         }
611
612         else if (!strncasecmp(cmdbuf, "EXPN", 4)) {
613                 smtp_expn(&cmdbuf[5]);
614         }
615
616         else if (!strncasecmp(cmdbuf, "HELO", 4)) {
617                 smtp_hello(&cmdbuf[5], 0);
618         }
619
620         else if (!strncasecmp(cmdbuf, "HELP", 4)) {
621                 smtp_help();
622         }
623
624         else if (!strncasecmp(cmdbuf, "MAIL", 4)) {
625                 smtp_mail(&cmdbuf[5]);
626         }
627
628         else if (!strncasecmp(cmdbuf, "NOOP", 4)) {
629                 cprintf("250 This command successfully did nothing.\r\n");
630         }
631
632         else if (!strncasecmp(cmdbuf, "QUIT", 4)) {
633                 cprintf("221 Goodbye...\r\n");
634                 CC->kill_me = 1;
635                 return;
636                 }
637
638         else if (!strncasecmp(cmdbuf, "RCPT", 4)) {
639                 smtp_rcpt(&cmdbuf[5]);
640         }
641
642         else if (!strncasecmp(cmdbuf, "RSET", 4)) {
643                 smtp_rset();
644         }
645
646         else if (!strncasecmp(cmdbuf, "VRFY", 4)) {
647                 smtp_vrfy(&cmdbuf[5]);
648         }
649
650         else {
651                 cprintf("502 I'm sorry Dave, I'm afraid I can't do that.\r\n");
652         }
653
654 }
655
656
657 char *Dynamic_Module_Init(void)
658 {
659         SYM_SMTP = CtdlGetDynamicSymbol();
660         SYM_SMTP_RECP = CtdlGetDynamicSymbol();
661         CtdlRegisterServiceHook(SMTP_PORT,
662                                 smtp_greeting,
663                                 smtp_command_loop);
664         create_room(SMTP_SPOOLOUT_ROOM, 3, "", 0);
665         return "$Id$";
666 }
667