* Renamed CtdlLocalHost() to CtdlHostAlias() and worked it a little deeper into
[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 #include "domain.h"
33 #include "clientsocket.h"
34
35
36 struct citsmtp {                /* Information about the current session */
37         int command_state;
38         char helo_node[256];
39         struct usersupp vrfy_buffer;
40         int vrfy_count;
41         char vrfy_match[256];
42         char from[256];
43         int number_of_recipients;
44         int delivery_mode;
45 };
46
47 enum {                          /* Command states for login authentication */
48         smtp_command,
49         smtp_user,
50         smtp_password
51 };
52
53 enum {                          /* Delivery modes */
54         smtp_deliver_local,
55         smtp_deliver_remote
56 };
57
58 #define SMTP            ((struct citsmtp *)CtdlGetUserData(SYM_SMTP))
59 #define SMTP_RECP       ((char *)CtdlGetUserData(SYM_SMTP_RECP))
60
61 long SYM_SMTP;
62 long SYM_SMTP_RECP;
63
64
65
66 /*****************************************************************************/
67 /*                      SMTP SERVER (INBOUND) STUFF                          */
68 /*****************************************************************************/
69
70
71
72
73 /*
74  * Here's where our SMTP session begins its happy day.
75  */
76 void smtp_greeting(void) {
77
78         strcpy(CC->cs_clientname, "SMTP session");
79         CC->internal_pgm = 1;
80         CC->cs_flags |= CS_STEALTH;
81         CtdlAllocUserData(SYM_SMTP, sizeof(struct citsmtp));
82         CtdlAllocUserData(SYM_SMTP_RECP, 256);
83         sprintf(SMTP_RECP, "%s", "");
84
85         cprintf("220 Welcome to the Citadel/UX ESMTP server at %s\r\n",
86                 config.c_fqdn);
87 }
88
89
90 /*
91  * Implement HELO and EHLO commands.
92  */
93 void smtp_hello(char *argbuf, int is_esmtp) {
94
95         safestrncpy(SMTP->helo_node, argbuf, sizeof SMTP->helo_node);
96
97         if (!is_esmtp) {
98                 cprintf("250 Greetings and joyous salutations.\r\n");
99         }
100         else {
101                 cprintf("250-Greetings and joyous salutations.\r\n");
102                 cprintf("250-HELP\r\n");
103                 cprintf("250-SIZE %ld\r\n", config.c_maxmsglen);
104                 cprintf("250 AUTH=LOGIN\r\n");
105         }
106 }
107
108
109 /*
110  * Implement HELP command.
111  */
112 void smtp_help(void) {
113         cprintf("214-Here's the frequency, Kenneth:\r\n");
114         cprintf("214-    DATA\r\n");
115         cprintf("214-    EHLO\r\n");
116         cprintf("214-    EXPN\r\n");
117         cprintf("214-    HELO\r\n");
118         cprintf("214-    HELP\r\n");
119         cprintf("214-    MAIL\r\n");
120         cprintf("214-    NOOP\r\n");
121         cprintf("214-    QUIT\r\n");
122         cprintf("214-    RCPT\r\n");
123         cprintf("214-    RSET\r\n");
124         cprintf("214-    VRFY\r\n");
125         cprintf("214 I could tell you more, but then I'd have to kill you.\r\n");
126 }
127
128
129 /*
130  *
131  */
132 void smtp_get_user(char *argbuf) {
133         char buf[256];
134         char username[256];
135
136         decode_base64(username, argbuf);
137         lprintf(9, "Trying <%s>\n", username);
138         if (CtdlLoginExistingUser(username) == login_ok) {
139                 encode_base64(buf, "Password:");
140                 cprintf("334 %s\r\n", buf);
141                 SMTP->command_state = smtp_password;
142         }
143         else {
144                 cprintf("500 No such user.\r\n");
145                 SMTP->command_state = smtp_command;
146         }
147 }
148
149
150 /*
151  *
152  */
153 void smtp_get_pass(char *argbuf) {
154         char password[256];
155
156         decode_base64(password, argbuf);
157         lprintf(9, "Trying <%s>\n", password);
158         if (CtdlTryPassword(password) == pass_ok) {
159                 cprintf("235 Authentication successful.\r\n");
160                 lprintf(9, "SMTP authenticated login successful\n");
161                 CC->internal_pgm = 0;
162                 CC->cs_flags &= ~CS_STEALTH;
163         }
164         else {
165                 cprintf("500 Authentication failed.\r\n");
166         }
167         SMTP->command_state = smtp_command;
168 }
169
170
171 /*
172  *
173  */
174 void smtp_auth(char *argbuf) {
175         char buf[256];
176
177         if (strncasecmp(argbuf, "login", 5) ) {
178                 cprintf("550 We only support LOGIN authentication.\r\n");
179                 return;
180         }
181
182         if (strlen(argbuf) >= 7) {
183                 smtp_get_user(&argbuf[6]);
184         }
185
186         else {
187                 encode_base64(buf, "Username:");
188                 cprintf("334 %s\r\n", buf);
189                 SMTP->command_state = smtp_user;
190         }
191 }
192
193
194 /*
195  * Back end for smtp_vrfy() command
196  */
197 void smtp_vrfy_backend(struct usersupp *us, void *data) {
198
199         if (!fuzzy_match(us, SMTP->vrfy_match)) {
200                 ++SMTP->vrfy_count;
201                 memcpy(&SMTP->vrfy_buffer, us, sizeof(struct usersupp));
202         }
203 }
204
205
206 /* 
207  * Implements the VRFY (verify user name) command.
208  * Performs fuzzy match on full user names.
209  */
210 void smtp_vrfy(char *argbuf) {
211         SMTP->vrfy_count = 0;
212         strcpy(SMTP->vrfy_match, argbuf);
213         ForEachUser(smtp_vrfy_backend, NULL);
214
215         if (SMTP->vrfy_count < 1) {
216                 cprintf("550 String does not match anything.\r\n");
217         }
218         else if (SMTP->vrfy_count == 1) {
219                 cprintf("250 %s <cit%ld@%s>\r\n",
220                         SMTP->vrfy_buffer.fullname,
221                         SMTP->vrfy_buffer.usernum,
222                         config.c_fqdn);
223         }
224         else if (SMTP->vrfy_count > 1) {
225                 cprintf("553 Request ambiguous: %d users matched.\r\n",
226                         SMTP->vrfy_count);
227         }
228
229 }
230
231
232
233 /*
234  * Back end for smtp_expn() command
235  */
236 void smtp_expn_backend(struct usersupp *us, void *data) {
237
238         if (!fuzzy_match(us, SMTP->vrfy_match)) {
239
240                 if (SMTP->vrfy_count >= 1) {
241                         cprintf("250-%s <cit%ld@%s>\r\n",
242                                 SMTP->vrfy_buffer.fullname,
243                                 SMTP->vrfy_buffer.usernum,
244                                 config.c_fqdn);
245                 }
246
247                 ++SMTP->vrfy_count;
248                 memcpy(&SMTP->vrfy_buffer, us, sizeof(struct usersupp));
249         }
250 }
251
252
253 /* 
254  * Implements the EXPN (expand user name) command.
255  * Performs fuzzy match on full user names.
256  */
257 void smtp_expn(char *argbuf) {
258         SMTP->vrfy_count = 0;
259         strcpy(SMTP->vrfy_match, argbuf);
260         ForEachUser(smtp_expn_backend, NULL);
261
262         if (SMTP->vrfy_count < 1) {
263                 cprintf("550 String does not match anything.\r\n");
264         }
265         else if (SMTP->vrfy_count >= 1) {
266                 cprintf("250 %s <cit%ld@%s>\r\n",
267                         SMTP->vrfy_buffer.fullname,
268                         SMTP->vrfy_buffer.usernum,
269                         config.c_fqdn);
270         }
271 }
272
273
274 /*
275  * Implements the RSET (reset state) command.
276  * Currently this just zeroes out the state buffer.  If pointers to data
277  * allocated with mallok() are ever placed in the state buffer, we have to
278  * be sure to phree() them first!
279  */
280 void smtp_rset(void) {
281         memset(SMTP, 0, sizeof(struct citsmtp));
282         if (CC->logged_in) logout(CC);
283         cprintf("250 Zap!\r\n");
284 }
285
286
287
288 /*
289  * Implements the "MAIL From:" command
290  */
291 void smtp_mail(char *argbuf) {
292         char user[256];
293         char node[256];
294         int cvt;
295
296         if (strlen(SMTP->from) != 0) {
297                 cprintf("503 Only one sender permitted\r\n");
298                 return;
299         }
300
301         if (strncasecmp(argbuf, "From:", 5)) {
302                 cprintf("501 Syntax error\r\n");
303                 return;
304         }
305
306         strcpy(SMTP->from, &argbuf[5]);
307         striplt(SMTP->from);
308
309         if (strlen(SMTP->from) == 0) {
310                 cprintf("501 Empty sender name is not permitted\r\n");
311                 return;
312         }
313
314
315         /* If this SMTP connection is from a logged-in user, make sure that
316          * the user only sends email from his/her own address.
317          */
318         if (CC->logged_in) {
319                 cvt = convert_internet_address(user, node, SMTP->from);
320                 lprintf(9, "cvt=%d, citaddr=<%s@%s>\n", cvt, user, node);
321                 if ( (cvt != 0) || (strcasecmp(user, CC->usersupp.fullname))) {
322                         cprintf("550 <%s> is not your address.\r\n", SMTP->from);
323                         strcpy(SMTP->from, "");
324                         return;
325                 }
326         }
327
328         /* Otherwise, make sure outsiders aren't trying to forge mail from
329          * this system.
330          */
331         else {
332                 cvt = convert_internet_address(user, node, SMTP->from);
333                 lprintf(9, "cvt=%d, citaddr=<%s@%s>\n", cvt, user, node);
334                 if (CtdlHostAlias(node) == hostalias_localhost) {
335                         cprintf("550 You must log in to send mail from %s\r\n",
336                                 node);
337                         strcpy(SMTP->from, "");
338                         return;
339                 }
340         }
341
342         cprintf("250 Sender ok.  Groovy.\r\n");
343 }
344
345
346
347 /*
348  * Implements the "RCPT To:" command
349  */
350 void smtp_rcpt(char *argbuf) {
351         int cvt;
352         char user[256];
353         char node[256];
354         char recp[256];
355         int is_spam = 0;        /* FIX implement anti-spamming */
356
357         if (strlen(SMTP->from) == 0) {
358                 cprintf("503 MAIL first, then RCPT.  Duh.\r\n");
359                 return;
360         }
361
362         if (strncasecmp(argbuf, "To:", 3)) {
363                 cprintf("501 Syntax error\r\n");
364                 return;
365         }
366
367         strcpy(recp, &argbuf[3]);
368         striplt(recp);
369         alias(recp);
370
371         cvt = convert_internet_address(user, node, recp);
372         sprintf(recp, "%s@%s", user, node);
373
374
375         switch(cvt) {
376                 case rfc822_address_locally_validated:
377                         cprintf("250 %s is a valid recipient.\r\n", user);
378                         ++SMTP->number_of_recipients;
379                         CtdlReallocUserData(SYM_SMTP_RECP,
380                                 strlen(SMTP_RECP) + 1024 );
381                         strcat(SMTP_RECP, "local|");
382                         strcat(SMTP_RECP, user);
383                         strcat(SMTP_RECP, "|0\n");
384                         return;
385
386                 case rfc822_room_delivery:
387                         cprintf("250 Delivering to room '%s'\r\n", user);
388                         ++SMTP->number_of_recipients;
389                         CtdlReallocUserData(SYM_SMTP_RECP,
390                                 strlen(SMTP_RECP) + 1024 );
391                         strcat(SMTP_RECP, "room|");
392                         strcat(SMTP_RECP, user);
393                         strcat(SMTP_RECP, "|0|\n");
394                         return;
395
396                 case rfc822_no_such_user:
397                         cprintf("550 %s: no such user\r\n", recp);
398                         return;
399
400                 case rfc822_address_invalid:
401                         if (is_spam) {
402                                 cprintf("551 Away with thee, spammer!\r\n");
403                         }
404                         else {
405                                 cprintf("250 Remote recipient %s ok\r\n", recp);
406                                 ++SMTP->number_of_recipients;
407                                 CtdlReallocUserData(SYM_SMTP_RECP,
408                                         strlen(SMTP_RECP) + 1024 );
409                                 strcat(SMTP_RECP, "remote|");
410                                 strcat(SMTP_RECP, recp);
411                                 strcat(SMTP_RECP, "|0|\n");
412                                 return;
413                         }
414                         return;
415         }
416
417         cprintf("599 Unknown error\r\n");
418 }
419
420
421
422
423
424 /*
425  * Back end for smtp_data()  ... this does the actual delivery of the message
426  * Returns 0 on success, nonzero on failure
427  */
428 int smtp_message_delivery(struct CtdlMessage *msg) {
429         char user[1024];
430         char node[1024];
431         char name[1024];
432         char buf[1024];
433         char dtype[1024];
434         char room[1024];
435         int successful_saves = 0;       /* number of successful local saves */
436         int failed_saves = 0;           /* number of failed deliveries */
437         int remote_spools = 0;          /* number of copies to send out */
438         long msgid = (-1L);
439         int i;
440         struct usersupp userbuf;
441         char *instr;                    /* Remote delivery instructions */
442         struct CtdlMessage *imsg;
443
444         lprintf(9, "smtp_message_delivery() called\n");
445
446         /* Fill in 'from' fields with envelope information if missing */
447         process_rfc822_addr(SMTP->from, user, node, name);
448         if (msg->cm_fields['A']==NULL) msg->cm_fields['A'] = strdoop(user);
449         if (msg->cm_fields['N']==NULL) msg->cm_fields['N'] = strdoop(node);
450         if (msg->cm_fields['H']==NULL) msg->cm_fields['H'] = strdoop(name);
451
452         /* Save the message in the queue */
453         msgid = CtdlSaveMsg(msg,
454                 "",
455                 SMTP_SPOOLOUT_ROOM,
456                 MES_LOCAL,
457                 1);
458         ++successful_saves;
459
460         instr = mallok(1024);
461         sprintf(instr, "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n",
462                 SPOOLMIME, msgid, time(NULL) );
463
464         for (i=0; i<SMTP->number_of_recipients; ++i) {
465                 extract_token(buf, SMTP_RECP, i, '\n');
466                 extract(dtype, buf, 0);
467
468                 /* Stuff local mailboxes */
469                 if (!strcasecmp(dtype, "local")) {
470                         extract(user, buf, 1);
471                         if (getuser(&userbuf, user) == 0) {
472                                 MailboxName(room, &userbuf, MAILROOM);
473                                 CtdlSaveMsgPointerInRoom(room, msgid, 0);
474                                 ++successful_saves;
475                         }
476                         else {
477                                 ++failed_saves;
478                         }
479                 }
480
481                 /* Delivery to local non-mailbox rooms */
482                 if (!strcasecmp(dtype, "room")) {
483                         extract(room, buf, 1);
484                         CtdlSaveMsgPointerInRoom(room, msgid, 0);
485                         ++successful_saves;
486                 }
487
488                 /* Remote delivery */
489                 if (!strcasecmp(dtype, "remote")) {
490                         extract(user, buf, 1);
491                         instr = reallok(instr, strlen(instr) + 1024);
492                         sprintf(&instr[strlen(instr)],
493                                 "remote|%s|0\n",
494                                 user);
495                         ++remote_spools;
496                 }
497
498         }
499
500         /* If there are remote spools to be done, save the instructions */
501         if (remote_spools > 0) {
502                 imsg = mallok(sizeof(struct CtdlMessage));
503                 memset(imsg, 0, sizeof(struct CtdlMessage));
504                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
505                 imsg->cm_anon_type = MES_NORMAL;
506                 imsg->cm_format_type = FMT_RFC822;
507                 imsg->cm_fields['M'] = instr;
508                 CtdlSaveMsg(imsg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL, 1);
509                 CtdlFreeMessage(imsg);
510         }
511
512         /* If there are no remote spools, delete the message */ 
513         else {
514                 phree(instr);   /* only needed here, because CtdlSaveMsg()
515                                  * would free this buffer otherwise */
516                 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgid, NULL); 
517         }
518
519         return(failed_saves);
520 }
521
522
523
524 /*
525  * Implements the DATA command
526  */
527 void smtp_data(void) {
528         char *body;
529         struct CtdlMessage *msg;
530         int retval;
531         char nowstamp[256];
532
533         if (strlen(SMTP->from) == 0) {
534                 cprintf("503 Need MAIL command first.\r\n");
535                 return;
536         }
537
538         if (SMTP->number_of_recipients < 1) {
539                 cprintf("503 Need RCPT command first.\r\n");
540                 return;
541         }
542
543         cprintf("354 Transmit message now; terminate with '.' by itself\r\n");
544         
545         generate_rfc822_datestamp(nowstamp, time(NULL));
546         body = mallok(4096);
547
548         if (body != NULL) sprintf(body,
549                 "Received: from %s\n"
550                 "       by %s;\n"
551                 "       %s\n",
552                         SMTP->helo_node,
553                         config.c_fqdn,
554                         nowstamp);
555         
556         body = CtdlReadMessageBody(".", config.c_maxmsglen, body);
557         if (body == NULL) {
558                 cprintf("550 Unable to save message text: internal error.\r\n");
559                 return;
560         }
561
562         lprintf(9, "Converting message...\n");
563         msg = convert_internet_message(body);
564
565         /* If the user is locally authenticated, FORCE the From: header to
566          * show up as the real sender
567          */
568         if (CC->logged_in) {
569                 if (msg->cm_fields['A'] != NULL) phree(msg->cm_fields['A']);
570                 if (msg->cm_fields['N'] != NULL) phree(msg->cm_fields['N']);
571                 if (msg->cm_fields['H'] != NULL) phree(msg->cm_fields['H']);
572                 msg->cm_fields['A'] = strdoop(CC->usersupp.fullname);
573                 msg->cm_fields['N'] = strdoop(config.c_nodename);
574                 msg->cm_fields['H'] = strdoop(config.c_humannode);
575         }
576
577         retval = smtp_message_delivery(msg);
578         CtdlFreeMessage(msg);
579
580         if (!retval) {
581                 cprintf("250 Message accepted for delivery.\r\n");
582         }
583         else {
584                 cprintf("550 Internal delivery errors: %d\r\n", retval);
585         }
586 }
587
588
589
590
591 /* 
592  * Main command loop for SMTP sessions.
593  */
594 void smtp_command_loop(void) {
595         char cmdbuf[256];
596
597         time(&CC->lastcmd);
598         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
599         if (client_gets(cmdbuf) < 1) {
600                 lprintf(3, "SMTP socket is broken.  Ending session.\n");
601                 CC->kill_me = 1;
602                 return;
603         }
604         lprintf(5, "citserver[%3d]: %s\n", CC->cs_pid, cmdbuf);
605         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
606
607         if (SMTP->command_state == smtp_user) {
608                 smtp_get_user(cmdbuf);
609         }
610
611         else if (SMTP->command_state == smtp_password) {
612                 smtp_get_pass(cmdbuf);
613         }
614
615         else if (!strncasecmp(cmdbuf, "AUTH", 4)) {
616                 smtp_auth(&cmdbuf[5]);
617         }
618
619         else if (!strncasecmp(cmdbuf, "DATA", 4)) {
620                 smtp_data();
621         }
622
623         else if (!strncasecmp(cmdbuf, "EHLO", 4)) {
624                 smtp_hello(&cmdbuf[5], 1);
625         }
626
627         else if (!strncasecmp(cmdbuf, "EXPN", 4)) {
628                 smtp_expn(&cmdbuf[5]);
629         }
630
631         else if (!strncasecmp(cmdbuf, "HELO", 4)) {
632                 smtp_hello(&cmdbuf[5], 0);
633         }
634
635         else if (!strncasecmp(cmdbuf, "HELP", 4)) {
636                 smtp_help();
637         }
638
639         else if (!strncasecmp(cmdbuf, "MAIL", 4)) {
640                 smtp_mail(&cmdbuf[5]);
641         }
642
643         else if (!strncasecmp(cmdbuf, "NOOP", 4)) {
644                 cprintf("250 This command successfully did nothing.\r\n");
645         }
646
647         else if (!strncasecmp(cmdbuf, "QUIT", 4)) {
648                 cprintf("221 Goodbye...\r\n");
649                 CC->kill_me = 1;
650                 return;
651                 }
652
653         else if (!strncasecmp(cmdbuf, "RCPT", 4)) {
654                 smtp_rcpt(&cmdbuf[5]);
655         }
656
657         else if (!strncasecmp(cmdbuf, "RSET", 4)) {
658                 smtp_rset();
659         }
660
661         else if (!strncasecmp(cmdbuf, "VRFY", 4)) {
662                 smtp_vrfy(&cmdbuf[5]);
663         }
664
665         else {
666                 cprintf("502 I'm sorry Dave, I'm afraid I can't do that.\r\n");
667         }
668
669 }
670
671
672
673
674 /*****************************************************************************/
675 /*               SMTP CLIENT (OUTBOUND PROCESSING) STUFF                     */
676 /*****************************************************************************/
677
678
679
680 /*
681  * smtp_try()
682  *
683  * Called by smtp_do_procmsg() to attempt delivery to one SMTP host
684  *
685  */
686 void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
687 {
688         char buf[256];
689         int sock = (-1);
690         char mxhosts[1024];
691         int num_mxhosts;
692         int mx;
693         char user[256], node[256], name[256];
694
695         /* Parse out the host portion of the recipient address */
696         process_rfc822_addr(addr, user, node, name);
697         lprintf(9, "Attempting SMTP delivery to <%s> @ <%s> (%s)\n",
698                 user, node, name);
699
700         num_mxhosts = getmx(mxhosts, node);
701         lprintf(9, "Number of MX hosts for <%s> is %d\n", node, num_mxhosts);
702         if (num_mxhosts < 1) {
703                 *status = 5;
704                 sprintf(dsn, "No MX hosts found for <%s>", node);
705                 return;
706         }
707
708         for (mx=0; mx<num_mxhosts; ++mx) {
709                 extract(buf, mxhosts, mx);
710                 lprintf(9, "Trying <%s>\n", buf);
711                 sock = sock_connect(buf, "25", "tcp");
712                 sprintf(dsn, "Could not connect: %s", strerror(errno));
713                 if (sock >= 0) lprintf(9, "Connected!\n");
714                 if (sock < 0) sprintf(dsn, "%s", strerror(errno));
715                 if (sock >= 0) break;
716         }
717
718         if (sock < 0) {
719                 *status = 4;    /* dsn is already filled in */
720                 return;
721         }
722
723         /* Process the SMTP greeting from the server */
724         if (sock_gets(sock, buf) < 0) {
725                 *status = 4;
726                 strcpy(dsn, "Connection broken during SMTP conversation");
727                 sock_close(sock);
728                 return;
729         }
730         lprintf(9, "%s\n", buf);
731         if (buf[0] != '2') {
732                 if (buf[0] == '4') {
733                         *status = 4;
734                         strcpy(dsn, &buf[4]);
735                         sock_close(sock);
736                         return;
737                 }
738                 else {
739                         *status = 5;
740                         strcpy(dsn, &buf[4]);
741                         sock_close(sock);
742                         return;
743                 }
744         }
745
746         /* At this point we know we are talking to a real SMTP server */
747
748         /* Do a HELO command */
749         sprintf(buf, "HELO %s", config.c_fqdn);
750         sock_puts(sock, buf);
751         if (sock_gets(sock, buf) < 0) {
752                 *status = 4;
753                 strcpy(dsn, "Connection broken during SMTP conversation");
754                 sock_close(sock);
755                 return;
756         }
757         lprintf(9, "%s\n", buf);
758         if (buf[0] != '2') {
759                 if (buf[0] == '4') {
760                         *status = 4;
761                         strcpy(dsn, &buf[4]);
762                         sock_close(sock);
763                         return;
764                 }
765                 else {
766                         *status = 5;
767                         strcpy(dsn, &buf[4]);
768                         sock_close(sock);
769                         return;
770                 }
771         }
772
773
774         /* HELO succeeded, now try the MAIL From: command */
775         sprintf(buf, "MAIL From: FIX@uncnsrd.mt-kisco.ny.us"); /* FIX */
776         sock_puts(sock, buf);
777         if (sock_gets(sock, buf) < 0) {
778                 *status = 4;
779                 strcpy(dsn, "Connection broken during SMTP conversation");
780                 sock_close(sock);
781                 return;
782         }
783         lprintf(9, "%s\n", buf);
784         if (buf[0] != '2') {
785                 if (buf[0] == '4') {
786                         *status = 4;
787                         strcpy(dsn, &buf[4]);
788                         sock_close(sock);
789                         return;
790                 }
791                 else {
792                         *status = 5;
793                         strcpy(dsn, &buf[4]);
794                         sock_close(sock);
795                         return;
796                 }
797         }
798
799
800         /* MAIL succeeded, now try the RCPT To: command */
801         sprintf(buf, "RCPT To: %s", addr);
802         sock_puts(sock, buf);
803         if (sock_gets(sock, buf) < 0) {
804                 *status = 4;
805                 strcpy(dsn, "Connection broken during SMTP conversation");
806                 sock_close(sock);
807                 return;
808         }
809         lprintf(9, "%s\n", buf);
810         if (buf[0] != '2') {
811                 if (buf[0] == '4') {
812                         *status = 4;
813                         strcpy(dsn, &buf[4]);
814                         sock_close(sock);
815                         return;
816                 }
817                 else {
818                         *status = 5;
819                         strcpy(dsn, &buf[4]);
820                         sock_close(sock);
821                         return;
822                 }
823         }
824
825
826         /* RCPT succeeded, now try the DATA command */
827         sock_puts(sock, "DATA");
828         if (sock_gets(sock, buf) < 0) {
829                 *status = 4;
830                 strcpy(dsn, "Connection broken during SMTP conversation");
831                 sock_close(sock);
832                 return;
833         }
834         lprintf(9, "%s\n", buf);
835         if (buf[0] != '3') {
836                 if (buf[0] == '4') {
837                         *status = 3;
838                         strcpy(dsn, &buf[4]);
839                         sock_close(sock);
840                         return;
841                 }
842                 else {
843                         *status = 5;
844                         strcpy(dsn, &buf[4]);
845                         sock_close(sock);
846                         return;
847                 }
848         }
849
850         /* If we reach this point, the server is expecting data */
851         CtdlOutputMsg(msgnum, MT_RFC822, 0, 0, NULL, sock, 1);
852         sock_puts(sock, ".");
853         if (sock_gets(sock, buf) < 0) {
854                 *status = 4;
855                 strcpy(dsn, "Connection broken during SMTP conversation");
856                 sock_close(sock);
857                 return;
858         }
859         lprintf(9, "%s\n", buf);
860         if (buf[0] != '2') {
861                 if (buf[0] == '4') {
862                         *status = 4;
863                         strcpy(dsn, &buf[4]);
864                         sock_close(sock);
865                         return;
866                 }
867                 else {
868                         *status = 5;
869                         strcpy(dsn, &buf[4]);
870                         sock_close(sock);
871                         return;
872                 }
873         }
874
875         /* We did it! */
876         strcpy(dsn, &buf[4]);
877         *status = 2;
878
879         sock_puts(sock, "QUIT");
880         sock_gets(sock, buf);
881         lprintf(9, "%s\n", buf);
882         sock_close(sock);
883 }
884
885
886
887
888 /*
889  * smtp_do_procmsg()
890  *
891  * Called by smtp_do_queue() to handle an individual message.
892  */
893 void smtp_do_procmsg(long msgnum) {
894         struct CtdlMessage *msg;
895         char *instr = NULL;
896         char *results = NULL;
897         int i;
898         int lines;
899         int status;
900         char buf[1024];
901         char key[1024];
902         char addr[1024];
903         char dsn[1024];
904         long text_msgid = (-1);
905
906         msg = CtdlFetchMessage(msgnum);
907         if (msg == NULL) {
908                 lprintf(3, "SMTP: tried %ld but no such message!\n", msgnum);
909                 return;
910         }
911
912         instr = strdoop(msg->cm_fields['M']);
913         CtdlFreeMessage(msg);
914
915         /* Strip out the headers amd any other non-instruction line */
916         lines = num_tokens(instr, '\n');
917         for (i=0; i<lines; ++i) {
918                 extract_token(buf, instr, i, '\n');
919                 if (num_tokens(buf, '|') < 2) {
920                         lprintf(9, "removing <%s>\n", buf);
921                         remove_token(instr, i, '\n');
922                         --lines;
923                         --i;
924                 }
925         }
926
927         /* Learn the message ID */
928         lines = num_tokens(instr, '\n');
929         for (i=0; i<lines; ++i) {
930                 extract_token(buf, instr, i, '\n');
931                 extract(key, buf, 0);
932                 if (!strcasecmp(key, "msgid")) {
933                         text_msgid = extract_long(buf, 1);
934                 }
935         }
936
937         if (text_msgid < 0L) {
938                 lprintf(3, "SMTP: no 'msgid' directive found!\n");
939                 phree(instr);
940                 return;
941         }
942
943         /* Plow through the instructions looking for 'remote' directives and
944          * a status of 0 (no delivery yet attempted) or 3 (transient errors
945          * were experienced and it's time to try again)
946          */
947         lines = num_tokens(instr, '\n');
948         for (i=0; i<lines; ++i) {
949                 extract_token(buf, instr, i, '\n');
950                 extract(key, buf, 0);
951                 extract(addr, buf, 1);
952                 status = extract_int(buf, 2);
953                 extract(dsn, buf, 3);
954                 if ( (!strcasecmp(key, "remote"))
955                    && ((status==0)||(status==3)) ) {
956                         remove_token(instr, i, '\n');
957                         --i;
958                         --lines;
959                         lprintf(9, "SMTP: Trying <%s>\n", addr);
960                         smtp_try(key, addr, &status, dsn, text_msgid);
961                         if (status != 2) {
962                                 if (results == NULL) {
963                                         results = mallok(1024);
964                                         memset(results, 0, 1024);
965                                 }
966                                 else {
967                                         results = reallok(results,
968                                                 strlen(results) + 1024);
969                                 }
970                                 sprintf(&results[strlen(results)],
971                                         "%s|%s|%d|%s\n",
972                                         key, addr, status, dsn);
973                         }
974                 }
975         }
976
977         if (results != NULL) {
978                 instr = reallok(instr, strlen(instr) + strlen(results) + 2);
979                 strcat(instr, results);
980                 phree(results);
981         }
982
983         /* Delete the instructions and replace with the updated ones */
984         CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgnum, NULL);    
985         msg = mallok(sizeof(struct CtdlMessage));
986         memset(msg, 0, sizeof(struct CtdlMessage));
987         msg->cm_magic = CTDLMESSAGE_MAGIC;
988         msg->cm_anon_type = MES_NORMAL;
989         msg->cm_format_type = FMT_RFC822;
990         msg->cm_fields['M'] = malloc(strlen(instr)+256);
991         sprintf(msg->cm_fields['M'],
992                 "Content-type: %s\n\n%s\n", SPOOLMIME, instr);
993         phree(instr);
994         CtdlSaveMsg(msg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL, 1);
995         CtdlFreeMessage(msg);
996 }
997
998
999
1000 /*
1001  * smtp_do_queue()
1002  * 
1003  * Run through the queue sending out messages.
1004  */
1005 void smtp_do_queue(void) {
1006         lprintf(5, "SMTP: processing outbound queue\n");
1007
1008         if (getroom(&CC->quickroom, SMTP_SPOOLOUT_ROOM) != 0) {
1009                 lprintf(3, "Cannot find room <%s>\n", SMTP_SPOOLOUT_ROOM);
1010                 return;
1011         }
1012         CtdlForEachMessage(MSGS_ALL, 0L, SPOOLMIME, NULL, smtp_do_procmsg);
1013
1014         lprintf(5, "SMTP: queue run completed\n");
1015 }
1016
1017
1018 /**** FIX  temporary hack to run the queue *****/
1019 void cmd_qqqq(char *argbuf) {
1020         smtp_do_queue();
1021         cprintf("%d ok\n", OK);
1022 }
1023
1024
1025
1026 /*****************************************************************************/
1027 /*                      MODULE INITIALIZATION STUFF                          */
1028 /*****************************************************************************/
1029
1030
1031 char *Dynamic_Module_Init(void)
1032 {
1033         SYM_SMTP = CtdlGetDynamicSymbol();
1034         SYM_SMTP_RECP = CtdlGetDynamicSymbol();
1035         CtdlRegisterServiceHook(SMTP_PORT,
1036                                 smtp_greeting,
1037                                 smtp_command_loop);
1038
1039         /****  FIX ... temporary hack to run the queue ******/
1040         CtdlRegisterProtoHook(cmd_qqqq, "QQQQ", "run the queue");  
1041
1042         create_room(SMTP_SPOOLOUT_ROOM, 3, "", 0);
1043         return "$Id$";
1044 }
1045