]> code.citadel.org Git - citadel.git/blobdiff - citadel/serv_smtp.c
* Changed the comments at the beginning of each file to a consistent format
[citadel.git] / citadel / serv_smtp.c
index 61a5e5ef3476d3423462e9e58813a4be23b9130c..75e9a4ef100e39aa13e8968ef0ace9f8518bcf3b 100644 (file)
@@ -1,4 +1,10 @@
-/* $Id$ */
+/*
+ * $Id$
+ *
+ * An implementation of RFC821 (Simple Mail Transfer Protocol) for the
+ * Citadel system.
+ *
+ */
 
 #include "sysdep.h"
 #include <stdlib.h>
@@ -21,6 +27,7 @@
 #include "citserver.h"
 #include "support.h"
 #include "config.h"
+#include "control.h"
 #include "dynloader.h"
 #include "room_ops.h"
 #include "user_ops.h"
@@ -43,6 +50,7 @@ struct citsmtp {              /* Information about the current session */
        char from[256];
        int number_of_recipients;
        int delivery_mode;
+       int message_originated_locally;
 };
 
 enum {                         /* Command states for login authentication */
@@ -280,10 +288,23 @@ void smtp_expn(char *argbuf) {
  */
 void smtp_rset(void) {
        memset(SMTP, 0, sizeof(struct citsmtp));
+       if (SMTP_RECP != NULL) strcpy(SMTP_RECP, "");
        if (CC->logged_in) logout(CC);
        cprintf("250 Zap!\r\n");
 }
 
+/*
+ * Clear out the portions of the state buffer that need to be cleared out
+ * after the DATA command finishes.
+ */
+void smtp_data_clear(void) {
+       strcpy(SMTP->from, "");
+       SMTP->number_of_recipients = 0;
+       SMTP->delivery_mode = 0;
+       SMTP->message_originated_locally = 0;
+       if (SMTP_RECP != NULL) strcpy(SMTP_RECP, "");
+}
+
 
 
 /*
@@ -324,6 +345,9 @@ void smtp_mail(char *argbuf) {
                        strcpy(SMTP->from, "");
                        return;
                }
+               else {
+                       SMTP->message_originated_locally = 1;
+               }
        }
 
        /* Otherwise, make sure outsiders aren't trying to forge mail from
@@ -340,7 +364,7 @@ void smtp_mail(char *argbuf) {
                }
        }
 
-       cprintf("250 Sender ok.  Groovy.\r\n");
+       cprintf("250 Sender ok\r\n");
 }
 
 
@@ -353,10 +377,9 @@ void smtp_rcpt(char *argbuf) {
        char user[256];
        char node[256];
        char recp[256];
-       int is_spam = 0;        /* FIX implement anti-spamming */
 
        if (strlen(SMTP->from) == 0) {
-               cprintf("503 MAIL first, then RCPT.  Duh.\r\n");
+               cprintf("503 Need MAIL before RCPT\r\n");
                return;
        }
 
@@ -367,11 +390,13 @@ void smtp_rcpt(char *argbuf) {
 
        strcpy(recp, &argbuf[3]);
        striplt(recp);
+       TRACE;
        alias(recp);
+       TRACE;
 
        cvt = convert_internet_address(user, node, recp);
-       sprintf(recp, "%s@%s", user, node);
-
+       snprintf(recp, sizeof recp, "%s@%s", user, node);
+       lprintf(9, "cvt=%d, citaddr=<%s@%s>\n", cvt, user, node);
 
        switch(cvt) {
                case rfc822_address_locally_validated:
@@ -398,9 +423,21 @@ void smtp_rcpt(char *argbuf) {
                        cprintf("550 %s: no such user\r\n", recp);
                        return;
 
-               case rfc822_address_invalid:
-                       if (is_spam) {
-                               cprintf("551 Away with thee, spammer!\r\n");
+               case rfc822_address_on_citadel_network:
+                       cprintf("250 %s is on the local network\r\n", recp);
+                       ++SMTP->number_of_recipients;
+                       CtdlReallocUserData(SYM_SMTP_RECP,
+                               strlen(SMTP_RECP) + 1024 );
+                       strcat(SMTP_RECP, "ignet|");
+                       strcat(SMTP_RECP, user);
+                       strcat(SMTP_RECP, "|");
+                       strcat(SMTP_RECP, node);
+                       strcat(SMTP_RECP, "|0|\n");
+                       return;
+
+               case rfc822_address_nonlocal:
+                       if (SMTP->message_originated_locally == 0) {
+                               cprintf("551 Relaying denied\r\n");
                        }
                        else {
                                cprintf("250 Remote recipient %s ok\r\n", recp);
@@ -420,6 +457,48 @@ void smtp_rcpt(char *argbuf) {
 
 
 
+/*
+ * Send a message out through the local network
+ * (This is kind of ugly.  IGnet should be done using clean server-to-server
+ * code instead of the old style spool.)
+ */
+void smtp_deliver_ignet(struct CtdlMessage *msg, char *user, char *dest) {
+       struct ser_ret smr;
+       char *hold_R, *hold_D, *hold_O;
+       FILE *fp;
+       char filename[256];
+       static int seq = 0;
+
+       lprintf(9, "smtp_deliver_ignet(msg, %s, %s)\n", user, dest);
+
+       hold_R = msg->cm_fields['R'];
+       hold_D = msg->cm_fields['D'];
+       hold_O = msg->cm_fields['O'];
+       msg->cm_fields['R'] = user;
+       msg->cm_fields['D'] = dest;
+       msg->cm_fields['O'] = MAILROOM;
+
+       serialize_message(&smr, msg);
+
+       msg->cm_fields['R'] = hold_R;
+       msg->cm_fields['D'] = hold_D;
+       msg->cm_fields['O'] = hold_O;
+
+       if (smr.len != 0) {
+               snprintf(filename, sizeof filename,
+                       "./network/spoolin/%s.%04x.%04x",
+                       dest, getpid(), ++seq);
+               lprintf(9, "spool file name is <%s>\n", filename);
+               fp = fopen(filename, "wb");
+               if (fp != NULL) {
+                       fwrite(smr.ser, smr.len, 1, fp);
+                       fclose(fp);
+               }
+               phree(smr.ser);
+       }
+
+}
+
 
 
 /*
@@ -449,18 +528,21 @@ int smtp_message_delivery(struct CtdlMessage *msg) {
        if (msg->cm_fields['A']==NULL) msg->cm_fields['A'] = strdoop(user);
        if (msg->cm_fields['N']==NULL) msg->cm_fields['N'] = strdoop(node);
        if (msg->cm_fields['H']==NULL) msg->cm_fields['H'] = strdoop(name);
+       if (msg->cm_fields['O']==NULL) msg->cm_fields['O'] = strdoop(MAILROOM);
 
        /* Save the message in the queue */
        msgid = CtdlSaveMsg(msg,
                "",
                SMTP_SPOOLOUT_ROOM,
-               MES_LOCAL,
-               1);
+               MES_LOCAL);
        ++successful_saves;
 
        instr = mallok(1024);
-       sprintf(instr, "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n",
-               SPOOLMIME, msgid, time(NULL) );
+       snprintf(instr, 1024,
+                       "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
+                       "bounceto|%s\n",
+               SPOOLMIME, msgid, time(NULL),
+               SMTP->from );
 
        for (i=0; i<SMTP->number_of_recipients; ++i) {
                extract_token(buf, SMTP_RECP, i, '\n');
@@ -486,11 +568,19 @@ int smtp_message_delivery(struct CtdlMessage *msg) {
                        ++successful_saves;
                }
 
+               /* Delivery over the local Citadel network (IGnet) */
+               if (!strcasecmp(dtype, "ignet")) {
+                       extract(user, buf, 1);
+                       extract(node, buf, 2);
+                       smtp_deliver_ignet(msg, user, node);
+               }
+
                /* Remote delivery */
                if (!strcasecmp(dtype, "remote")) {
                        extract(user, buf, 1);
                        instr = reallok(instr, strlen(instr) + 1024);
-                       sprintf(&instr[strlen(instr)],
+                       snprintf(&instr[strlen(instr)],
+                               strlen(instr) + 1024,
                                "remote|%s|0\n",
                                user);
                        ++remote_spools;
@@ -506,7 +596,7 @@ int smtp_message_delivery(struct CtdlMessage *msg) {
                imsg->cm_anon_type = MES_NORMAL;
                imsg->cm_format_type = FMT_RFC822;
                imsg->cm_fields['M'] = instr;
-               CtdlSaveMsg(imsg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL, 1);
+               CtdlSaveMsg(imsg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL);
                CtdlFreeMessage(imsg);
        }
 
@@ -514,7 +604,7 @@ int smtp_message_delivery(struct CtdlMessage *msg) {
        else {
                phree(instr);   /* only needed here, because CtdlSaveMsg()
                                 * would free this buffer otherwise */
-               CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgid, NULL); 
+               CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgid, ""); 
        }
 
        return(failed_saves);
@@ -546,7 +636,7 @@ void smtp_data(void) {
        generate_rfc822_datestamp(nowstamp, time(NULL));
        body = mallok(4096);
 
-       if (body != NULL) sprintf(body,
+       if (body != NULL) snprintf(body, 4096,
                "Received: from %s\n"
                "       by %s;\n"
                "       %s\n",
@@ -584,6 +674,8 @@ void smtp_data(void) {
        else {
                cprintf("550 Internal delivery errors: %d\r\n", retval);
        }
+
+       smtp_data_clear();      /* clear out the buffers now */
 }
 
 
@@ -702,6 +794,7 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
 
        /* Parse out the host portion of the recipient address */
        process_rfc822_addr(addr, user, node, name);
+
        lprintf(9, "Attempting SMTP delivery to <%s> @ <%s> (%s)\n",
                user, node, name);
 
@@ -771,7 +864,7 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        lprintf(9, "Number of MX hosts for <%s> is %d\n", node, num_mxhosts);
        if (num_mxhosts < 1) {
                *status = 5;
-               sprintf(dsn, "No MX hosts found for <%s>", node);
+               snprintf(dsn, 256, "No MX hosts found for <%s>", node);
                return;
        }
 
@@ -779,9 +872,9 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
                extract(buf, mxhosts, mx);
                lprintf(9, "Trying <%s>\n", buf);
                sock = sock_connect(buf, "25", "tcp");
-               sprintf(dsn, "Could not connect: %s", strerror(errno));
+               snprintf(dsn, 256, "Could not connect: %s", strerror(errno));
                if (sock >= 0) lprintf(9, "Connected!\n");
-               if (sock < 0) sprintf(dsn, "%s", strerror(errno));
+               if (sock < 0) snprintf(dsn, 256, "%s", strerror(errno));
                if (sock >= 0) break;
        }
 
@@ -791,7 +884,7 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        }
 
        /* Process the SMTP greeting from the server */
-       if (sock_gets(sock, buf) < 0) {
+       if (ml_sock_gets(sock, buf) < 0) {
                *status = 4;
                strcpy(dsn, "Connection broken during SMTP conversation");
                goto bail;
@@ -800,12 +893,12 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        if (buf[0] != '2') {
                if (buf[0] == '4') {
                        *status = 4;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
                else {
                        *status = 5;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
        }
@@ -813,10 +906,10 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        /* At this point we know we are talking to a real SMTP server */
 
        /* Do a HELO command */
-       sprintf(buf, "HELO %s", config.c_fqdn);
+       snprintf(buf, sizeof buf, "HELO %s", config.c_fqdn);
        lprintf(9, ">%s\n", buf);
-       sock_puts(sock, buf);
-       if (sock_gets(sock, buf) < 0) {
+       sock_puts_crlf(sock, buf);
+       if (ml_sock_gets(sock, buf) < 0) {
                *status = 4;
                strcpy(dsn, "Connection broken during SMTP conversation");
                goto bail;
@@ -825,22 +918,22 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        if (buf[0] != '2') {
                if (buf[0] == '4') {
                        *status = 4;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
                else {
                        *status = 5;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
        }
 
 
        /* HELO succeeded, now try the MAIL From: command */
-       sprintf(buf, "MAIL From: %s", mailfrom);
+       snprintf(buf, sizeof buf, "MAIL From: <%s>", mailfrom);
        lprintf(9, ">%s\n", buf);
-       sock_puts(sock, buf);
-       if (sock_gets(sock, buf) < 0) {
+       sock_puts_crlf(sock, buf);
+       if (ml_sock_gets(sock, buf) < 0) {
                *status = 4;
                strcpy(dsn, "Connection broken during SMTP conversation");
                goto bail;
@@ -849,22 +942,22 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        if (buf[0] != '2') {
                if (buf[0] == '4') {
                        *status = 4;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
                else {
                        *status = 5;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
        }
 
 
        /* MAIL succeeded, now try the RCPT To: command */
-       sprintf(buf, "RCPT To: %s", addr);
+       snprintf(buf, sizeof buf, "RCPT To: <%s>", addr);
        lprintf(9, ">%s\n", buf);
-       sock_puts(sock, buf);
-       if (sock_gets(sock, buf) < 0) {
+       sock_puts_crlf(sock, buf);
+       if (ml_sock_gets(sock, buf) < 0) {
                *status = 4;
                strcpy(dsn, "Connection broken during SMTP conversation");
                goto bail;
@@ -873,12 +966,12 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        if (buf[0] != '2') {
                if (buf[0] == '4') {
                        *status = 4;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
                else {
                        *status = 5;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
        }
@@ -886,8 +979,8 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
 
        /* RCPT succeeded, now try the DATA command */
        lprintf(9, ">DATA\n");
-       sock_puts(sock, "DATA");
-       if (sock_gets(sock, buf) < 0) {
+       sock_puts_crlf(sock, "DATA");
+       if (ml_sock_gets(sock, buf) < 0) {
                *status = 4;
                strcpy(dsn, "Connection broken during SMTP conversation");
                goto bail;
@@ -896,12 +989,12 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        if (buf[0] != '3') {
                if (buf[0] == '4') {
                        *status = 3;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
                else {
                        *status = 5;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
        }
@@ -922,7 +1015,7 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        }
 
        sock_write(sock, ".\r\n", 3);
-       if (sock_gets(sock, buf) < 0) {
+       if (ml_sock_gets(sock, buf) < 0) {
                *status = 4;
                strcpy(dsn, "Connection broken during SMTP conversation");
                goto bail;
@@ -931,23 +1024,23 @@ void smtp_try(char *key, char *addr, int *status, char *dsn, long msgnum)
        if (buf[0] != '2') {
                if (buf[0] == '4') {
                        *status = 4;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
                else {
                        *status = 5;
-                       strcpy(dsn, &buf[4]);
+                       safestrncpy(dsn, &buf[4], 1023);
                        goto bail;
                }
        }
 
        /* We did it! */
-       strcpy(dsn, &buf[4]);
+       safestrncpy(dsn, &buf[4], 1023);
        *status = 2;
 
        lprintf(9, ">QUIT\n");
-       sock_puts(sock, "QUIT");
-       sock_gets(sock, buf);
+       sock_puts_crlf(sock, "QUIT");
+       ml_sock_gets(sock, buf);
        lprintf(9, "<%s\n", buf);
 
 bail:  if (msg_fp != NULL) fclose(msg_fp);
@@ -958,8 +1051,158 @@ bail:    if (msg_fp != NULL) fclose(msg_fp);
 
 
 /*
- * smtp_purge_completed_deliveries() is caled by smtp_do_procmsg() to remove
- * all of the completed deliveries from a set of delivery instructions.
+ * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
+ * instructions for "5" codes (permanent fatal errors) and produce/deliver
+ * a "bounce" message (delivery status notification).
+ */
+void smtp_do_bounce(char *instr) {
+       int i;
+       int lines;
+       int status;
+       char buf[1024];
+       char key[1024];
+       char addr[1024];
+       char dsn[1024];
+       char bounceto[1024];
+       int num_bounces = 0;
+       int bounce_this = 0;
+       long bounce_msgid = (-1);
+       time_t submitted = 0L;
+       struct CtdlMessage *bmsg = NULL;
+       int give_up = 0;
+       int mes_type = 0;
+
+       lprintf(9, "smtp_do_bounce() called\n");
+       strcpy(bounceto, "");
+
+       lines = num_tokens(instr, '\n');
+
+
+       /* See if it's time to give up on delivery of this message */
+       for (i=0; i<lines; ++i) {
+               extract_token(buf, instr, i, '\n');
+               extract(key, buf, 0);
+               extract(addr, buf, 1);
+               if (!strcasecmp(key, "submitted")) {
+                       submitted = atol(addr);
+               }
+       }
+
+       if ( (time(NULL) - submitted) > SMTP_GIVE_UP ) {
+               give_up = 1;
+       }
+
+
+
+       bmsg = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
+       if (bmsg == NULL) return;
+       memset(bmsg, 0, sizeof(struct CtdlMessage));
+
+        bmsg->cm_magic = CTDLMESSAGE_MAGIC;
+        bmsg->cm_anon_type = MES_NORMAL;
+        bmsg->cm_format_type = 1;
+        bmsg->cm_fields['A'] = strdoop("Citadel");
+        bmsg->cm_fields['O'] = strdoop(MAILROOM);
+        bmsg->cm_fields['N'] = strdoop(config.c_nodename);
+
+       if (give_up) bmsg->cm_fields['M'] = strdoop(
+"A message you sent could not be delivered to some or all of its recipients\n"
+"due to prolonged unavailability of its destination(s).\n"
+"Giving up on the following addresses:\n\n"
+);
+
+        else bmsg->cm_fields['M'] = strdoop(
+"A message you sent could not be delivered to some or all of its recipients.\n"
+"The following addresses were undeliverable:\n\n"
+);
+
+       /*
+        * Now go through the instructions checking for stuff.
+        */
+
+       for (i=0; i<lines; ++i) {
+               extract_token(buf, instr, i, '\n');
+               extract(key, buf, 0);
+               extract(addr, buf, 1);
+               status = extract_int(buf, 2);
+               extract(dsn, buf, 3);
+               bounce_this = 0;
+
+               lprintf(9, "key=<%s> addr=<%s> status=%d dsn=<%s>\n",
+                       key, addr, status, dsn);
+
+               if (!strcasecmp(key, "bounceto")) {
+                       strcpy(bounceto, addr);
+               }
+
+               if (
+                  (!strcasecmp(key, "local"))
+                  || (!strcasecmp(key, "remote"))
+                  || (!strcasecmp(key, "ignet"))
+                  || (!strcasecmp(key, "room"))
+               ) {
+                       if (status == 5) bounce_this = 1;
+                       if (give_up) bounce_this = 1;
+               }
+
+               if (bounce_this) {
+                       ++num_bounces;
+
+                       if (bmsg->cm_fields['M'] == NULL) {
+                               lprintf(2, "ERROR ... M field is null "
+                                       "(%s:%d)\n", __FILE__, __LINE__);
+                       }
+
+                       bmsg->cm_fields['M'] = reallok(bmsg->cm_fields['M'],
+                               strlen(bmsg->cm_fields['M']) + 1024 );
+                       strcat(bmsg->cm_fields['M'], addr);
+                       strcat(bmsg->cm_fields['M'], ": ");
+                       strcat(bmsg->cm_fields['M'], dsn);
+                       strcat(bmsg->cm_fields['M'], "\n");
+
+                       remove_token(instr, i, '\n');
+                       --i;
+                       --lines;
+               }
+       }
+
+       /* Deliver the bounce if there's anything worth mentioning */
+       lprintf(9, "num_bounces = %d\n", num_bounces);
+       if (num_bounces > 0) {
+
+               /* First try the user who sent the message */
+               lprintf(9, "bounce to user? <%s>\n", bounceto);
+               TRACE;
+               if (strlen(bounceto) == 0) {
+                       lprintf(7, "No bounce address specified\n");
+                       bounce_msgid = (-1L);
+               }
+               else if (mes_type = alias(bounceto), mes_type == MES_ERROR) {
+                       lprintf(7, "Invalid bounce address <%s>\n", bounceto);
+                       bounce_msgid = (-1L);
+               }
+               else {
+                       bounce_msgid = CtdlSaveMsg(bmsg,
+                               bounceto,
+                               "", mes_type);
+               }
+               TRACE;
+
+               /* Otherwise, go to the Aide> room */
+               lprintf(9, "bounce to room?\n");
+               if (bounce_msgid < 0L) bounce_msgid = CtdlSaveMsg(bmsg,
+                       "", AIDEROOM,
+                       MES_LOCAL);
+       }
+
+       CtdlFreeMessage(bmsg);
+       lprintf(9, "Done processing bounces\n");
+}
+
+
+/*
+ * smtp_purge_completed_deliveries() is caled by smtp_do_procmsg() to scan a
+ * set of delivery instructions for completed deliveries and remove them.
  *
  * It returns the number of incomplete deliveries remaining.
  */
@@ -1023,6 +1266,9 @@ void smtp_do_procmsg(long msgnum) {
        char dsn[1024];
        long text_msgid = (-1);
        int incomplete_deliveries_remaining;
+       time_t attempted = 0L;
+       time_t last_attempted = 0L;
+       time_t retry = SMTP_RETRY_INTERVAL;
 
        msg = CtdlFetchMessage(msgnum);
        if (msg == NULL) {
@@ -1045,7 +1291,7 @@ void smtp_do_procmsg(long msgnum) {
                }
        }
 
-       /* Learn the message ID */
+       /* Learn the message ID and find out about recent delivery attempts */
        lines = num_tokens(instr, '\n');
        for (i=0; i<lines; ++i) {
                extract_token(buf, instr, i, '\n');
@@ -1053,8 +1299,32 @@ void smtp_do_procmsg(long msgnum) {
                if (!strcasecmp(key, "msgid")) {
                        text_msgid = extract_long(buf, 1);
                }
+               if (!strcasecmp(key, "retry")) {
+                       /* double the retry interval after each attempt */
+                       retry = extract_long(buf, 1) * 2L;
+                       remove_token(instr, i, '\n');
+               }
+               if (!strcasecmp(key, "attempted")) {
+                       attempted = extract_long(buf, 1);
+                       if (attempted > last_attempted)
+                               last_attempted = attempted;
+               }
        }
 
+
+       /*
+        * Postpone delivery if we've already tried recently.
+        */
+       if ( (time(NULL) - last_attempted) < retry) {
+               lprintf(7, "Retry time not yet reached.\n");
+               phree(instr);
+               return;
+       }
+
+
+       /*
+        * Bail out if there's no actual message associated with this
+        */
        if (text_msgid < 0L) {
                lprintf(3, "SMTP: no 'msgid' directive found!\n");
                phree(instr);
@@ -1102,10 +1372,10 @@ void smtp_do_procmsg(long msgnum) {
        }
 
 
+       /* Generate 'bounce' messages */
+       smtp_do_bounce(instr);
 
-       /*
-        * Go through the delivery list, deleting completed deliveries
-        */
+       /* Go through the delivery list, deleting completed deliveries */
        incomplete_deliveries_remaining = 
                smtp_purge_completed_deliveries(instr);
 
@@ -1114,9 +1384,9 @@ void smtp_do_procmsg(long msgnum) {
         * No delivery instructions remain, so delete both the instructions
         * message and the message message.
         */
-       if (incomplete_deliveries_remaining <= 0)  {
-               CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgnum, NULL);    
-               CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, text_msgid, NULL);    
+       if (incomplete_deliveries_remaining <= 0) {
+               CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgnum, "");
+               CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, text_msgid, "");
        }
 
 
@@ -1125,17 +1395,21 @@ void smtp_do_procmsg(long msgnum) {
         * instructions and replace with the updated ones.
         */
        if (incomplete_deliveries_remaining > 0) {
-               CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgnum, NULL);    
+               CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, msgnum, "");
                msg = mallok(sizeof(struct CtdlMessage));
                memset(msg, 0, sizeof(struct CtdlMessage));
                msg->cm_magic = CTDLMESSAGE_MAGIC;
                msg->cm_anon_type = MES_NORMAL;
                msg->cm_format_type = FMT_RFC822;
                msg->cm_fields['M'] = malloc(strlen(instr)+256);
-               sprintf(msg->cm_fields['M'],
-                       "Content-type: %s\n\n%s\n", SPOOLMIME, instr);
+               snprintf(msg->cm_fields['M'],
+                       strlen(instr)+256,
+                       "Content-type: %s\n\n%s\n"
+                       "attempted|%ld\n"
+                       "retry|%ld\n",
+                       SPOOLMIME, instr, time(NULL), retry );
                phree(instr);
-               CtdlSaveMsg(msg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL, 1);
+               CtdlSaveMsg(msg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL);
                CtdlFreeMessage(msg);
        }
 
@@ -1149,15 +1423,31 @@ void smtp_do_procmsg(long msgnum) {
  * Run through the queue sending out messages.
  */
 void smtp_do_queue(void) {
-       lprintf(5, "SMTP: processing outbound queue\n");
+       static int doing_queue = 0;
+
+       /*
+        * This is a simple concurrency check to make sure only one queue run
+        * is done at a time.  We could do this with a mutex, but since we
+        * don't really require extremely fine granularity here, we'll do it
+        * with a static variable instead.
+        */
+       if (doing_queue) return;
+       doing_queue = 1;
+
+       /* 
+        * Go ahead and run the queue
+        */
+       lprintf(7, "SMTP: processing outbound queue\n");
 
        if (getroom(&CC->quickroom, SMTP_SPOOLOUT_ROOM) != 0) {
                lprintf(3, "Cannot find room <%s>\n", SMTP_SPOOLOUT_ROOM);
                return;
        }
-       CtdlForEachMessage(MSGS_ALL, 0L, SPOOLMIME, NULL, smtp_do_procmsg);
+       CtdlForEachMessage(MSGS_ALL, 0L, (-127),
+               SPOOLMIME, NULL, smtp_do_procmsg);
 
-       lprintf(5, "SMTP: queue run completed\n");
+       lprintf(7, "SMTP: queue run completed\n");
+       doing_queue = 0;
 }
 
 
@@ -1171,11 +1461,18 @@ char *Dynamic_Module_Init(void)
 {
        SYM_SMTP = CtdlGetDynamicSymbol();
        SYM_SMTP_RECP = CtdlGetDynamicSymbol();
-       CtdlRegisterServiceHook(SMTP_PORT,
+
+       CtdlRegisterServiceHook(config.c_smtp_port,     /* On the net... */
+                               NULL,
                                smtp_greeting,
                                smtp_command_loop);
+
+       CtdlRegisterServiceHook(0,                      /* ...and locally */
+                               "smtp.socket",
+                               smtp_greeting,
+                               smtp_command_loop);
+
        create_room(SMTP_SPOOLOUT_ROOM, 3, "", 0);
        CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER);
        return "$Id$";
 }
-