]> code.citadel.org Git - citadel.git/blobdiff - citadel/modules/smtp/serv_smtpqueue.c
fix removal from Queu
[citadel.git] / citadel / modules / smtp / serv_smtpqueue.c
index a05d2f26b592b91a9b752b1465028669cc1dfab4..5f22ee6fbd2bfc3088b24fc3ada8b7bd4521facb 100644 (file)
 
 #include "ctdl_module.h"
 
-#include "smtp_util.h"
 #include "smtpqueue.h"
 #include "event_client.h"
 
-HashList *QItemHandlers = NULL;
 
-citthread_mutex_t ActiveQItemsLock;
-HashList *ActiveQItems = NULL;
+struct CitContext smtp_queue_CC;
+pthread_mutex_t ActiveQItemsLock;
+HashList *ActiveQItems  = NULL;
+HashList *QItemHandlers = NULL;
 
-int MsgCount = 0;
-int run_queue_now = 0; /* Set to 1 to ignore SMTP send retry times */
+int MsgCount            = 0;
+int run_queue_now       = 0;   /* Set to 1 to ignore SMTP send retry times */
 
-void smtp_try(OneQueItem *MyQItem, 
-             MailQEntry *MyQEntry, 
-             StrBuf *MsgText, 
-             int KeepMsgText, /* KeepMsgText allows us to use MsgText as ours. */
-             int MsgCount);
+void smtp_try_one_queue_entry(OneQueItem *MyQItem, 
+                             MailQEntry *MyQEntry, 
+                             StrBuf *MsgText, 
+                             int KeepMsgText, /* KeepMsgText allows us to use MsgText as ours. */
+                             int MsgCount, 
+                             ParsedURL *RelayUrls);
 
 
 void smtp_evq_cleanup(void)
 {
-       citthread_mutex_lock(&ActiveQItemsLock);
+
+       pthread_mutex_lock(&ActiveQItemsLock);
        DeleteHash(&QItemHandlers);
        DeleteHash(&ActiveQItems);
-       citthread_mutex_unlock(&ActiveQItemsLock);
-       citthread_mutex_destroy(&ActiveQItemsLock);
+       pthread_mutex_unlock(&ActiveQItemsLock);
+       pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
+/*     citthread_mutex_destroy(&ActiveQItemsLock); TODO */
 }
 
 int DecreaseQReference(OneQueItem *MyQItem)
 {
        int IDestructQueItem;
 
-       citthread_mutex_lock(&ActiveQItemsLock);
+       pthread_mutex_lock(&ActiveQItemsLock);
        MyQItem->ActiveDeliveries--;
        IDestructQueItem = MyQItem->ActiveDeliveries == 0;
-       citthread_mutex_unlock(&ActiveQItemsLock);
+       pthread_mutex_unlock(&ActiveQItemsLock);
        return IDestructQueItem;
 }
 
 void RemoveQItem(OneQueItem *MyQItem)
 {
+       long len;
+       const char* Key;
+       void *VData;
        HashPos  *It;
 
-       It = GetNewHashPos(MyQItem->MailQEntries, 0);
-       citthread_mutex_lock(&ActiveQItemsLock);
-       {
-               GetHashPosFromKey(ActiveQItems, IKEY(MyQItem->MessageID), It);
+       pthread_mutex_lock(&ActiveQItemsLock);
+       It = GetNewHashPos(ActiveQItems, 0);
+       if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
                DeleteEntryFromHash(ActiveQItems, It);
+       else
+       {
+               syslog(LOG_WARNING, 
+                      "SMTP cleanup: unable to find QItem with ID[%ld]",
+                      MyQItem->MessageID);
+               while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
+                       syslog(LOG_WARNING, 
+                              "SMTP cleanup: have_: ID[%ld]",
+                              ((OneQueItem *)VData)->MessageID);                               
        }
-       citthread_mutex_unlock(&ActiveQItemsLock);
+       pthread_mutex_unlock(&ActiveQItemsLock);
        DeleteHashPos(&It);
 }
 
 
-
 void FreeMailQEntry(void *qv)
 {
        MailQEntry *Q = qv;
@@ -152,6 +165,7 @@ void FreeQueItem(OneQueItem **Item)
        DeleteHash(&(*Item)->MailQEntries);
        FreeStrBuf(&(*Item)->EnvelopeFrom);
        FreeStrBuf(&(*Item)->BounceTo);
+       FreeURL(&(*Item)->URL);
        free(*Item);
        Item = NULL;
 }
@@ -205,25 +219,6 @@ OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
        Item->MessageID = -1;
        Item->QueMsgID = QueMsgID;
 
-       citthread_mutex_lock(&ActiveQItemsLock);
-       if (GetHash(ActiveQItems, 
-                   IKEY(Item->QueMsgID), 
-                   &v))
-       {
-               /* WHOOPS. somebody else is already working on this. */
-               citthread_mutex_unlock(&ActiveQItemsLock);
-               FreeQueItem(&Item);
-               return NULL;
-       }
-       else {
-               /* mark our claim on this. */
-               Put(ActiveQItems, 
-                   IKEY(Item->QueMsgID),
-                   Item,
-                   HFreeQueItem);
-               citthread_mutex_unlock(&ActiveQItemsLock);
-       }
-
        Token = NewStrBuf();
        Line = NewStrBufPlain(NULL, 128);
        while (pLine != StrBufNOTNULL) {
@@ -242,6 +237,26 @@ OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
        }
        FreeStrBuf(&Line);
        FreeStrBuf(&Token);
+
+       pthread_mutex_lock(&ActiveQItemsLock);
+       if (GetHash(ActiveQItems, 
+                   LKEY(Item->MessageID),
+                   &v))
+       {
+               /* WHOOPS. somebody else is already working on this. */
+               pthread_mutex_unlock(&ActiveQItemsLock);
+               FreeQueItem(&Item);
+               return NULL;
+       }
+       else {
+               /* mark our claim on this. */
+               Put(ActiveQItems, 
+                   LKEY(Item->MessageID),
+                   Item,
+                   HFreeQueItem);
+               pthread_mutex_unlock(&ActiveQItemsLock);
+       }
+
        return Item;
 }
 
@@ -260,6 +275,9 @@ StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
        StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
        StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
 
+       StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
+       StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
+
        if (StrLength(MyQItem->BounceTo) > 0) {
                StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
                StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
@@ -280,6 +298,7 @@ StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
                        continue; /* skip already sent ones from the spoolfile. */
 
                for (i=0; i < ThisItem->nAttempts; i++) {
+                       /* TODO: most probably there is just one retry/attempted per message! */
                        StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
                        StrBufAppendPrintf(QMessage, "%ld", 
                                           ThisItem->Attempts[i].retry);
@@ -311,13 +330,14 @@ void NewMailQEntry(OneQueItem *Item)
 
        if (Item->MailQEntries == NULL)
                Item->MailQEntries = NewHash(1, Flathash);
+       Item->Current->StatusMessage = NewStrBuf();
        Item->Current->n = GetCount(Item->MailQEntries);
        Put(Item->MailQEntries, IKEY(Item->Current->n), Item->Current, FreeMailQEntry);
 }
 
 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
 {
-       Item->MessageID = StrBufExtractNext_int(Line, Pos, '|');
+       Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
 }
 
 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
@@ -360,6 +380,13 @@ void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
        Item->Current->Attempts[Item->Current->nAttempts].retry = StrBufExtractNext_int(Line, Pos, '|');
 }
 
+
+void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
+{
+       Item->Submitted = atol(*Pos);
+
+}
+
 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
 {
        if (Item->Current == NULL)
@@ -397,11 +424,11 @@ StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
        CCC->redirect_buffer = NULL;
        if ((StrLength(SendMsg) > 0) && 
            ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
-               CtdlLogPrintf(CTDL_WARNING, 
-                             "SMTP client[%ld]: Possible problem: message did not "
-                             "correctly terminate. (expecting 0x10, got 0x%02x)\n",
-                             MsgCount, //yes uncool, but best choice here... 
-                             ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
+               syslog(LOG_WARNING, 
+                      "SMTP client[%d]: Possible problem: message did not "
+                      "correctly terminate. (expecting 0x10, got 0x%02x)\n",
+                      MsgCount, //yes uncool, but best choice here... 
+                      ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
                StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
        }
        return SendMsg;
@@ -409,6 +436,183 @@ StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
 
 
 
+/*
+ * 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 smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt) 
+{
+       static int seq = 0;
+
+       struct CtdlMessage *bmsg = NULL;
+       StrBuf *boundary;
+       StrBuf *Msg = NULL; 
+       StrBuf *BounceMB;
+       struct recptypes *valid;
+       
+       HashPos *It;
+       void *vQE;
+       long len;
+       const char *Key;
+
+       int successful_bounce = 0;
+       int num_bounces = 0;
+       int give_up = 0;
+
+       syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
+
+       if ( (ev_time() - MyQItem->Submitted) > SMTP_GIVE_UP ) {
+               give_up = 1;/// TODO: replace time by libevq timer get
+       }
+
+       /*
+        * Now go through the instructions checking for stuff.
+        */
+       It = GetNewHashPos(MyQItem->MailQEntries, 0);
+       while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
+       {
+               MailQEntry *ThisItem = vQE;
+               if ((ThisItem->Status == 5) || /* failed now? */
+                   ((give_up == 1) && (ThisItem->Status != 2))) /* giving up after failed attempts... */
+               {
+                       if (num_bounces == 0)
+                               Msg = NewStrBufPlain(NULL, 1024);
+                       ++num_bounces;
+       
+                       StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
+                       StrBufAppendBufPlain(Msg, HKEY(": "), 0);
+                       StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
+                       StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
+               }
+       }
+       DeleteHashPos(&It);
+
+       /* Deliver the bounce if there's anything worth mentioning */
+       syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
+
+       if (num_bounces == 0) {
+               FreeStrBuf(&Msg);
+               return;
+       }
+
+       boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
+       StrBufAppendPrintf(boundary, "%s_%04x%04x", config.c_fqdn, getpid(), ++seq);
+
+       /* Start building our bounce message; go shopping for memory first. */
+       BounceMB = NewStrBufPlain(NULL, 
+                                 1024 + /* mime stuff.... */
+                                 StrLength(Msg) +  /* the bounce information... */
+                                 StrLength(OMsgTxt)); /* the original message */
+       if (BounceMB == NULL) {
+               FreeStrBuf(&boundary);
+               syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
+
+               return;
+       }
+
+       bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
+       if (bmsg == NULL) {
+               FreeStrBuf(&boundary);
+               FreeStrBuf(&BounceMB);
+               syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
+
+               return;
+       }
+       memset(bmsg, 0, sizeof(struct CtdlMessage));
+
+
+       StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
+       StrBufAppendBuf(BounceMB, boundary, 0);
+        StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
+        StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
+        StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
+        StrBufAppendBuf(BounceMB, boundary, 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
+        StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
+
+       if (give_up) 
+               StrBufAppendBufPlain(
+                       BounceMB, 
+                       HKEY(
+                               "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"
+                               ), 0);
+       else 
+               StrBufAppendBufPlain(
+                       BounceMB, 
+                       HKEY(
+                               "A message you sent could not be delivered to some or all of its recipients.\n"
+                               "The following addresses were undeliverable:\n\n"
+                               ), 0);
+
+       StrBufAppendBuf(BounceMB, Msg, 0);
+       FreeStrBuf(&Msg);
+
+       /* Attach the original message */
+       StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
+       StrBufAppendBuf(BounceMB, boundary, 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("Content-type: message/rfc822\r\n"), 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("Content-Disposition: inline\r\n"), 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
+       StrBufAppendBuf(BounceMB, OMsgTxt, 0);
+
+       /* Close the multipart MIME scope */
+        StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
+       StrBufAppendBuf(BounceMB, boundary, 0);
+       StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
+
+
+
+        bmsg->cm_magic = CTDLMESSAGE_MAGIC;
+        bmsg->cm_anon_type = MES_NORMAL;
+        bmsg->cm_format_type = FMT_RFC822;
+
+        bmsg->cm_fields['O'] = strdup(MAILROOM);
+        bmsg->cm_fields['A'] = strdup("Citadel");
+        bmsg->cm_fields['N'] = strdup(config.c_nodename);
+        bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
+       bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
+
+       /* First try the user who sent the message */
+       if (StrLength(MyQItem->BounceTo) == 0) 
+               syslog(LOG_ERR, "No bounce address specified\n");
+       else
+               syslog(LOG_DEBUG, "bounce to user? <%s>\n", ChrPtr(MyQItem->BounceTo));
+
+       /* Can we deliver the bounce to the original sender? */
+       valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
+       if ((valid != NULL) && (valid->num_error == 0)) {
+               CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
+               successful_bounce = 1;
+       }
+
+       /* If not, post it in the Aide> room */
+       if (successful_bounce == 0) {
+               CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
+       }
+
+       /* Free up the memory we used */
+       free_recipients(valid);
+       FreeStrBuf(&boundary);
+       CtdlFreeMessage(bmsg);
+       syslog(LOG_DEBUG, "Done processing bounces\n");
+}
+
+
+
+/*
+{
+
+       if (threadding)
+               n_smarthosts =  get_hosts(char *mxbuf, char *rectype);
+}
+*/
 /*
  * smtp_do_procmsg()
  *
@@ -424,13 +628,17 @@ void smtp_do_procmsg(long msgnum, void *userdata) {
        void *vQE;
        long len;
        const char *Key;
-
-       CtdlLogPrintf(CTDL_DEBUG, "SMTP Queue: smtp_do_procmsg(%ld)\n", msgnum);
+       int nRelays = 0;
+       ParsedURL *RelayUrls = NULL;
+       int HaveBuffers = 0;
+       StrBuf *Msg =NULL;
+       
+       syslog(LOG_DEBUG, "SMTP Queue: smtp_do_procmsg(%ld)\n", msgnum);
        ///strcpy(envelope_from, "");
 
        msg = CtdlFetchMessage(msgnum, 1);
        if (msg == NULL) {
-               CtdlLogPrintf(CTDL_ERR, "SMTP Queue: tried %ld but no such message!\n", msgnum);
+               syslog(LOG_ERR, "SMTP Queue: tried %ld but no such message!\n", msgnum);
                return;
        }
 
@@ -450,7 +658,7 @@ void smtp_do_procmsg(long msgnum, void *userdata) {
        FreeStrBuf(&PlainQItem);
 
        if (MyQItem == NULL) {
-               CtdlLogPrintf(CTDL_ERR, "SMTP Queue: Msg No %ld: already in progress!\n", msgnum);              
+               syslog(LOG_ERR, "SMTP Queue: Msg No %ld: already in progress!\n", msgnum);              
                return; /* s.b. else is already processing... */
        }
 
@@ -458,15 +666,15 @@ void smtp_do_procmsg(long msgnum, void *userdata) {
         * Postpone delivery if we've already tried recently.
         * /
        if (((time(NULL) - MyQItem->LastAttempt.when) < MyQItem->LastAttempt.retry) && (run_queue_now == 0)) {
-               CtdlLogPrintf(CTDL_DEBUG, "SMTP client: Retry time not yet reached.\n");
+               syslog(LOG_DEBUG, "SMTP client: Retry time not yet reached.\n");
 
                It = GetNewHashPos(MyQItem->MailQEntries, 0);
-               citthread_mutex_lock(&ActiveQItemsLock);
+               pthread_mutex_lock(&ActiveQItemsLock);
                {
-                       GetHashPosFromKey(ActiveQItems, IKEY(MyQItem->MessageID), It);
+                       GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It);
                        DeleteEntryFromHash(ActiveQItems, It);
                }
-               citthread_mutex_unlock(&ActiveQItemsLock);
+               pthread_mutex_unlock(&ActiveQItemsLock);
                ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
                DeleteHashPos(&It);
                return;
@@ -476,24 +684,70 @@ void smtp_do_procmsg(long msgnum, void *userdata) {
         * Bail out if there's no actual message associated with this
         */
        if (MyQItem->MessageID < 0L) {
-               CtdlLogPrintf(CTDL_ERR, "SMTP Queue: no 'msgid' directive found!\n");
+               syslog(LOG_ERR, "SMTP Queue: no 'msgid' directive found!\n");
                It = GetNewHashPos(MyQItem->MailQEntries, 0);
-               citthread_mutex_lock(&ActiveQItemsLock);
+               pthread_mutex_lock(&ActiveQItemsLock);
                {
-                       GetHashPosFromKey(ActiveQItems, IKEY(MyQItem->MessageID), It);
+                       GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It);
                        DeleteEntryFromHash(ActiveQItems, It);
                }
-               citthread_mutex_unlock(&ActiveQItemsLock);
+               pthread_mutex_unlock(&ActiveQItemsLock);
                DeleteHashPos(&It);
                ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
                return;
        }
 
+       {
+               char mxbuf[SIZ];
+               ParsedURL **Url = &MyQItem->URL;
+               nRelays = get_hosts(mxbuf, "smarthost");
+               if (nRelays > 0) {
+                       StrBuf *All;
+                       StrBuf *One;
+                       const char *Pos = NULL;
+                       All = NewStrBufPlain(mxbuf, -1);
+                       One = NewStrBufPlain(NULL, StrLength(All) + 1);
+                       
+                       while ((Pos != StrBufNOTNULL) && ((Pos == NULL) || !IsEmptyStr(Pos))) {
+                               StrBufExtract_NextToken(One, All, &Pos, '|');
+                               if (!ParseURL(Url, One, 25))
+                                       syslog(LOG_DEBUG, "Failed to parse: %s\n", ChrPtr(One));
+                               else {
+                                       ///if (!Url->IsIP)) /// todo dupe me fork ipv6
+                                       Url = &(*Url)->Next;
+                                       
+                               }
+                       }
+                       FreeStrBuf(&All);
+                       FreeStrBuf(&One);
+               }
+
+               Url = &MyQItem->FallBackHost;
+               nRelays = get_hosts(mxbuf, "fallbackhost");
+               if (nRelays > 0) {
+                       StrBuf *All;
+                       StrBuf *One;
+                       const char *Pos = NULL;
+                       All = NewStrBufPlain(mxbuf, -1);
+                       One = NewStrBufPlain(NULL, StrLength(All) + 1);
+                       
+                       while ((Pos != StrBufNOTNULL) && ((Pos == NULL) || !IsEmptyStr(Pos))) {
+                               StrBufExtract_NextToken(One, All, &Pos, '|');
+                               if (!ParseURL(Url, One, 25))
+                                       syslog(LOG_DEBUG, "Failed to parse: %s\n", ChrPtr(One));
+                               else 
+                                       Url = &(*Url)->Next;
+                       }
+                       FreeStrBuf(&All);
+                       FreeStrBuf(&One);
+               }
+       }
+
        It = GetNewHashPos(MyQItem->MailQEntries, 0);
        while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
        {
                MailQEntry *ThisItem = vQE;
-               CtdlLogPrintf(CTDL_DEBUG, "SMTP Queue: Task: <%s> %d\n", ChrPtr(ThisItem->Recipient), ThisItem->Active);
+               syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n", ChrPtr(ThisItem->Recipient), ThisItem->Active);
        }
        DeleteHashPos(&It);
 
@@ -501,17 +755,30 @@ void smtp_do_procmsg(long msgnum, void *userdata) {
        if (MyQItem->ActiveDeliveries > 0)
        {
                int n = MsgCount++;
+               int m = MyQItem->ActiveDeliveries;
                int i = 1;
-               StrBuf *Msg = smtp_load_msg(MyQItem, n);
+               Msg = smtp_load_msg(MyQItem, n);
                It = GetNewHashPos(MyQItem->MailQEntries, 0);
-               while ((i <= MyQItem->ActiveDeliveries) && 
+               while ((i <= m) && 
                       (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE)))
                {
                        MailQEntry *ThisItem = vQE;
                        if (ThisItem->Active == 1) {
+                               int KeepBuffers = (i == m);
                                if (i > 1) n = MsgCount++;
-                               CtdlLogPrintf(CTDL_DEBUG, "SMTP Queue: Trying <%s>\n", ChrPtr(ThisItem->Recipient));
-                               smtp_try(MyQItem, ThisItem, Msg, (i == MyQItem->ActiveDeliveries), n);
+                               syslog(LOG_DEBUG, 
+                                      "SMTP Queue: Trying <%ld> <%s> %d / %d \n", 
+                                      MyQItem->MessageID,
+                                      ChrPtr(ThisItem->Recipient), 
+                                      i, 
+                                      m);
+                               smtp_try_one_queue_entry(MyQItem, 
+                                                        ThisItem, 
+                                                        Msg, 
+                                                        KeepBuffers, 
+                                                        n, 
+                                                        RelayUrls);
+                               if (KeepBuffers) HaveBuffers = 1;
                                i++;
                        }
                }
@@ -520,18 +787,36 @@ void smtp_do_procmsg(long msgnum, void *userdata) {
        else 
        {
                It = GetNewHashPos(MyQItem->MailQEntries, 0);
-               citthread_mutex_lock(&ActiveQItemsLock);
+               pthread_mutex_lock(&ActiveQItemsLock);
                {
-                       GetHashPosFromKey(ActiveQItems, IKEY(MyQItem->MessageID), It);
-                       DeleteEntryFromHash(ActiveQItems, It);
+                       if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
+                               DeleteEntryFromHash(ActiveQItems, It);
+                       else
+                       {
+                               long len;
+                               const char* Key;
+                               void *VData;
+                               syslog(LOG_WARNING, 
+                                      "SMTP cleanup: unable to find QItem with ID[%ld]",
+                                      MyQItem->MessageID);
+                               while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
+                                       syslog(LOG_WARNING, 
+                                              "SMTP cleanup: have: ID[%ld]",
+                                              ((OneQueItem *)VData)->MessageID);
+                       }
+
                }
-               citthread_mutex_unlock(&ActiveQItemsLock);
+               pthread_mutex_unlock(&ActiveQItemsLock);
                DeleteHashPos(&It);
                ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
 
 // TODO: bounce & delete?
 
        }
+       if (!HaveBuffers) {
+               FreeStrBuf (&Msg);
+// TODO : free RelayUrls
+       }
 }
 
 
@@ -541,32 +826,25 @@ void smtp_do_procmsg(long msgnum, void *userdata) {
  * 
  * Run through the queue sending out messages.
  */
-void *smtp_queue_thread(void *arg) {
+void smtp_do_queue(void) {
+       static int is_running = 0;
        int num_processed = 0;
-       struct CitContext smtp_queue_CC;
 
-       CtdlThreadSleep(10);
+       if (is_running) return;         /* Concurrency check - only one can run */
+       is_running = 1;
 
-       CtdlFillSystemContext(&smtp_queue_CC, "SMTP Send");
-       citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
-       CtdlLogPrintf(CTDL_DEBUG, "smtp_queue_thread() initializing\n");
+       pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
+       syslog(LOG_INFO, "SMTP client: processing outbound queue");
 
-       while (!CtdlThreadCheckStop()) {
-               
-               CtdlLogPrintf(CTDL_INFO, "SMTP client: processing outbound queue\n");
-
-               if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
-                       CtdlLogPrintf(CTDL_ERR, "Cannot find room <%s>\n", SMTP_SPOOLOUT_ROOM);
-               }
-               else {
-                       num_processed = CtdlForEachMessage(MSGS_ALL, 0L, NULL, SPOOLMIME, NULL, smtp_do_procmsg, NULL);
-               }
-               CtdlLogPrintf(CTDL_INFO, "SMTP client: queue run completed; %d messages processed\n", num_processed);
-               CtdlThreadSleep(60);
+       if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
+               syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
        }
-
-       CtdlClearSystemContext();
-       return(NULL);
+       else {
+               num_processed = CtdlForEachMessage(MSGS_ALL, 0L, NULL, SPOOLMIME, NULL, smtp_do_procmsg, NULL);
+       }
+       syslog(LOG_INFO, "SMTP client: queue run completed; %d messages processed", num_processed);
+       run_queue_now = 0;
+       is_running = 0;
 }
 
 
@@ -637,15 +915,13 @@ void cmd_smtp(char *argbuf) {
 }
 
 
-
-
 CTDL_MODULE_INIT(smtp_queu)
 {
-#ifdef EXPERIMENTAL_SMTP_EVENT_CLIENT
        if (!threading)
        {
-               ActiveQItems = NewHash(1, Flathash);
-               citthread_mutex_init(&ActiveQItemsLock, NULL);
+               CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
+               ActiveQItems = NewHash(1, lFlathash);
+               pthread_mutex_init(&ActiveQItemsLock, NULL);
 
                QItemHandlers = NewHash(0, NULL);
 
@@ -655,15 +931,15 @@ CTDL_MODULE_INIT(smtp_queu)
                Put(QItemHandlers, HKEY("attempted"), QItem_Handle_Attempted, reference_free_handler);
                Put(QItemHandlers, HKEY("remote"), QItem_Handle_Recipient, reference_free_handler);
                Put(QItemHandlers, HKEY("bounceto"), QItem_Handle_BounceTo, reference_free_handler);
-///submitted /TODO: flush qitemhandlers on exit
+               Put(QItemHandlers, HKEY("submitted"), QItem_Handle_Submitted, reference_free_handler);
+////TODO: flush qitemhandlers on exit
                smtp_init_spoolout();
 
                CtdlRegisterCleanupHook(smtp_evq_cleanup);
-               CtdlThreadCreate("SMTPEvent Send", CTDLTHREAD_BIGSTACK, smtp_queue_thread, NULL);
 
                CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
+               CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER);
        }
-#endif
        
        /* return our Subversion id for the Log */
        return "smtpeventclient";