SMTP-Client: when relaying failed also notify aide that somethings broken.
[citadel.git] / citadel / modules / smtp / serv_smtpqueue.c
1 /*
2  * This module is an SMTP and ESMTP implementation for the Citadel system.
3  * It is compliant with all of the following:
4  *
5  * RFC  821 - Simple Mail Transfer Protocol
6  * RFC  876 - Survey of SMTP Implementations
7  * RFC 1047 - Duplicate messages and SMTP
8  * RFC 1652 - 8 bit MIME
9  * RFC 1869 - Extended Simple Mail Transfer Protocol
10  * RFC 1870 - SMTP Service Extension for Message Size Declaration
11  * RFC 2033 - Local Mail Transfer Protocol
12  * RFC 2197 - SMTP Service Extension for Command Pipelining
13  * RFC 2476 - Message Submission
14  * RFC 2487 - SMTP Service Extension for Secure SMTP over TLS
15  * RFC 2554 - SMTP Service Extension for Authentication
16  * RFC 2821 - Simple Mail Transfer Protocol
17  * RFC 2822 - Internet Message Format
18  * RFC 2920 - SMTP Service Extension for Command Pipelining
19  *  
20  * The VRFY and EXPN commands have been removed from this implementation
21  * because nobody uses these commands anymore, except for spammers.
22  *
23  * Copyright (c) 1998-2012 by the citadel.org team
24  *
25  *  This program is open source software; you can redistribute it and/or modify
26  *  it under the terms of the GNU General Public License version 3.
27  *  
28  *  
29  *
30  *  This program is distributed in the hope that it will be useful,
31  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
32  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  *  GNU General Public License for more details.
34  *
35  *  
36  *  
37  *  
38  */
39
40 #include "sysdep.h"
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <stdio.h>
44 #include <termios.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <pwd.h>
48 #include <errno.h>
49 #include <sys/types.h>
50 #include <syslog.h>
51
52 #if TIME_WITH_SYS_TIME
53 # include <sys/time.h>
54 # include <time.h>
55 #else
56 # if HAVE_SYS_TIME_H
57 #  include <sys/time.h>
58 # else
59 #  include <time.h>
60 # endif
61 #endif
62 #include <sys/wait.h>
63 #include <ctype.h>
64 #include <string.h>
65 #include <limits.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69 #include <libcitadel.h>
70 #include "citadel.h"
71 #include "server.h"
72 #include "citserver.h"
73 #include "support.h"
74 #include "config.h"
75 #include "control.h"
76 #include "user_ops.h"
77 #include "database.h"
78 #include "msgbase.h"
79 #include "internet_addressing.h"
80 #include "genstamp.h"
81 #include "domain.h"
82 #include "clientsocket.h"
83 #include "locate_host.h"
84 #include "citadel_dirs.h"
85
86 #include "ctdl_module.h"
87
88 #include "smtpqueue.h"
89 #include "smtp_clienthandlers.h"
90 #include "event_client.h"
91
92
93 struct CitContext smtp_queue_CC;
94 pthread_mutex_t ActiveQItemsLock;
95 HashList *ActiveQItems  = NULL;
96 HashList *QItemHandlers = NULL;
97 const unsigned short DefaultMXPort = 25;
98 int max_sessions_for_outbound_smtp = 500; /* how many sessions might be active till we stop adding more smtp jobs */
99 int ndelay_count = 50; /* every n queued messages we will sleep... */
100 int delay_msec = 5000; /* this many seconds. */
101
102 static const long MaxRetry = SMTP_RETRY_INTERVAL * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
103 int MsgCount            = 0;
104 int run_queue_now       = 0;    /* Set to 1 to ignore SMTP send retry times */
105
106 void RegisterQItemHandler(const char *Key, long Len, QItemHandler H)
107 {
108         QItemHandlerStruct *HS = (QItemHandlerStruct*)malloc(sizeof(QItemHandlerStruct));
109         HS->H = H;
110         Put(QItemHandlers, Key, Len, HS, NULL);
111 }
112
113
114
115 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
116                               MailQEntry *MyQEntry,
117                               StrBuf *MsgText,
118 /* KeepMsgText allows us to use MsgText as ours. */
119                               int KeepMsgText,
120                               int MsgCount,
121                               ParsedURL *RelayUrls);
122
123
124 void smtp_evq_cleanup(void)
125 {
126
127         pthread_mutex_lock(&ActiveQItemsLock);
128         DeleteHash(&QItemHandlers);
129         DeleteHash(&ActiveQItems);
130         pthread_mutex_unlock(&ActiveQItemsLock);
131         pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
132 /*      citthread_mutex_destroy(&ActiveQItemsLock); TODO */
133 }
134
135 int DecreaseQReference(OneQueItem *MyQItem)
136 {
137         int IDestructQueItem;
138
139         pthread_mutex_lock(&ActiveQItemsLock);
140         MyQItem->ActiveDeliveries--;
141         IDestructQueItem = MyQItem->ActiveDeliveries == 0;
142         pthread_mutex_unlock(&ActiveQItemsLock);
143         return IDestructQueItem;
144 }
145
146 void DecreaseShutdownDeliveries(OneQueItem *MyQItem)
147 {
148         pthread_mutex_lock(&ActiveQItemsLock);
149         MyQItem->NotYetShutdownDeliveries--;
150         pthread_mutex_unlock(&ActiveQItemsLock);
151 }
152
153 int GetShutdownDeliveries(OneQueItem *MyQItem)
154 {
155         int DestructNow;
156
157         pthread_mutex_lock(&ActiveQItemsLock);
158         DestructNow = MyQItem->ActiveDeliveries == 0;
159         pthread_mutex_unlock(&ActiveQItemsLock);
160         return DestructNow;
161 }
162 void RemoveQItem(OneQueItem *MyQItem)
163 {
164         long len;
165         const char* Key;
166         void *VData;
167         HashPos  *It;
168
169         pthread_mutex_lock(&ActiveQItemsLock);
170         It = GetNewHashPos(ActiveQItems, 0);
171         if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
172                 DeleteEntryFromHash(ActiveQItems, It);
173         else
174         {
175                 SMTPC_syslog(LOG_WARNING,
176                              "unable to find QItem with ID[%ld]",
177                              MyQItem->MessageID);
178                 while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
179                         SMTPC_syslog(LOG_WARNING,
180                                      "have_: ID[%ld]",
181                                      ((OneQueItem *)VData)->MessageID);
182         }
183         pthread_mutex_unlock(&ActiveQItemsLock);
184         DeleteHashPos(&It);
185 }
186
187
188 void FreeMailQEntry(void *qv)
189 {
190         MailQEntry *Q = qv;
191 /*
192         SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
193         cit_backtrace();
194 */
195         FreeStrBuf(&Q->Recipient);
196         FreeStrBuf(&Q->StatusMessage);
197
198         memset(Q, 0, sizeof(MailQEntry));
199         free(Q);
200 }
201 void FreeQueItem(OneQueItem **Item)
202 {
203 /*
204         SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
205         cit_backtrace();
206 */
207         DeleteHash(&(*Item)->MailQEntries);
208         FreeStrBuf(&(*Item)->EnvelopeFrom);
209         FreeStrBuf(&(*Item)->BounceTo);
210         FreeStrBuf(&(*Item)->SenderRoom);
211         FreeURL(&(*Item)->URL);
212         memset(*Item, 0, sizeof(OneQueItem));
213         free(*Item);
214         Item = NULL;
215 }
216 void HFreeQueItem(void *Item)
217 {
218         FreeQueItem((OneQueItem**)&Item);
219 }
220
221 /* inspect recipients with a status of:
222  * - 0 (no delivery yet attempted)
223  * - 3/4 (transient errors
224  *        were experienced and it's time to try again)
225  */
226 int CheckQEntryActive(MailQEntry *ThisItem)
227 {
228         if ((ThisItem->Status == 0) ||
229             (ThisItem->Status == 3) ||
230             (ThisItem->Status == 4))
231         {
232                 return 1;
233         }
234         else
235                 return 0;
236 }
237 int CheckQEntryIsBounce(MailQEntry *ThisItem)
238 {
239         if ((ThisItem->Status == 3) ||
240             (ThisItem->Status == 4) ||
241             (ThisItem->Status == 5))
242         {
243                 return 1;
244         }
245         else
246                 return 0;
247 }       
248
249 int CountActiveQueueEntries(OneQueItem *MyQItem, int before)
250 {
251         HashPos  *It;
252         long len;
253         long ActiveDeliveries;
254         const char *Key;
255         void *vQE;
256
257         ActiveDeliveries = 0;
258         It = GetNewHashPos(MyQItem->MailQEntries, 0);
259         while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
260         {
261                 int Active;
262                 MailQEntry *ThisItem = vQE;
263
264                 if (CheckQEntryActive(ThisItem))
265                 {
266                         ActiveDeliveries++;
267                         Active = 1;
268                 }
269                 else
270                         Active = 0;
271                 if (before)
272                         ThisItem->Active = Active;
273                 else
274                         ThisItem->StillActive = Active;
275         }
276         DeleteHashPos(&It);
277         return ActiveDeliveries;
278 }
279
280 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
281 {
282         OneQueItem *Item;
283         const char *pLine = NULL;
284         StrBuf *Line;
285         StrBuf *Token;
286         void *v;
287
288         Item = (OneQueItem*)malloc(sizeof(OneQueItem));
289         memset(Item, 0, sizeof(OneQueItem));
290         Item->Retry = SMTP_RETRY_INTERVAL;
291         Item->MessageID = -1;
292         Item->QueMsgID = QueMsgID;
293
294         Token = NewStrBuf();
295         Line = NewStrBufPlain(NULL, 128);
296         while (pLine != StrBufNOTNULL) {
297                 const char *pItemPart = NULL;
298                 void *vHandler;
299
300                 StrBufExtract_NextToken(Line, RawQItem, &pLine, '\n');
301                 if (StrLength(Line) == 0) continue;
302                 StrBufExtract_NextToken(Token, Line, &pItemPart, '|');
303                 if (GetHash(QItemHandlers, SKEY(Token), &vHandler))
304                 {
305                         QItemHandlerStruct *HS;
306                         HS = (QItemHandlerStruct*) vHandler;
307                         HS->H(Item, Line, &pItemPart);
308                 }
309         }
310         FreeStrBuf(&Line);
311         FreeStrBuf(&Token);
312
313         if (Item->Retry >= MaxRetry)
314                 Item->FailNow = 1;
315
316         pthread_mutex_lock(&ActiveQItemsLock);
317         if (GetHash(ActiveQItems,
318                     LKEY(Item->MessageID),
319                     &v))
320         {
321                 /* WHOOPS. somebody else is already working on this. */
322                 pthread_mutex_unlock(&ActiveQItemsLock);
323                 FreeQueItem(&Item);
324                 return NULL;
325         }
326         else {
327                 /* mark our claim on this. */
328                 Put(ActiveQItems,
329                     LKEY(Item->MessageID),
330                     Item,
331                     HFreeQueItem);
332                 pthread_mutex_unlock(&ActiveQItemsLock);
333         }
334
335         return Item;
336 }
337
338 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
339 {
340         StrBuf *QMessage;
341         HashPos  *It;
342         const char *Key;
343         long len;
344         void *vQE;
345
346         QMessage = NewStrBufPlain(NULL, SIZ);
347         StrBufPrintf(QMessage, "Content-type: %s\n", SPOOLMIME);
348 //      "attempted|%ld\n"  "retry|%ld\n",, (long)time(NULL), (long)retry );
349         StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
350         StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
351
352         StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
353         StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
354
355         if (StrLength(MyQItem->BounceTo) > 0) {
356                 StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
357                 StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
358         }
359
360         if (StrLength(MyQItem->EnvelopeFrom) > 0) {
361                 StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
362                 StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
363         }
364
365         if (StrLength(MyQItem->SenderRoom) > 0) {
366                 StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
367                 StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
368         }
369
370         StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
371         StrBufAppendPrintf(QMessage, "%ld",
372                            MyQItem->Retry);
373
374         StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
375         StrBufAppendPrintf(QMessage, "%ld",
376                            time(NULL) /*ctdl_ev_now()*/ + MyQItem->Retry);
377
378         It = GetNewHashPos(MyQItem->MailQEntries, 0);
379         while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
380         {
381                 MailQEntry *ThisItem = vQE;
382
383                 StrBufAppendBufPlain(QMessage, HKEY("\nremote|"), 0);
384                 StrBufAppendBuf(QMessage, ThisItem->Recipient, 0);
385                 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
386                 StrBufAppendPrintf(QMessage, "%d", ThisItem->Status);
387                 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
388                 StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
389         }
390         DeleteHashPos(&It);
391         StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
392         return QMessage;
393 }
394
395
396
397
398
399 void NewMailQEntry(OneQueItem *Item)
400 {
401         Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
402         memset(Item->Current, 0, sizeof(MailQEntry));
403
404         if (Item->MailQEntries == NULL)
405                 Item->MailQEntries = NewHash(1, Flathash);
406         /* alocate big buffer so we won't get problems reallocating later. */
407         Item->Current->StatusMessage = NewStrBufPlain(NULL, SIZ);
408         Item->Current->n = GetCount(Item->MailQEntries);
409         Put(Item->MailQEntries,
410             IKEY(Item->Current->n),
411             Item->Current,
412             FreeMailQEntry);
413 }
414
415 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
416 {
417         Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
418 }
419
420 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
421 {
422         if (Item->EnvelopeFrom == NULL)
423                 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
424         StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
425 }
426
427 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
428 {
429         if (Item->BounceTo == NULL)
430                 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
431         StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
432 }
433
434 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
435 {
436         if (Item->SenderRoom == NULL)
437                 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
438         StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
439 }
440
441 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
442 {
443         if (Item->Current == NULL)
444                 NewMailQEntry(Item);
445         if (Item->Current->Recipient == NULL)
446                 Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
447         StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
448         Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
449         StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
450         Item->Current = NULL; // TODO: is this always right?
451 }
452
453
454 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
455 {
456         Item->Retry =
457                 StrBufExtractNext_int(Line, Pos, '|');
458         if (Item->Retry == 0)
459                 Item->Retry = SMTP_RETRY_INTERVAL;
460         else
461                 Item->Retry *= 2;
462 }
463
464
465 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
466 {
467         Item->Submitted = atol(*Pos);
468
469 }
470
471 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
472 {
473         Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
474 }
475
476
477
478 /**
479  * this one has to have the context for loading the message via the redirect buffer...
480  */
481 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
482 {
483         CitContext *CCC=CC;
484         StrBuf *SendMsg;
485
486         CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
487         CtdlOutputMsg(MyQItem->MessageID,
488                       MT_RFC822, HEADERS_ALL,
489                       0, 1, NULL,
490                       (ESC_DOT|SUPPRESS_ENV_TO) );
491
492         SendMsg = CCC->redirect_buffer;
493         CCC->redirect_buffer = NULL;
494         if ((StrLength(SendMsg) > 0) &&
495             ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
496                 SMTPC_syslog(LOG_WARNING,
497                              "[%d] Possible problem: message did not "
498                              "correctly terminate. (expecting 0x10, got 0x%02x)\n",
499                              MsgCount, //yes uncool, but best choice here...
500                              ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
501                 StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
502         }
503         return SendMsg;
504 }
505
506
507
508 /*
509  * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
510  * instructions for "5" codes (permanent fatal errors) and produce/deliver
511  * a "bounce" message (delivery status notification).
512  */
513 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt, ParsedURL *Relay)
514 {
515         static int seq = 0;
516
517         struct CtdlMessage *bmsg = NULL;
518         StrBuf *boundary;
519         StrBuf *Msg = NULL;
520         StrBuf *BounceMB;
521         struct recptypes *valid;
522         time_t now;
523
524         HashPos *It;
525         void *vQE;
526         long len;
527         const char *Key;
528
529         int first_attempt = 0;
530         int successful_bounce = 0;
531         int num_bounces = 0;
532         int give_up = 0;
533
534         SMTPCM_syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
535
536         if (MyQItem->SendBounceMail == 0)
537                 return;
538
539         now = time (NULL); //ev_time();
540
541         if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
542                 give_up = 1;
543         }
544
545         if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
546                 first_attempt = 1;
547         }
548
549         /*
550          * Now go through the instructions checking for stuff.
551          */
552         Msg = NewStrBufPlain(NULL, 1024);
553         It = GetNewHashPos(MyQItem->MailQEntries, 0);
554         while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
555         {
556                 MailQEntry *ThisItem = vQE;
557                 if ((ThisItem->Active && (ThisItem->Status == 5)) || /* failed now? */
558                     ((give_up == 1) && (ThisItem->Status != 2)) ||
559                     ((first_attempt == 1) && (ThisItem->Status != 2)))
560                         /* giving up after failed attempts... */
561                 {
562                         ++num_bounces;
563
564                         StrBufAppendBufPlain(Msg, HKEY(" "), 0);
565                         StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
566                         StrBufAppendBufPlain(Msg, HKEY(": "), 0);
567                         StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
568                         StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
569                 }
570         }
571         DeleteHashPos(&It);
572
573         /* Deliver the bounce if there's anything worth mentioning */
574         SMTPC_syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
575
576         if (num_bounces == 0) {
577                 FreeStrBuf(&Msg);
578                 return;
579         }
580
581         if ((StrLength(MyQItem->SenderRoom) == 0) && MyQItem->HaveRelay) {
582                 /* one message that relaying is broken is enough; no extra room error message. */
583                 StrBuf *RelayDetails = NewStrBuf();
584
585                 StrBufPrintf(RelayDetails,
586                              "Relaying via %s failed permanently. \n Reason:\n%s\n Revalidate your relay configuration.",
587                              ChrPtr(Relay->URL),
588                              ChrPtr(Msg));
589                 CtdlAideMessage(ChrPtr(RelayDetails), "Relaying Failed");
590                 FreeStrBuf(&RelayDetails);
591         }
592
593         boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
594         StrBufAppendPrintf(boundary,
595                            "%s_%04x%04x",
596                            config.c_fqdn,
597                            getpid(),
598                            ++seq);
599
600         /* Start building our bounce message; go shopping for memory first. */
601         BounceMB = NewStrBufPlain(
602                 NULL,
603                 1024 + /* mime stuff.... */
604                 StrLength(Msg) +  /* the bounce information... */
605                 StrLength(OMsgTxt)); /* the original message */
606         if (BounceMB == NULL) {
607                 FreeStrBuf(&boundary);
608                 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
609
610                 return;
611         }
612
613         bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
614         if (bmsg == NULL) {
615                 FreeStrBuf(&boundary);
616                 FreeStrBuf(&BounceMB);
617                 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
618
619                 return;
620         }
621         memset(bmsg, 0, sizeof(struct CtdlMessage));
622
623
624         StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
625         StrBufAppendBuf(BounceMB, boundary, 0);
626         StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
627         StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
628         StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
629         StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
630         StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
631         StrBufAppendBuf(BounceMB, boundary, 0);
632         StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
633         StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
634
635         if (give_up)
636                 StrBufAppendBufPlain(
637                         BounceMB,
638                         HKEY(
639                                 "A message you sent could not be delivered "
640                                 "to some or all of its recipients\n"
641                                 "due to prolonged unavailability "
642                                 "of its destination(s).\n"
643                                 "Giving up on the following addresses:\n\n"
644                                 ), 0);
645         else
646                 StrBufAppendBufPlain(
647                         BounceMB,
648                         HKEY(
649                                 "A message you sent could not be delivered "
650                                 "to some or all of its recipients.\n"
651                                 "The following addresses "
652                                 "were undeliverable:\n\n"
653                                 ), 0);
654
655         StrBufAppendBuf(BounceMB, Msg, 0);
656         FreeStrBuf(&Msg);
657
658         if (StrLength(MyQItem->SenderRoom) > 0)
659         {
660                 StrBufAppendBufPlain(
661                         BounceMB,
662                         HKEY("The message was originaly posted in: "), 0);
663                 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
664                 StrBufAppendBufPlain(
665                         BounceMB,
666                         HKEY("\n"), 0);
667         }
668
669         /* Attach the original message */
670         StrBufAppendBufPlain(BounceMB, HKEY("\r\n--"), 0);
671         StrBufAppendBuf(BounceMB, boundary, 0);
672         StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
673         StrBufAppendBufPlain(BounceMB,
674                              HKEY("Content-type: message/rfc822\r\n"), 0);
675         StrBufAppendBufPlain(BounceMB,
676                              HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
677         StrBufAppendBufPlain(BounceMB,
678                              HKEY("Content-Disposition: inline\r\n"), 0);
679         StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
680         StrBufAppendBuf(BounceMB, OMsgTxt, 0);
681
682         /* Close the multipart MIME scope */
683         StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
684         StrBufAppendBuf(BounceMB, boundary, 0);
685         StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
686
687         bmsg->cm_magic = CTDLMESSAGE_MAGIC;
688         bmsg->cm_anon_type = MES_NORMAL;
689         bmsg->cm_format_type = FMT_RFC822;
690
691         bmsg->cm_fields['O'] = strdup(MAILROOM);
692         bmsg->cm_fields['A'] = strdup("Citadel");
693         bmsg->cm_fields['N'] = strdup(config.c_nodename);
694         bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
695         bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
696
697         /* First try the user who sent the message */
698         if (StrLength(MyQItem->BounceTo) == 0) {
699                 SMTPCM_syslog(LOG_ERR, "No bounce address specified\n");
700         }
701         else {
702                 SMTPC_syslog(LOG_DEBUG, "bounce to user? <%s>\n",
703                        ChrPtr(MyQItem->BounceTo));
704         }
705
706         /* Can we deliver the bounce to the original sender? */
707         valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
708         if ((valid != NULL) && (valid->num_error == 0)) {
709                 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
710                 successful_bounce = 1;
711         }
712
713         /* If not, post it in the Aide> room */
714         if (successful_bounce == 0) {
715                 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
716         }
717
718         /* Free up the memory we used */
719         free_recipients(valid);
720         FreeStrBuf(&boundary);
721         CtdlFreeMessage(bmsg);
722         SMTPCM_syslog(LOG_DEBUG, "Done processing bounces\n");
723 }
724
725 /*
726  * smtp_do_procmsg()
727  *
728  * Called by smtp_do_queue() to handle an individual message.
729  */
730 void smtp_do_procmsg(long msgnum, void *userdata) {
731         time_t now;
732         int mynumsessions = num_sessions;
733         struct CtdlMessage *msg = NULL;
734         char *instr = NULL;
735         StrBuf *PlainQItem;
736         OneQueItem *MyQItem;
737         char *pch;
738         HashPos  *It;
739         void *vQE;
740         long len;
741         const char *Key;
742         int nRelays = 0;
743         ParsedURL *RelayUrls = NULL;
744         int HaveBuffers = 0;
745         StrBuf *Msg =NULL;
746
747         if (mynumsessions > max_sessions_for_outbound_smtp) {
748                 SMTPC_syslog(LOG_DEBUG,
749                              "skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
750                              mynumsessions,
751                              max_sessions_for_outbound_smtp);
752         }
753
754         SMTPC_syslog(LOG_DEBUG, "smtp_do_procmsg(%ld)\n", msgnum);
755         ///strcpy(envelope_from, "");
756
757         msg = CtdlFetchMessage(msgnum, 1);
758         if (msg == NULL) {
759                 SMTPC_syslog(LOG_ERR, "tried %ld but no such message!\n",
760                        msgnum);
761                 return;
762         }
763
764         pch = instr = msg->cm_fields['M'];
765
766         /* Strip out the headers (no not amd any other non-instruction) line */
767         while (pch != NULL) {
768                 pch = strchr(pch, '\n');
769                 if ((pch != NULL) && (*(pch + 1) == '\n')) {
770                         instr = pch + 2;
771                         pch = NULL;
772                 }
773         }
774         PlainQItem = NewStrBufPlain(instr, -1);
775         CtdlFreeMessage(msg);
776         MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
777         FreeStrBuf(&PlainQItem);
778
779         if (MyQItem == NULL) {
780                 SMTPC_syslog(LOG_ERR,
781                              "Msg No %ld: already in progress!\n",
782                              msgnum);
783                 return; /* s.b. else is already processing... */
784         }
785
786         /*
787          * Postpone delivery if we've already tried recently.
788          */
789         now = time(NULL);
790         if ((MyQItem->ReattemptWhen != 0) && 
791             (now < MyQItem->ReattemptWhen) &&
792             (run_queue_now == 0))
793         {
794                 SMTPC_syslog(LOG_DEBUG, 
795                              "Retry time not yet reached. %ld seconds left.",
796                              MyQItem->ReattemptWhen - now);
797
798                 It = GetNewHashPos(MyQItem->MailQEntries, 0);
799                 pthread_mutex_lock(&ActiveQItemsLock);
800                 {
801                         if (GetHashPosFromKey(ActiveQItems,
802                                               LKEY(MyQItem->MessageID),
803                                               It))
804                         {
805                                 DeleteEntryFromHash(ActiveQItems, It);
806                         }
807                 }
808                 pthread_mutex_unlock(&ActiveQItemsLock);
809                 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
810                 DeleteHashPos(&It);
811                 return;
812         }
813
814         /*
815          * Bail out if there's no actual message associated with this
816          */
817         if (MyQItem->MessageID < 0L) {
818                 SMTPCM_syslog(LOG_ERR, "no 'msgid' directive found!\n");
819                 It = GetNewHashPos(MyQItem->MailQEntries, 0);
820                 pthread_mutex_lock(&ActiveQItemsLock);
821                 {
822                         if (GetHashPosFromKey(ActiveQItems,
823                                               LKEY(MyQItem->MessageID),
824                                               It))
825                         {
826                                 DeleteEntryFromHash(ActiveQItems, It);
827                         }
828                 }
829                 pthread_mutex_unlock(&ActiveQItemsLock);
830                 DeleteHashPos(&It);
831                 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
832                 return;
833         }
834
835         {
836                 char mxbuf[SIZ];
837                 ParsedURL **Url = &MyQItem->URL;
838                 nRelays = get_hosts(mxbuf, "fallbackhost");
839                 if (nRelays > 0) {
840                         StrBuf *All;
841                         StrBuf *One;
842                         const char *Pos = NULL;
843                         All = NewStrBufPlain(mxbuf, -1);
844                         One = NewStrBufPlain(NULL, StrLength(All) + 1);
845
846                         while ((Pos != StrBufNOTNULL) &&
847                                ((Pos == NULL) ||
848                                 !IsEmptyStr(Pos)))
849                         {
850                                 StrBufExtract_NextToken(One, All, &Pos, '|');
851                                 if (!ParseURL(Url, One, DefaultMXPort)) {
852                                         SMTPC_syslog(LOG_DEBUG,
853                                                      "Failed to parse: %s\n",
854                                                      ChrPtr(One));
855                                 }
856                                 else {
857                                         (*Url)->IsRelay = 1;
858                                         MyQItem->HaveRelay = 1;
859                                 }
860                         }
861                         FreeStrBuf(&All);
862                         FreeStrBuf(&One);
863                 }
864                 nRelays = get_hosts(mxbuf, "smarthost");
865                 if (nRelays > 0) {
866                         StrBuf *All;
867                         StrBuf *One;
868                         const char *Pos = NULL;
869                         All = NewStrBufPlain(mxbuf, -1);
870                         One = NewStrBufPlain(NULL, StrLength(All) + 1);
871
872                         while ((Pos != StrBufNOTNULL) &&
873                                ((Pos == NULL) ||
874                                 !IsEmptyStr(Pos)))
875                         {
876                                 StrBufExtract_NextToken(One, All, &Pos, '|');
877                                 if (!ParseURL(Url, One, DefaultMXPort)) {
878                                         SMTPC_syslog(LOG_DEBUG,
879                                                      "Failed to parse: %s\n",
880                                                      ChrPtr(One));
881                                 }
882                                 else {
883                                         ///if (!Url->IsIP)) // todo dupe me fork ipv6
884                                         (*Url)->IsRelay = 1;
885                                         MyQItem->HaveRelay = 1;
886                                 }
887                         }
888                         FreeStrBuf(&All);
889                         FreeStrBuf(&One);
890                 }
891
892         }
893
894         It = GetNewHashPos(MyQItem->MailQEntries, 0);
895         while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
896         {
897                 MailQEntry *ThisItem = vQE;
898                 SMTPC_syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
899                              ChrPtr(ThisItem->Recipient),
900                              ThisItem->Active);
901         }
902         DeleteHashPos(&It);
903
904         MyQItem->NotYetShutdownDeliveries = 
905                 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem, 1);
906
907         /* failsafe against overload: 
908          * will we exceed the limit set? 
909          */
910         if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) && 
911             /* if yes, did we reach more than half of the quota? */
912             ((mynumsessions * 2) > max_sessions_for_outbound_smtp) && 
913             /* if... would we ever fit into half of the quota?? */
914             (((MyQItem->ActiveDeliveries * 2)  < max_sessions_for_outbound_smtp)))
915         {
916                 /* abort delivery for another time. */
917                 SMTPC_syslog(LOG_DEBUG,
918                              "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
919                              mynumsessions,
920                              MyQItem->ActiveDeliveries,
921                              max_sessions_for_outbound_smtp);
922
923                 FreeQueItem(&MyQItem);
924
925                 return;
926         }
927
928
929         if (MyQItem->ActiveDeliveries > 0)
930         {
931                 int nActivated = 0;
932                 int n = MsgCount++;
933                 int m = MyQItem->ActiveDeliveries;
934                 int i = 1;
935                 Msg = smtp_load_msg(MyQItem, n);
936                 It = GetNewHashPos(MyQItem->MailQEntries, 0);
937                 while ((i <= m) &&
938                        (GetNextHashPos(MyQItem->MailQEntries,
939                                        It, &len, &Key, &vQE)))
940                 {
941                         MailQEntry *ThisItem = vQE;
942
943                         if (ThisItem->Active == 1)
944                         {
945                                 int KeepBuffers = (i == m);
946
947                                 nActivated++;
948                                 if (nActivated % ndelay_count == 0)
949                                         usleep(delay_msec);
950
951                                 if (i > 1) n = MsgCount++;
952                                 syslog(LOG_DEBUG,
953                                        "SMTPC: Trying <%ld> <%s> %d / %d \n",
954                                        MyQItem->MessageID,
955                                        ChrPtr(ThisItem->Recipient),
956                                        i,
957                                        m);
958                                 (*((int*) userdata)) ++;
959                                 smtp_try_one_queue_entry(MyQItem,
960                                                          ThisItem,
961                                                          Msg,
962                                                          KeepBuffers,
963                                                          n,
964                                                          RelayUrls);
965
966                                 if (KeepBuffers) HaveBuffers = 1;
967
968                                 i++;
969                         }
970                 }
971                 DeleteHashPos(&It);
972         }
973         else
974         {
975                 It = GetNewHashPos(MyQItem->MailQEntries, 0);
976                 pthread_mutex_lock(&ActiveQItemsLock);
977                 {
978                         if (GetHashPosFromKey(ActiveQItems,
979                                               LKEY(MyQItem->MessageID),
980                                               It))
981                         {
982                                 DeleteEntryFromHash(ActiveQItems, It);
983                         }
984                         else
985                         {
986                                 long len;
987                                 const char* Key;
988                                 void *VData;
989
990                                 SMTPC_syslog(LOG_WARNING,
991                                              "unable to find QItem with ID[%ld]",
992                                              MyQItem->MessageID);
993                                 while (GetNextHashPos(ActiveQItems,
994                                                       It,
995                                                       &len,
996                                                       &Key,
997                                                       &VData))
998                                 {
999                                         SMTPC_syslog(LOG_WARNING,
1000                                                      "have: ID[%ld]",
1001                                                      ((OneQueItem *)VData)->MessageID);
1002                                 }
1003                         }
1004
1005                 }
1006                 pthread_mutex_unlock(&ActiveQItemsLock);
1007                 DeleteHashPos(&It);
1008                 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
1009
1010 // TODO: bounce & delete?
1011
1012         }
1013         if (!HaveBuffers) {
1014                 FreeStrBuf (&Msg);
1015 // TODO : free RelayUrls
1016         }
1017 }
1018
1019
1020
1021 /*
1022  * smtp_queue_thread()
1023  *
1024  * Run through the queue sending out messages.
1025  */
1026 void smtp_do_queue(void) {
1027         int num_processed = 0;
1028         int num_activated = 0;
1029
1030         pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
1031         SMTPCM_syslog(LOG_INFO, "processing outbound queue");
1032
1033         if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
1034                 SMTPC_syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
1035         }
1036         else {
1037                 num_processed = CtdlForEachMessage(MSGS_ALL,
1038                                                    0L,
1039                                                    NULL,
1040                                                    SPOOLMIME,
1041                                                    NULL,
1042                                                    smtp_do_procmsg,
1043                                                    &num_activated);
1044         }
1045         SMTPC_syslog(LOG_INFO,
1046                      "queue run completed; %d messages processed %d activated",
1047                      num_processed, num_activated);
1048
1049 }
1050
1051
1052
1053 /*
1054  * Initialize the SMTP outbound queue
1055  */
1056 void smtp_init_spoolout(void) {
1057         struct ctdlroom qrbuf;
1058
1059         /*
1060          * Create the room.  This will silently fail if the room already
1061          * exists, and that's perfectly ok, because we want it to exist.
1062          */
1063         CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1064
1065         /*
1066          * Make sure it's set to be a "system room" so it doesn't show up
1067          * in the <K>nown rooms list for Aides.
1068          */
1069         if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1070                 qrbuf.QRflags2 |= QR2_SYSTEM;
1071                 CtdlPutRoomLock(&qrbuf);
1072         }
1073 }
1074
1075
1076
1077
1078 /*****************************************************************************/
1079 /*                          SMTP UTILITY COMMANDS                            */
1080 /*****************************************************************************/
1081
1082 void cmd_smtp(char *argbuf) {
1083         char cmd[64];
1084         char node[256];
1085         char buf[1024];
1086         int i;
1087         int num_mxhosts;
1088
1089         if (CtdlAccessCheck(ac_aide)) return;
1090
1091         extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1092
1093         if (!strcasecmp(cmd, "mx")) {
1094                 extract_token(node, argbuf, 1, '|', sizeof node);
1095                 num_mxhosts = getmx(buf, node);
1096                 cprintf("%d %d MX hosts listed for %s\n",
1097                         LISTING_FOLLOWS, num_mxhosts, node);
1098                 for (i=0; i<num_mxhosts; ++i) {
1099                         extract_token(node, buf, i, '|', sizeof node);
1100                         cprintf("%s\n", node);
1101                 }
1102                 cprintf("000\n");
1103                 return;
1104         }
1105
1106         else if (!strcasecmp(cmd, "runqueue")) {
1107                 run_queue_now = 1;
1108                 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1109                 return;
1110         }
1111
1112         else {
1113                 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1114         }
1115
1116 }
1117
1118
1119 CTDL_MODULE_INIT(smtp_queu)
1120 {
1121         char *pstr;
1122
1123         if (!threading)
1124         {
1125                 pstr = getenv("CITSERVER_n_session_max");
1126                 if ((pstr != NULL) && (*pstr != '\0'))
1127                         max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1128
1129                 pstr = getenv("CITSERVER_smtp_n_delay_count");
1130                 if ((pstr != NULL) && (*pstr != '\0'))
1131                         ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1132
1133                 pstr = getenv("CITSERVER_smtp_delay");
1134                 if ((pstr != NULL) && (*pstr != '\0'))
1135                         delay_msec = atol(pstr) * 1000; /* this many seconds. */
1136
1137
1138
1139
1140                 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1141                 ActiveQItems = NewHash(1, lFlathash);
1142                 pthread_mutex_init(&ActiveQItemsLock, NULL);
1143
1144                 QItemHandlers = NewHash(0, NULL);
1145
1146                 RegisterQItemHandler(HKEY("msgid"),             QItem_Handle_MsgID);
1147                 RegisterQItemHandler(HKEY("envelope_from"),     QItem_Handle_EnvelopeFrom);
1148                 RegisterQItemHandler(HKEY("retry"),             QItem_Handle_retry);
1149                 RegisterQItemHandler(HKEY("attempted"),         QItem_Handle_Attempted);
1150                 RegisterQItemHandler(HKEY("remote"),            QItem_Handle_Recipient);
1151                 RegisterQItemHandler(HKEY("bounceto"),          QItem_Handle_BounceTo);
1152                 RegisterQItemHandler(HKEY("source_room"),       QItem_Handle_SenderRoom);
1153                 RegisterQItemHandler(HKEY("submitted"),         QItem_Handle_Submitted);
1154
1155                 smtp_init_spoolout();
1156
1157                 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1158
1159                 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1160                 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER, PRIO_SEND + 10);
1161         }
1162
1163         /* return our Subversion id for the Log */
1164         return "smtpeventclient";
1165 }