Back to index

citadel  8.12
serv_smtpqueue.c
Go to the documentation of this file.
00001 /*
00002  * This module is an SMTP and ESMTP implementation for the Citadel system.
00003  * It is compliant with all of the following:
00004  *
00005  * RFC  821 - Simple Mail Transfer Protocol
00006  * RFC  876 - Survey of SMTP Implementations
00007  * RFC 1047 - Duplicate messages and SMTP
00008  * RFC 1652 - 8 bit MIME
00009  * RFC 1869 - Extended Simple Mail Transfer Protocol
00010  * RFC 1870 - SMTP Service Extension for Message Size Declaration
00011  * RFC 2033 - Local Mail Transfer Protocol
00012  * RFC 2197 - SMTP Service Extension for Command Pipelining
00013  * RFC 2476 - Message Submission
00014  * RFC 2487 - SMTP Service Extension for Secure SMTP over TLS
00015  * RFC 2554 - SMTP Service Extension for Authentication
00016  * RFC 2821 - Simple Mail Transfer Protocol
00017  * RFC 2822 - Internet Message Format
00018  * RFC 2920 - SMTP Service Extension for Command Pipelining
00019  *  
00020  * The VRFY and EXPN commands have been removed from this implementation
00021  * because nobody uses these commands anymore, except for spammers.
00022  *
00023  * Copyright (c) 1998-2012 by the citadel.org team
00024  *
00025  *  This program is open source software; you can redistribute it and/or modify
00026  *  it under the terms of the GNU General Public License version 3.
00027  *  
00028  *  
00029  *
00030  *  This program is distributed in the hope that it will be useful,
00031  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00032  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00033  *  GNU General Public License for more details.
00034  *
00035  *  
00036  *  
00037  *  
00038  */
00039 
00040 #include "sysdep.h"
00041 #include <stdlib.h>
00042 #include <unistd.h>
00043 #include <stdio.h>
00044 #include <termios.h>
00045 #include <fcntl.h>
00046 #include <signal.h>
00047 #include <pwd.h>
00048 #include <errno.h>
00049 #include <sys/types.h>
00050 #include <syslog.h>
00051 
00052 #if TIME_WITH_SYS_TIME
00053 # include <sys/time.h>
00054 # include <time.h>
00055 #else
00056 # if HAVE_SYS_TIME_H
00057 #  include <sys/time.h>
00058 # else
00059 #  include <time.h>
00060 # endif
00061 #endif
00062 #include <sys/wait.h>
00063 #include <ctype.h>
00064 #include <string.h>
00065 #include <limits.h>
00066 #include <sys/socket.h>
00067 #include <netinet/in.h>
00068 #include <arpa/inet.h>
00069 #include <libcitadel.h>
00070 #include "citadel.h"
00071 #include "server.h"
00072 #include "citserver.h"
00073 #include "support.h"
00074 #include "config.h"
00075 #include "control.h"
00076 #include "user_ops.h"
00077 #include "database.h"
00078 #include "msgbase.h"
00079 #include "internet_addressing.h"
00080 #include "genstamp.h"
00081 #include "domain.h"
00082 #include "clientsocket.h"
00083 #include "locate_host.h"
00084 #include "citadel_dirs.h"
00085 
00086 #include "ctdl_module.h"
00087 
00088 #include "smtpqueue.h"
00089 #include "smtp_clienthandlers.h"
00090 #include "event_client.h"
00091 
00092 
00093 struct CitContext smtp_queue_CC;
00094 pthread_mutex_t ActiveQItemsLock;
00095 HashList *ActiveQItems  = NULL;
00096 HashList *QItemHandlers = NULL;
00097 const unsigned short DefaultMXPort = 25;
00098 int max_sessions_for_outbound_smtp = 500; /* how many sessions might be active till we stop adding more smtp jobs */
00099 int ndelay_count = 50; /* every n queued messages we will sleep... */
00100 int delay_msec = 5000; /* this many seconds. */
00101 
00102 static const long MaxRetry = SMTP_RETRY_INTERVAL * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
00103 int MsgCount            = 0;
00104 int run_queue_now       = 0;       /* Set to 1 to ignore SMTP send retry times */
00105 
00106 void RegisterQItemHandler(const char *Key, long Len, QItemHandler H)
00107 {
00108        QItemHandlerStruct *HS = (QItemHandlerStruct*)malloc(sizeof(QItemHandlerStruct));
00109        HS->H = H;
00110        Put(QItemHandlers, Key, Len, HS, NULL);
00111 }
00112 
00113 
00114 
00115 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
00116                            MailQEntry *MyQEntry,
00117                            StrBuf *MsgText,
00118 /* KeepMsgText allows us to use MsgText as ours. */
00119                            int KeepMsgText,
00120                            int MsgCount,
00121                            ParsedURL *RelayUrls);
00122 
00123 
00124 void smtp_evq_cleanup(void)
00125 {
00126 
00127        pthread_mutex_lock(&ActiveQItemsLock);
00128        DeleteHash(&QItemHandlers);
00129        DeleteHash(&ActiveQItems);
00130        pthread_mutex_unlock(&ActiveQItemsLock);
00131        pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
00132 /*     citthread_mutex_destroy(&ActiveQItemsLock); TODO */
00133 }
00134 
00135 int DecreaseQReference(OneQueItem *MyQItem)
00136 {
00137        int IDestructQueItem;
00138 
00139        pthread_mutex_lock(&ActiveQItemsLock);
00140        MyQItem->ActiveDeliveries--;
00141        IDestructQueItem = MyQItem->ActiveDeliveries == 0;
00142        pthread_mutex_unlock(&ActiveQItemsLock);
00143        return IDestructQueItem;
00144 }
00145 
00146 void DecreaseShutdownDeliveries(OneQueItem *MyQItem)
00147 {
00148        pthread_mutex_lock(&ActiveQItemsLock);
00149        MyQItem->NotYetShutdownDeliveries--;
00150        pthread_mutex_unlock(&ActiveQItemsLock);
00151 }
00152 
00153 int GetShutdownDeliveries(OneQueItem *MyQItem)
00154 {
00155        int DestructNow;
00156 
00157        pthread_mutex_lock(&ActiveQItemsLock);
00158        DestructNow = MyQItem->ActiveDeliveries == 0;
00159        pthread_mutex_unlock(&ActiveQItemsLock);
00160        return DestructNow;
00161 }
00162 void RemoveQItem(OneQueItem *MyQItem)
00163 {
00164        long len;
00165        const char* Key;
00166        void *VData;
00167        HashPos  *It;
00168 
00169        pthread_mutex_lock(&ActiveQItemsLock);
00170        It = GetNewHashPos(ActiveQItems, 0);
00171        if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
00172               DeleteEntryFromHash(ActiveQItems, It);
00173        else
00174        {
00175               SMTPC_syslog(LOG_WARNING,
00176                           "unable to find QItem with ID[%ld]",
00177                           MyQItem->MessageID);
00178               while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
00179                      SMTPC_syslog(LOG_WARNING,
00180                                  "have_: ID[%ld]",
00181                                  ((OneQueItem *)VData)->MessageID);
00182        }
00183        pthread_mutex_unlock(&ActiveQItemsLock);
00184        DeleteHashPos(&It);
00185 }
00186 
00187 
00188 void FreeMailQEntry(void *qv)
00189 {
00190        MailQEntry *Q = qv;
00191 /*
00192        SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
00193        cit_backtrace();
00194 */
00195        FreeStrBuf(&Q->Recipient);
00196        FreeStrBuf(&Q->StatusMessage);
00197 
00198        memset(Q, 0, sizeof(MailQEntry));
00199        free(Q);
00200 }
00201 void FreeQueItem(OneQueItem **Item)
00202 {
00203 /*
00204        SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
00205        cit_backtrace();
00206 */
00207        DeleteHash(&(*Item)->MailQEntries);
00208        FreeStrBuf(&(*Item)->EnvelopeFrom);
00209        FreeStrBuf(&(*Item)->BounceTo);
00210        FreeStrBuf(&(*Item)->SenderRoom);
00211        FreeURL(&(*Item)->URL);
00212        memset(*Item, 0, sizeof(OneQueItem));
00213        free(*Item);
00214        Item = NULL;
00215 }
00216 void HFreeQueItem(void *Item)
00217 {
00218        FreeQueItem((OneQueItem**)&Item);
00219 }
00220 
00221 /* inspect recipients with a status of:
00222  * - 0 (no delivery yet attempted)
00223  * - 3/4 (transient errors
00224  *        were experienced and it's time to try again)
00225  */
00226 int CheckQEntryActive(MailQEntry *ThisItem)
00227 {
00228        if ((ThisItem->Status == 0) ||
00229            (ThisItem->Status == 3) ||
00230            (ThisItem->Status == 4))
00231        {
00232               return 1;
00233        }
00234        else
00235               return 0;
00236 }
00237 int CheckQEntryIsBounce(MailQEntry *ThisItem)
00238 {
00239        if ((ThisItem->Status == 3) ||
00240            (ThisItem->Status == 4) ||
00241            (ThisItem->Status == 5))
00242        {
00243               return 1;
00244        }
00245        else
00246               return 0;
00247 }      
00248 
00249 int CountActiveQueueEntries(OneQueItem *MyQItem)
00250 {
00251        HashPos  *It;
00252        long len;
00253        long ActiveDeliveries;
00254        const char *Key;
00255        void *vQE;
00256 
00257        ActiveDeliveries = 0;
00258        It = GetNewHashPos(MyQItem->MailQEntries, 0);
00259        while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
00260        {
00261               MailQEntry *ThisItem = vQE;
00262 
00263               if (CheckQEntryActive(ThisItem))
00264               {
00265                      ActiveDeliveries++;
00266                      ThisItem->Active = 1;
00267               }
00268               else
00269                      ThisItem->Active = 0;
00270        }
00271        DeleteHashPos(&It);
00272        return ActiveDeliveries;
00273 }
00274 
00275 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
00276 {
00277        OneQueItem *Item;
00278        const char *pLine = NULL;
00279        StrBuf *Line;
00280        StrBuf *Token;
00281        void *v;
00282 
00283        Item = (OneQueItem*)malloc(sizeof(OneQueItem));
00284        memset(Item, 0, sizeof(OneQueItem));
00285        Item->Retry = SMTP_RETRY_INTERVAL;
00286        Item->MessageID = -1;
00287        Item->QueMsgID = QueMsgID;
00288 
00289        Token = NewStrBuf();
00290        Line = NewStrBufPlain(NULL, 128);
00291        while (pLine != StrBufNOTNULL) {
00292               const char *pItemPart = NULL;
00293               void *vHandler;
00294 
00295               StrBufExtract_NextToken(Line, RawQItem, &pLine, '\n');
00296               if (StrLength(Line) == 0) continue;
00297               StrBufExtract_NextToken(Token, Line, &pItemPart, '|');
00298               if (GetHash(QItemHandlers, SKEY(Token), &vHandler))
00299               {
00300                      QItemHandlerStruct *HS;
00301                      HS = (QItemHandlerStruct*) vHandler;
00302                      HS->H(Item, Line, &pItemPart);
00303               }
00304        }
00305        FreeStrBuf(&Line);
00306        FreeStrBuf(&Token);
00307 
00308        if (Item->Retry >= MaxRetry)
00309               Item->FailNow = 1;
00310 
00311        pthread_mutex_lock(&ActiveQItemsLock);
00312        if (GetHash(ActiveQItems,
00313                   LKEY(Item->MessageID),
00314                   &v))
00315        {
00316               /* WHOOPS. somebody else is already working on this. */
00317               pthread_mutex_unlock(&ActiveQItemsLock);
00318               FreeQueItem(&Item);
00319               return NULL;
00320        }
00321        else {
00322               /* mark our claim on this. */
00323               Put(ActiveQItems,
00324                   LKEY(Item->MessageID),
00325                   Item,
00326                   HFreeQueItem);
00327               pthread_mutex_unlock(&ActiveQItemsLock);
00328        }
00329 
00330        return Item;
00331 }
00332 
00333 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
00334 {
00335        StrBuf *QMessage;
00336        HashPos  *It;
00337        const char *Key;
00338        long len;
00339        void *vQE;
00340 
00341        QMessage = NewStrBufPlain(NULL, SIZ);
00342        StrBufPrintf(QMessage, "Content-type: %s\n", SPOOLMIME);
00343 //     "attempted|%ld\n"  "retry|%ld\n",, (long)time(NULL), (long)retry );
00344        StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
00345        StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
00346 
00347        StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
00348        StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
00349 
00350        if (StrLength(MyQItem->BounceTo) > 0) {
00351               StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
00352               StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
00353        }
00354 
00355        if (StrLength(MyQItem->EnvelopeFrom) > 0) {
00356               StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
00357               StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
00358        }
00359 
00360        if (StrLength(MyQItem->SenderRoom) > 0) {
00361               StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
00362               StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
00363        }
00364 
00365        StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
00366        StrBufAppendPrintf(QMessage, "%ld",
00367                         MyQItem->Retry);
00368 
00369        StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
00370        StrBufAppendPrintf(QMessage, "%ld",
00371                         time(NULL) /*ctdl_ev_now()*/ + MyQItem->Retry);
00372 
00373        It = GetNewHashPos(MyQItem->MailQEntries, 0);
00374        while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
00375        {
00376               MailQEntry *ThisItem = vQE;
00377 
00378               StrBufAppendBufPlain(QMessage, HKEY("\nremote|"), 0);
00379               StrBufAppendBuf(QMessage, ThisItem->Recipient, 0);
00380               StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
00381               StrBufAppendPrintf(QMessage, "%d", ThisItem->Status);
00382               StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
00383               StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
00384        }
00385        DeleteHashPos(&It);
00386        StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
00387        return QMessage;
00388 }
00389 
00390 
00391 
00392 
00393 
00394 void NewMailQEntry(OneQueItem *Item)
00395 {
00396        Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
00397        memset(Item->Current, 0, sizeof(MailQEntry));
00398 
00399        if (Item->MailQEntries == NULL)
00400               Item->MailQEntries = NewHash(1, Flathash);
00401        /* alocate big buffer so we won't get problems reallocating later. */
00402        Item->Current->StatusMessage = NewStrBufPlain(NULL, SIZ);
00403        Item->Current->n = GetCount(Item->MailQEntries);
00404        Put(Item->MailQEntries,
00405            IKEY(Item->Current->n),
00406            Item->Current,
00407            FreeMailQEntry);
00408 }
00409 
00410 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
00411 {
00412        Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
00413 }
00414 
00415 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
00416 {
00417        if (Item->EnvelopeFrom == NULL)
00418               Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
00419        StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
00420 }
00421 
00422 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
00423 {
00424        if (Item->BounceTo == NULL)
00425               Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
00426        StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
00427 }
00428 
00429 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
00430 {
00431        if (Item->SenderRoom == NULL)
00432               Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
00433        StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
00434 }
00435 
00436 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
00437 {
00438        if (Item->Current == NULL)
00439               NewMailQEntry(Item);
00440        if (Item->Current->Recipient == NULL)
00441               Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
00442        StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
00443        Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
00444        StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
00445        Item->Current = NULL; // TODO: is this always right?
00446 }
00447 
00448 
00449 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
00450 {
00451        Item->Retry =
00452               StrBufExtractNext_int(Line, Pos, '|');
00453        if (Item->Retry == 0)
00454               Item->Retry = SMTP_RETRY_INTERVAL;
00455        else
00456               Item->Retry *= 2;
00457 }
00458 
00459 
00460 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
00461 {
00462        Item->Submitted = atol(*Pos);
00463 
00464 }
00465 
00466 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
00467 {
00468        Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
00469 }
00470 
00471 
00472 
00476 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
00477 {
00478        CitContext *CCC=CC;
00479        StrBuf *SendMsg;
00480 
00481        CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
00482        CtdlOutputMsg(MyQItem->MessageID,
00483                     MT_RFC822, HEADERS_ALL,
00484                     0, 1, NULL,
00485                     (ESC_DOT|SUPPRESS_ENV_TO) );
00486 
00487        SendMsg = CCC->redirect_buffer;
00488        CCC->redirect_buffer = NULL;
00489        if ((StrLength(SendMsg) > 0) &&
00490            ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
00491               SMTPC_syslog(LOG_WARNING,
00492                           "[%d] Possible problem: message did not "
00493                           "correctly terminate. (expecting 0x10, got 0x%02x)\n",
00494                           MsgCount, //yes uncool, but best choice here...
00495                           ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
00496               StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
00497        }
00498        return SendMsg;
00499 }
00500 
00501 
00502 
00503 /*
00504  * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
00505  * instructions for "5" codes (permanent fatal errors) and produce/deliver
00506  * a "bounce" message (delivery status notification).
00507  */
00508 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt)
00509 {
00510        static int seq = 0;
00511 
00512        struct CtdlMessage *bmsg = NULL;
00513        StrBuf *boundary;
00514        StrBuf *Msg = NULL;
00515        StrBuf *BounceMB;
00516        struct recptypes *valid;
00517        time_t now;
00518 
00519        HashPos *It;
00520        void *vQE;
00521        long len;
00522        const char *Key;
00523 
00524        int first_attempt = 0;
00525        int successful_bounce = 0;
00526        int num_bounces = 0;
00527        int give_up = 0;
00528 
00529        SMTPCM_syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
00530 
00531        if (MyQItem->SendBounceMail == 0)
00532               return;
00533 
00534        now = time (NULL); //ev_time();
00535 
00536        if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
00537               give_up = 1;
00538        }
00539 
00540        if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
00541               first_attempt = 1;
00542        }
00543 
00544        /*
00545         * Now go through the instructions checking for stuff.
00546         */
00547        Msg = NewStrBufPlain(NULL, 1024);
00548        It = GetNewHashPos(MyQItem->MailQEntries, 0);
00549        while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
00550        {
00551               MailQEntry *ThisItem = vQE;
00552               if ((ThisItem->Active && (ThisItem->Status == 5)) || /* failed now? */
00553                   ((give_up == 1) && (ThisItem->Status != 2)) ||
00554                   ((first_attempt == 1) && (ThisItem->Status != 2)))
00555                      /* giving up after failed attempts... */
00556               {
00557                      ++num_bounces;
00558 
00559                      StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
00560                      StrBufAppendBufPlain(Msg, HKEY(": "), 0);
00561                      StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
00562                      StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
00563               }
00564        }
00565        DeleteHashPos(&It);
00566 
00567        /* Deliver the bounce if there's anything worth mentioning */
00568        SMTPC_syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
00569 
00570        if (num_bounces == 0) {
00571               FreeStrBuf(&Msg);
00572               return;
00573        }
00574 
00575        boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
00576        StrBufAppendPrintf(boundary,
00577                         "%s_%04x%04x",
00578                         config.c_fqdn,
00579                         getpid(),
00580                         ++seq);
00581 
00582        /* Start building our bounce message; go shopping for memory first. */
00583        BounceMB = NewStrBufPlain(
00584               NULL,
00585               1024 + /* mime stuff.... */
00586               StrLength(Msg) +  /* the bounce information... */
00587               StrLength(OMsgTxt)); /* the original message */
00588        if (BounceMB == NULL) {
00589               FreeStrBuf(&boundary);
00590               SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
00591 
00592               return;
00593        }
00594 
00595        bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
00596        if (bmsg == NULL) {
00597               FreeStrBuf(&boundary);
00598               FreeStrBuf(&BounceMB);
00599               SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
00600 
00601               return;
00602        }
00603        memset(bmsg, 0, sizeof(struct CtdlMessage));
00604 
00605 
00606        StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
00607        StrBufAppendBuf(BounceMB, boundary, 0);
00608        StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
00609        StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
00610        StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
00611        StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
00612        StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
00613        StrBufAppendBuf(BounceMB, boundary, 0);
00614        StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
00615        StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
00616 
00617        if (give_up)
00618               StrBufAppendBufPlain(
00619                      BounceMB,
00620                      HKEY(
00621                             "A message you sent could not be delivered "
00622                             "to some or all of its recipients\n"
00623                             "due to prolonged unavailability "
00624                             "of its destination(s).\n"
00625                             "Giving up on the following addresses:\n\n"
00626                             ), 0);
00627        else
00628               StrBufAppendBufPlain(
00629                      BounceMB,
00630                      HKEY(
00631                             "A message you sent could not be delivered "
00632                             "to some or all of its recipients.\n"
00633                             "The following addresses "
00634                             "were undeliverable:\n\n"
00635                             ), 0);
00636 
00637        StrBufAppendBuf(BounceMB, Msg, 0);
00638        FreeStrBuf(&Msg);
00639 
00640        if (StrLength(MyQItem->SenderRoom) > 0)
00641        {
00642               StrBufAppendBufPlain(
00643                      BounceMB,
00644                      HKEY("The message was originaly posted in: "), 0);
00645               StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
00646               StrBufAppendBufPlain(
00647                      BounceMB,
00648                      HKEY("\n"), 0);
00649        }
00650 
00651        /* Attach the original message */
00652        StrBufAppendBufPlain(BounceMB, HKEY("\r\n--"), 0);
00653        StrBufAppendBuf(BounceMB, boundary, 0);
00654        StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
00655        StrBufAppendBufPlain(BounceMB,
00656                           HKEY("Content-type: message/rfc822\r\n"), 0);
00657        StrBufAppendBufPlain(BounceMB,
00658                           HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
00659        StrBufAppendBufPlain(BounceMB,
00660                           HKEY("Content-Disposition: inline\r\n"), 0);
00661        StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
00662        StrBufAppendBuf(BounceMB, OMsgTxt, 0);
00663 
00664        /* Close the multipart MIME scope */
00665        StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
00666        StrBufAppendBuf(BounceMB, boundary, 0);
00667        StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
00668 
00669        bmsg->cm_magic = CTDLMESSAGE_MAGIC;
00670        bmsg->cm_anon_type = MES_NORMAL;
00671        bmsg->cm_format_type = FMT_RFC822;
00672 
00673        bmsg->cm_fields['O'] = strdup(MAILROOM);
00674        bmsg->cm_fields['A'] = strdup("Citadel");
00675        bmsg->cm_fields['N'] = strdup(config.c_nodename);
00676        bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
00677        bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
00678 
00679        /* First try the user who sent the message */
00680        if (StrLength(MyQItem->BounceTo) == 0) {
00681               SMTPCM_syslog(LOG_ERR, "No bounce address specified\n");
00682        }
00683        else {
00684               SMTPC_syslog(LOG_DEBUG, "bounce to user? <%s>\n",
00685                      ChrPtr(MyQItem->BounceTo));
00686        }
00687 
00688        /* Can we deliver the bounce to the original sender? */
00689        valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
00690        if ((valid != NULL) && (valid->num_error == 0)) {
00691               CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
00692               successful_bounce = 1;
00693        }
00694 
00695        /* If not, post it in the Aide> room */
00696        if (successful_bounce == 0) {
00697               CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
00698        }
00699 
00700        /* Free up the memory we used */
00701        free_recipients(valid);
00702        FreeStrBuf(&boundary);
00703        CtdlFreeMessage(bmsg);
00704        SMTPCM_syslog(LOG_DEBUG, "Done processing bounces\n");
00705 }
00706 
00707 /*
00708  * smtp_do_procmsg()
00709  *
00710  * Called by smtp_do_queue() to handle an individual message.
00711  */
00712 void smtp_do_procmsg(long msgnum, void *userdata) {
00713        time_t now;
00714        int mynumsessions = num_sessions;
00715        struct CtdlMessage *msg = NULL;
00716        char *instr = NULL;
00717        StrBuf *PlainQItem;
00718        OneQueItem *MyQItem;
00719        char *pch;
00720        HashPos  *It;
00721        void *vQE;
00722        long len;
00723        const char *Key;
00724        int nRelays = 0;
00725        ParsedURL *RelayUrls = NULL;
00726        int HaveBuffers = 0;
00727        StrBuf *Msg =NULL;
00728 
00729        if (mynumsessions > max_sessions_for_outbound_smtp) {
00730               SMTPC_syslog(LOG_DEBUG,
00731                           "skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
00732                           mynumsessions,
00733                           max_sessions_for_outbound_smtp);
00734        }
00735 
00736        SMTPC_syslog(LOG_DEBUG, "smtp_do_procmsg(%ld)\n", msgnum);
00738 
00739        msg = CtdlFetchMessage(msgnum, 1);
00740        if (msg == NULL) {
00741               SMTPC_syslog(LOG_ERR, "tried %ld but no such message!\n",
00742                      msgnum);
00743               return;
00744        }
00745 
00746        pch = instr = msg->cm_fields['M'];
00747 
00748        /* Strip out the headers (no not amd any other non-instruction) line */
00749        while (pch != NULL) {
00750               pch = strchr(pch, '\n');
00751               if ((pch != NULL) && (*(pch + 1) == '\n')) {
00752                      instr = pch + 2;
00753                      pch = NULL;
00754               }
00755        }
00756        PlainQItem = NewStrBufPlain(instr, -1);
00757        CtdlFreeMessage(msg);
00758        MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
00759        FreeStrBuf(&PlainQItem);
00760 
00761        if (MyQItem == NULL) {
00762               SMTPC_syslog(LOG_ERR,
00763                           "Msg No %ld: already in progress!\n",
00764                           msgnum);
00765               return; /* s.b. else is already processing... */
00766        }
00767 
00768        /*
00769         * Postpone delivery if we've already tried recently.
00770         */
00771        now = time(NULL);
00772        if ((MyQItem->ReattemptWhen != 0) && 
00773            (now < MyQItem->ReattemptWhen) &&
00774            (run_queue_now == 0))
00775        {
00776               SMTPC_syslog(LOG_DEBUG, 
00777                           "Retry time not yet reached. %ld seconds left.",
00778                           MyQItem->ReattemptWhen - now);
00779 
00780               It = GetNewHashPos(MyQItem->MailQEntries, 0);
00781               pthread_mutex_lock(&ActiveQItemsLock);
00782               {
00783                      if (GetHashPosFromKey(ActiveQItems,
00784                                          LKEY(MyQItem->MessageID),
00785                                          It))
00786                      {
00787                             DeleteEntryFromHash(ActiveQItems, It);
00788                      }
00789               }
00790               pthread_mutex_unlock(&ActiveQItemsLock);
00792               DeleteHashPos(&It);
00793               return;
00794        }
00795 
00796        /*
00797         * Bail out if there's no actual message associated with this
00798         */
00799        if (MyQItem->MessageID < 0L) {
00800               SMTPCM_syslog(LOG_ERR, "no 'msgid' directive found!\n");
00801               It = GetNewHashPos(MyQItem->MailQEntries, 0);
00802               pthread_mutex_lock(&ActiveQItemsLock);
00803               {
00804                      if (GetHashPosFromKey(ActiveQItems,
00805                                          LKEY(MyQItem->MessageID),
00806                                          It))
00807                      {
00808                             DeleteEntryFromHash(ActiveQItems, It);
00809                      }
00810               }
00811               pthread_mutex_unlock(&ActiveQItemsLock);
00812               DeleteHashPos(&It);
00814               return;
00815        }
00816 
00817        {
00818               char mxbuf[SIZ];
00819               ParsedURL **Url = &MyQItem->URL;
00820               nRelays = get_hosts(mxbuf, "smarthost");
00821               if (nRelays > 0) {
00822                      StrBuf *All;
00823                      StrBuf *One;
00824                      const char *Pos = NULL;
00825                      All = NewStrBufPlain(mxbuf, -1);
00826                      One = NewStrBufPlain(NULL, StrLength(All) + 1);
00827 
00828                      while ((Pos != StrBufNOTNULL) &&
00829                             ((Pos == NULL) ||
00830                             !IsEmptyStr(Pos)))
00831                      {
00832                             StrBufExtract_NextToken(One, All, &Pos, '|');
00833                             if (!ParseURL(Url, One, DefaultMXPort)) {
00834                                    SMTPC_syslog(LOG_DEBUG,
00835                                                "Failed to parse: %s\n",
00836                                                ChrPtr(One));
00837                             }
00838                             else {
00840                                    Url = &(*Url)->Next;
00841                             }
00842                      }
00843                      FreeStrBuf(&All);
00844                      FreeStrBuf(&One);
00845               }
00846 
00847               Url = &MyQItem->FallBackHost;
00848               nRelays = get_hosts(mxbuf, "fallbackhost");
00849               if (nRelays > 0) {
00850                      StrBuf *All;
00851                      StrBuf *One;
00852                      const char *Pos = NULL;
00853                      All = NewStrBufPlain(mxbuf, -1);
00854                      One = NewStrBufPlain(NULL, StrLength(All) + 1);
00855 
00856                      while ((Pos != StrBufNOTNULL) &&
00857                             ((Pos == NULL) ||
00858                             !IsEmptyStr(Pos)))
00859                      {
00860                             StrBufExtract_NextToken(One, All, &Pos, '|');
00861                             if (!ParseURL(Url, One, DefaultMXPort)) {
00862                                    SMTPC_syslog(LOG_DEBUG,
00863                                                "Failed to parse: %s\n",
00864                                                ChrPtr(One));
00865                             }
00866                             else
00867                                    Url = &(*Url)->Next;
00868                      }
00869                      FreeStrBuf(&All);
00870                      FreeStrBuf(&One);
00871               }
00872        }
00873 
00874        It = GetNewHashPos(MyQItem->MailQEntries, 0);
00875        while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
00876        {
00877               MailQEntry *ThisItem = vQE;
00878               SMTPC_syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
00879                           ChrPtr(ThisItem->Recipient),
00880                           ThisItem->Active);
00881        }
00882        DeleteHashPos(&It);
00883 
00884        MyQItem->NotYetShutdownDeliveries = 
00885        MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem);
00886 
00887        /* failsafe against overload: 
00888         * will we exceed the limit set? 
00889         */
00890        if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) && 
00891            /* if yes, did we reach more than half of the quota? */
00892            ((mynumsessions * 2) > max_sessions_for_outbound_smtp) && 
00893            /* if... would we ever fit into half of the quota?? */
00894            (((MyQItem->ActiveDeliveries * 2)  < max_sessions_for_outbound_smtp)))
00895        {
00896               /* abort delivery for another time. */
00897               SMTPC_syslog(LOG_DEBUG,
00898                           "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
00899                           mynumsessions,
00900                           MyQItem->ActiveDeliveries,
00901                           max_sessions_for_outbound_smtp);
00902 
00903               FreeQueItem(&MyQItem);
00904 
00905               return;
00906        }
00907 
00908 
00909        if (MyQItem->ActiveDeliveries > 0)
00910        {
00911               int nActivated = 0;
00912               int n = MsgCount++;
00913               int m = MyQItem->ActiveDeliveries;
00914               int i = 1;
00915               Msg = smtp_load_msg(MyQItem, n);
00916               It = GetNewHashPos(MyQItem->MailQEntries, 0);
00917               while ((i <= m) &&
00918                      (GetNextHashPos(MyQItem->MailQEntries,
00919                                    It, &len, &Key, &vQE)))
00920               {
00921                      MailQEntry *ThisItem = vQE;
00922 
00923                      if (ThisItem->Active == 1)
00924                      {
00925                             int KeepBuffers = (i == m);
00926 
00927                             nActivated++;
00928                             if (nActivated % ndelay_count == 0)
00929                                    usleep(delay_msec);
00930 
00931                             if (i > 1) n = MsgCount++;
00932                             syslog(LOG_DEBUG,
00933                                    "SMTPC: Trying <%ld> <%s> %d / %d \n",
00934                                    MyQItem->MessageID,
00935                                    ChrPtr(ThisItem->Recipient),
00936                                    i,
00937                                    m);
00938                             (*((int*) userdata)) ++;
00939                             smtp_try_one_queue_entry(MyQItem,
00940                                                   ThisItem,
00941                                                   Msg,
00942                                                   KeepBuffers,
00943                                                   n,
00944                                                   RelayUrls);
00945 
00946                             if (KeepBuffers) HaveBuffers = 1;
00947 
00948                             i++;
00949                      }
00950               }
00951               DeleteHashPos(&It);
00952        }
00953        else
00954        {
00955               It = GetNewHashPos(MyQItem->MailQEntries, 0);
00956               pthread_mutex_lock(&ActiveQItemsLock);
00957               {
00958                      if (GetHashPosFromKey(ActiveQItems,
00959                                          LKEY(MyQItem->MessageID),
00960                                          It))
00961                      {
00962                             DeleteEntryFromHash(ActiveQItems, It);
00963                      }
00964                      else
00965                      {
00966                             long len;
00967                             const char* Key;
00968                             void *VData;
00969 
00970                             SMTPC_syslog(LOG_WARNING,
00971                                         "unable to find QItem with ID[%ld]",
00972                                         MyQItem->MessageID);
00973                             while (GetNextHashPos(ActiveQItems,
00974                                                 It,
00975                                                 &len,
00976                                                 &Key,
00977                                                 &VData))
00978                             {
00979                                    SMTPC_syslog(LOG_WARNING,
00980                                                "have: ID[%ld]",
00981                                                ((OneQueItem *)VData)->MessageID);
00982                             }
00983                      }
00984 
00985               }
00986               pthread_mutex_unlock(&ActiveQItemsLock);
00987               DeleteHashPos(&It);
00989 
00990 // TODO: bounce & delete?
00991 
00992        }
00993        if (!HaveBuffers) {
00994               FreeStrBuf (&Msg);
00995 // TODO : free RelayUrls
00996        }
00997 }
00998 
00999 
01000 
01001 /*
01002  * smtp_queue_thread()
01003  *
01004  * Run through the queue sending out messages.
01005  */
01006 void smtp_do_queue(void) {
01007        int num_processed = 0;
01008        int num_activated = 0;
01009 
01010        pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
01011        SMTPCM_syslog(LOG_INFO, "processing outbound queue");
01012 
01013        if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
01014               SMTPC_syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
01015        }
01016        else {
01017               num_processed = CtdlForEachMessage(MSGS_ALL,
01018                                              0L,
01019                                              NULL,
01020                                              SPOOLMIME,
01021                                              NULL,
01022                                              smtp_do_procmsg,
01023                                              &num_activated);
01024        }
01025        SMTPC_syslog(LOG_INFO,
01026                    "queue run completed; %d messages processed %d activated",
01027                    num_processed, num_activated);
01028 
01029 }
01030 
01031 
01032 
01033 /*
01034  * Initialize the SMTP outbound queue
01035  */
01036 void smtp_init_spoolout(void) {
01037        struct ctdlroom qrbuf;
01038 
01039        /*
01040         * Create the room.  This will silently fail if the room already
01041         * exists, and that's perfectly ok, because we want it to exist.
01042         */
01043        CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
01044 
01045        /*
01046         * Make sure it's set to be a "system room" so it doesn't show up
01047         * in the <K>nown rooms list for Aides.
01048         */
01049        if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
01050               qrbuf.QRflags2 |= QR2_SYSTEM;
01051               CtdlPutRoomLock(&qrbuf);
01052        }
01053 }
01054 
01055 
01056 
01057 
01058 /*****************************************************************************/
01059 /*                          SMTP UTILITY COMMANDS                            */
01060 /*****************************************************************************/
01061 
01062 void cmd_smtp(char *argbuf) {
01063        char cmd[64];
01064        char node[256];
01065        char buf[1024];
01066        int i;
01067        int num_mxhosts;
01068 
01069        if (CtdlAccessCheck(ac_aide)) return;
01070 
01071        extract_token(cmd, argbuf, 0, '|', sizeof cmd);
01072 
01073        if (!strcasecmp(cmd, "mx")) {
01074               extract_token(node, argbuf, 1, '|', sizeof node);
01075               num_mxhosts = getmx(buf, node);
01076               cprintf("%d %d MX hosts listed for %s\n",
01077                      LISTING_FOLLOWS, num_mxhosts, node);
01078               for (i=0; i<num_mxhosts; ++i) {
01079                      extract_token(node, buf, i, '|', sizeof node);
01080                      cprintf("%s\n", node);
01081               }
01082               cprintf("000\n");
01083               return;
01084        }
01085 
01086        else if (!strcasecmp(cmd, "runqueue")) {
01087               run_queue_now = 1;
01088               cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
01089               return;
01090        }
01091 
01092        else {
01093               cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
01094        }
01095 
01096 }
01097 
01098 
01099 CTDL_MODULE_INIT(smtp_queu)
01100 {
01101        char *pstr;
01102 
01103        if (!threading)
01104        {
01105               pstr = getenv("CITSERVER_n_session_max");
01106               if ((pstr != NULL) && (*pstr != '\0'))
01107                      max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
01108 
01109               pstr = getenv("CITSERVER_smtp_n_delay_count");
01110               if ((pstr != NULL) && (*pstr != '\0'))
01111                      ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
01112 
01113               pstr = getenv("CITSERVER_smtp_delay");
01114               if ((pstr != NULL) && (*pstr != '\0'))
01115                      delay_msec = atol(pstr) * 1000; /* this many seconds. */
01116 
01117 
01118 
01119 
01120               CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
01121               ActiveQItems = NewHash(1, lFlathash);
01122               pthread_mutex_init(&ActiveQItemsLock, NULL);
01123 
01124               QItemHandlers = NewHash(0, NULL);
01125 
01126               RegisterQItemHandler(HKEY("msgid"),              QItem_Handle_MsgID);
01127               RegisterQItemHandler(HKEY("envelope_from"),      QItem_Handle_EnvelopeFrom);
01128               RegisterQItemHandler(HKEY("retry"),              QItem_Handle_retry);
01129               RegisterQItemHandler(HKEY("attempted"),          QItem_Handle_Attempted);
01130               RegisterQItemHandler(HKEY("remote"),             QItem_Handle_Recipient);
01131               RegisterQItemHandler(HKEY("bounceto"),           QItem_Handle_BounceTo);
01132               RegisterQItemHandler(HKEY("source_room"), QItem_Handle_SenderRoom);
01133               RegisterQItemHandler(HKEY("submitted"),          QItem_Handle_Submitted);
01134 
01135               smtp_init_spoolout();
01136 
01137               CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
01138 
01139               CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
01140               CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER, PRIO_SEND + 10);
01141        }
01142 
01143        /* return our Subversion id for the Log */
01144        return "smtpeventclient";
01145 }