0345dd2395648d9315e0172bef27164980e6e382
[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\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.\n");
85         }
86         else {
87                 cprintf("250-Greetings and joyous salutations.\n");
88                 cprintf("250-HELP\n");
89                 cprintf("250-SIZE %ld\n", config.c_maxmsglen);
90                 cprintf("250 AUTH=LOGIN\n");
91         }
92 }
93
94
95 /*
96  * Implement HELP command.
97  */
98 void smtp_help(void) {
99         cprintf("214-Here's the frequency, Kenneth:\n");
100         cprintf("214-    DATA\n");
101         cprintf("214-    EHLO\n");
102         cprintf("214-    EXPN\n");
103         cprintf("214-    HELO\n");
104         cprintf("214-    HELP\n");
105         cprintf("214-    MAIL\n");
106         cprintf("214-    NOOP\n");
107         cprintf("214-    QUIT\n");
108         cprintf("214-    RCPT\n");
109         cprintf("214-    RSET\n");
110         cprintf("214-    VRFY\n");
111         cprintf("214 I could tell you more, but then I'd have to kill you.\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\n", buf);
127                 SMTP->command_state = smtp_password;
128         }
129         else {
130                 cprintf("500 No such user.\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.\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.\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.\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\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) {
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);
200
201         if (SMTP->vrfy_count < 1) {
202                 cprintf("550 String does not match anything.\n");
203         }
204         else if (SMTP->vrfy_count == 1) {
205                 cprintf("250 %s <cit%ld@%s>\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.\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) {
223
224         if (!fuzzy_match(us, SMTP->vrfy_match)) {
225
226                 if (SMTP->vrfy_count >= 1) {
227                         cprintf("250-%s <cit%ld@%s>\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);
247
248         if (SMTP->vrfy_count < 1) {
249                 cprintf("550 String does not match anything.\n");
250         }
251         else if (SMTP->vrfy_count >= 1) {
252                 cprintf("250 %s <cit%ld@%s>\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!\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\n");
284                 return;
285         }
286
287         if (strncasecmp(argbuf, "From:", 5)) {
288                 cprintf("501 Syntax error\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\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.\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\n",
322                                 config.c_fqdn);
323                         strcpy(SMTP->from, "");
324                         return;
325                 }
326         }
327
328         cprintf("250 Sender ok.  Groovy.\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.\n");
345                 return;
346         }
347
348         if (strncasecmp(argbuf, "To:", 3)) {
349                 cprintf("501 Syntax error\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.\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_no_such_user:
373                         cprintf("550 %s: no such user\n", recp);
374                         return;
375
376                 case rfc822_address_invalid:
377                         if (is_spam) {
378                                 cprintf("551 Away with thee, spammer!\n");
379                         }
380                         else {
381                                 cprintf("250 Remote recipient %s ok\n", recp);
382                                 ++SMTP->number_of_recipients;
383                                 CtdlReallocUserData(SYM_SMTP_RECP,
384                                         strlen(SMTP_RECP) + 1024 );
385                                 strcat(SMTP_RECP, "remote|");
386                                 strcat(SMTP_RECP, recp);
387                                 strcat(SMTP_RECP, "|0\n");
388                                 return;
389                         }
390                         return;
391         }
392
393         cprintf("599 Unknown error\n");
394 }
395
396
397
398
399
400 /*
401  * Back end for smtp_data()  ... this does the actual delivery of the message
402  * Returns 0 on success, nonzero on failure
403  */
404 int smtp_message_delivery(struct CtdlMessage *msg) {
405         char user[1024];
406         char node[1024];
407         char name[1024];
408         char buf[1024];
409         char dtype[1024];
410         char room[1024];
411         int successful_saves = 0;       /* number of successful local saves */
412         int failed_saves = 0;           /* number of failed deliveries */
413         int remote_spools = 0;          /* number of copies to send out */
414         long msgid = (-1L);
415         int i;
416         struct usersupp userbuf;
417         char *instr;                    /* Remote delivery instructions */
418         struct CtdlMessage *imsg;
419
420         lprintf(9, "smtp_message_delivery() called\n");
421
422         /* Fill in 'from' fields with envelope information if missing */
423         process_rfc822_addr(SMTP->from, user, node, name);
424         if (msg->cm_fields['A']==NULL) msg->cm_fields['A'] = strdoop(user);
425         if (msg->cm_fields['N']==NULL) msg->cm_fields['N'] = strdoop(node);
426         if (msg->cm_fields['H']==NULL) msg->cm_fields['H'] = strdoop(name);
427
428         /* Save the message in the queue */
429         msgid = CtdlSaveMsg(msg,
430                 "",
431                 SMTP_SPOOLOUT_ROOM,
432                 MES_LOCAL,
433                 1);
434         ++successful_saves;
435
436         instr = mallok(1024);
437         sprintf(instr, "Content-type: %s\n\nmsgid|%ld\n",
438                 SPOOLMIME, msgid);
439
440         for (i=0; i<SMTP->number_of_recipients; ++i) {
441                 extract_token(buf, SMTP_RECP, i, '\n');
442                 extract(dtype, buf, 0);
443
444                 /* Stuff local mailboxes */
445                 if (!strcasecmp(dtype, "local")) {
446                         extract(user, buf, 1);
447                         if (getuser(&userbuf, user) == 0) {
448                                 MailboxName(room, &userbuf, MAILROOM);
449                                 CtdlSaveMsgPointerInRoom(room, msgid, 0);
450                                 ++successful_saves;
451                         }
452                         else {
453                                 ++failed_saves;
454                         }
455                 }
456
457                 /* Remote delivery */
458                 if (!strcasecmp(dtype, "remote")) {
459                         extract(user, buf, 1);
460                         instr = reallok(instr, strlen(instr) + 1024);
461                         sprintf(&instr[strlen(instr)],
462                                 "remote|%s|0\n",
463                                 user);
464                         ++remote_spools;
465                 }
466
467         }
468
469         /* If there are remote spools to be done, save the instructions */
470         if (remote_spools > 0) {
471                 imsg = mallok(sizeof(struct CtdlMessage));
472                 memset(imsg, 0, sizeof(struct CtdlMessage));
473                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
474                 imsg->cm_anon_type = MES_NORMAL;
475                 imsg->cm_format_type = FMT_RFC822;
476                 imsg->cm_fields['M'] = instr;
477                 CtdlSaveMsg(imsg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL, 1);
478                 CtdlFreeMessage(imsg);
479         }
480
481         /* If there are no remote spools, delete the message */ 
482         else {
483                 phree(instr);   /* only needed here, because CtdlSaveMsg()
484                                  * would free this buffer otherwise */
485                 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgid, NULL); 
486         }
487
488         return(failed_saves);
489 }
490
491
492
493 /*
494  * Implements the DATA command
495  */
496 void smtp_data(void) {
497         char *body;
498         struct CtdlMessage *msg;
499         int retval;
500         char nowstamp[256];
501
502         if (strlen(SMTP->from) == 0) {
503                 cprintf("503 Need MAIL command first.\n");
504                 return;
505         }
506
507         if (SMTP->number_of_recipients < 1) {
508                 cprintf("503 Need RCPT command first.\n");
509                 return;
510         }
511
512         cprintf("354 Transmit message now; terminate with '.' by itself\n");
513         
514         generate_rfc822_datestamp(nowstamp, time(NULL));
515         body = mallok(4096);
516         if (body != NULL) sprintf(body,
517                 "Received: from %s\n"
518                 "       by %s;\n"
519                 "       %s\n",
520                         "FIX.FIX.com",
521                         config.c_fqdn,
522                         nowstamp);
523         
524         body = CtdlReadMessageBody(".", config.c_maxmsglen, body);
525         if (body == NULL) {
526                 cprintf("550 Unable to save message text: internal error.\n");
527                 return;
528         }
529
530         lprintf(9, "Converting message...\n");
531         msg = convert_internet_message(body);
532
533         /* If the user is locally authenticated, FORCE the From: header to
534          * show up as the real sender
535          */
536         if (CC->logged_in) {
537                 if (msg->cm_fields['A'] != NULL) phree(msg->cm_fields['A']);
538                 if (msg->cm_fields['N'] != NULL) phree(msg->cm_fields['N']);
539                 if (msg->cm_fields['H'] != NULL) phree(msg->cm_fields['H']);
540                 msg->cm_fields['A'] = strdoop(CC->usersupp.fullname);
541                 msg->cm_fields['N'] = strdoop(config.c_nodename);
542                 msg->cm_fields['H'] = strdoop(config.c_humannode);
543         }
544
545         retval = smtp_message_delivery(msg);
546         CtdlFreeMessage(msg);
547
548         if (!retval) {
549                 cprintf("250 Message accepted for delivery.\n");
550         }
551         else {
552                 cprintf("550 Internal delivery errors: %d\n", retval);
553         }
554 }
555
556
557
558
559 /* 
560  * Main command loop for SMTP sessions.
561  */
562 void smtp_command_loop(void) {
563         char cmdbuf[256];
564
565         time(&CC->lastcmd);
566         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
567         if (client_gets(cmdbuf) < 1) {
568                 lprintf(3, "SMTP socket is broken.  Ending session.\n");
569                 CC->kill_me = 1;
570                 return;
571         }
572         lprintf(5, "citserver[%3d]: %s\n", CC->cs_pid, cmdbuf);
573         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
574
575         if (SMTP->command_state == smtp_user) {
576                 smtp_get_user(cmdbuf);
577         }
578
579         else if (SMTP->command_state == smtp_password) {
580                 smtp_get_pass(cmdbuf);
581         }
582
583         else if (!strncasecmp(cmdbuf, "AUTH", 4)) {
584                 smtp_auth(&cmdbuf[5]);
585         }
586
587         else if (!strncasecmp(cmdbuf, "DATA", 4)) {
588                 smtp_data();
589         }
590
591         else if (!strncasecmp(cmdbuf, "EHLO", 4)) {
592                 smtp_hello(&cmdbuf[5], 1);
593         }
594
595         else if (!strncasecmp(cmdbuf, "EXPN", 4)) {
596                 smtp_expn(&cmdbuf[5]);
597         }
598
599         else if (!strncasecmp(cmdbuf, "HELO", 4)) {
600                 smtp_hello(&cmdbuf[5], 0);
601         }
602
603         else if (!strncasecmp(cmdbuf, "HELP", 4)) {
604                 smtp_help();
605         }
606
607         else if (!strncasecmp(cmdbuf, "MAIL", 4)) {
608                 smtp_mail(&cmdbuf[5]);
609         }
610
611         else if (!strncasecmp(cmdbuf, "NOOP", 4)) {
612                 cprintf("250 This command successfully did nothing.\n");
613         }
614
615         else if (!strncasecmp(cmdbuf, "QUIT", 4)) {
616                 cprintf("221 Goodbye...\n");
617                 CC->kill_me = 1;
618                 return;
619                 }
620
621         else if (!strncasecmp(cmdbuf, "RCPT", 4)) {
622                 smtp_rcpt(&cmdbuf[5]);
623         }
624
625         else if (!strncasecmp(cmdbuf, "RSET", 4)) {
626                 smtp_rset();
627         }
628
629         else if (!strncasecmp(cmdbuf, "VRFY", 4)) {
630                 smtp_vrfy(&cmdbuf[5]);
631         }
632
633         else {
634                 cprintf("502 I'm sorry Dave, I'm afraid I can't do that.\n");
635         }
636
637 }
638
639
640 char *Dynamic_Module_Init(void)
641 {
642         SYM_SMTP = CtdlGetDynamicSymbol();
643         SYM_SMTP_RECP = CtdlGetDynamicSymbol();
644         CtdlRegisterServiceHook(SMTP_PORT,
645                                 smtp_greeting,
646                                 smtp_command_loop);
647         create_room(SMTP_SPOOLOUT_ROOM, 3, "", 0);
648         return "$Id$";
649 }
650