2 * This module is an SMTP and ESMTP implementation for the Citadel system.
3 * It is compliant with all of the following:
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
20 * The VRFY and EXPN commands have been removed from this implementation
21 * because nobody uses these commands anymore, except for spammers.
23 * Copyright (c) 1998-2012 by the citadel.org team
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.
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.
49 #include <sys/types.h>
52 #if TIME_WITH_SYS_TIME
53 # include <sys/time.h>
57 # include <sys/time.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69 #include <libcitadel.h>
72 #include "citserver.h"
79 #include "internet_addressing.h"
82 #include "clientsocket.h"
83 #include "locate_host.h"
84 #include "citadel_dirs.h"
86 #include "ctdl_module.h"
88 #include "smtpqueue.h"
89 #include "event_client.h"
92 struct CitContext smtp_queue_CC;
93 pthread_mutex_t ActiveQItemsLock;
94 HashList *ActiveQItems = NULL;
95 HashList *QItemHandlers = NULL;
96 int max_sessions_for_outbound_smtp = 500; /* how many sessions might be active till we stop adding more smtp jobs */
97 int ndelay_count = 50; /* every n queued messages we will sleep... */
98 int delay_msec = 5000; /* this many seconds. */
100 static const long MaxRetry = SMTP_RETRY_INTERVAL * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
102 int run_queue_now = 0; /* Set to 1 to ignore SMTP send retry times */
104 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
105 MailQEntry *MyQEntry,
107 /* KeepMsgText allows us to use MsgText as ours. */
110 ParsedURL *RelayUrls);
113 void smtp_evq_cleanup(void)
116 pthread_mutex_lock(&ActiveQItemsLock);
117 DeleteHash(&QItemHandlers);
118 DeleteHash(&ActiveQItems);
119 pthread_mutex_unlock(&ActiveQItemsLock);
120 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
121 /* citthread_mutex_destroy(&ActiveQItemsLock); TODO */
124 int DecreaseQReference(OneQueItem *MyQItem)
126 int IDestructQueItem;
128 pthread_mutex_lock(&ActiveQItemsLock);
129 MyQItem->ActiveDeliveries--;
130 IDestructQueItem = MyQItem->ActiveDeliveries == 0;
131 pthread_mutex_unlock(&ActiveQItemsLock);
132 return IDestructQueItem;
135 void RemoveQItem(OneQueItem *MyQItem)
142 pthread_mutex_lock(&ActiveQItemsLock);
143 It = GetNewHashPos(ActiveQItems, 0);
144 if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
145 DeleteEntryFromHash(ActiveQItems, It);
149 "SMTP cleanup: unable to find QItem with ID[%ld]",
151 while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
153 "SMTP cleanup: have_: ID[%ld]",
154 ((OneQueItem *)VData)->MessageID);
156 pthread_mutex_unlock(&ActiveQItemsLock);
161 void FreeMailQEntry(void *qv)
165 syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
168 FreeStrBuf(&Q->Recipient);
169 FreeStrBuf(&Q->StatusMessage);
171 memset(Q, 0, sizeof(MailQEntry));
174 void FreeQueItem(OneQueItem **Item)
177 syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
180 DeleteHash(&(*Item)->MailQEntries);
181 FreeStrBuf(&(*Item)->EnvelopeFrom);
182 FreeStrBuf(&(*Item)->BounceTo);
183 FreeStrBuf(&(*Item)->SenderRoom);
184 FreeURL(&(*Item)->URL);
185 memset(*Item, 0, sizeof(OneQueItem));
189 void HFreeQueItem(void *Item)
191 FreeQueItem((OneQueItem**)&Item);
194 /* inspect recipients with a status of:
195 * - 0 (no delivery yet attempted)
196 * - 3/4 (transient errors
197 * were experienced and it's time to try again)
199 int CheckQEntryActive(MailQEntry *ThisItem)
201 if ((ThisItem->Status == 0) ||
202 (ThisItem->Status == 3) ||
203 (ThisItem->Status == 4))
210 int CheckQEntryIsBounce(MailQEntry *ThisItem)
212 if ((ThisItem->Status == 3) ||
213 (ThisItem->Status == 4) ||
214 (ThisItem->Status == 5))
222 int CountActiveQueueEntries(OneQueItem *MyQItem)
226 long ActiveDeliveries;
230 ActiveDeliveries = 0;
231 It = GetNewHashPos(MyQItem->MailQEntries, 0);
232 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
234 MailQEntry *ThisItem = vQE;
236 if (CheckQEntryActive(ThisItem))
239 ThisItem->Active = 1;
242 ThisItem->Active = 0;
245 return ActiveDeliveries;
248 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
251 const char *pLine = NULL;
256 Item = (OneQueItem*)malloc(sizeof(OneQueItem));
257 memset(Item, 0, sizeof(OneQueItem));
258 Item->Retry = SMTP_RETRY_INTERVAL;
259 Item->MessageID = -1;
260 Item->QueMsgID = QueMsgID;
263 Line = NewStrBufPlain(NULL, 128);
264 while (pLine != StrBufNOTNULL) {
265 const char *pItemPart = NULL;
268 StrBufExtract_NextToken(Line, RawQItem, &pLine, '\n');
269 if (StrLength(Line) == 0) continue;
270 StrBufExtract_NextToken(Token, Line, &pItemPart, '|');
271 if (GetHash(QItemHandlers, SKEY(Token), &vHandler))
274 H = (QItemHandler) vHandler;
275 H(Item, Line, &pItemPart);
281 if (Item->Retry >= MaxRetry)
284 pthread_mutex_lock(&ActiveQItemsLock);
285 if (GetHash(ActiveQItems,
286 LKEY(Item->MessageID),
289 /* WHOOPS. somebody else is already working on this. */
290 pthread_mutex_unlock(&ActiveQItemsLock);
295 /* mark our claim on this. */
297 LKEY(Item->MessageID),
300 pthread_mutex_unlock(&ActiveQItemsLock);
306 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
314 QMessage = NewStrBufPlain(NULL, SIZ);
315 StrBufPrintf(QMessage, "Content-type: %s\n", SPOOLMIME);
316 // "attempted|%ld\n" "retry|%ld\n",, (long)time(NULL), (long)retry );
317 StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
318 StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
320 StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
321 StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
323 if (StrLength(MyQItem->BounceTo) > 0) {
324 StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
325 StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
328 if (StrLength(MyQItem->EnvelopeFrom) > 0) {
329 StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
330 StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
333 if (StrLength(MyQItem->SenderRoom) > 0) {
334 StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
335 StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
338 StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
339 StrBufAppendPrintf(QMessage, "%ld",
342 StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
343 StrBufAppendPrintf(QMessage, "%ld",
344 MyQItem->ReattemptWhen);
346 It = GetNewHashPos(MyQItem->MailQEntries, 0);
347 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
349 MailQEntry *ThisItem = vQE;
351 StrBufAppendBufPlain(QMessage, HKEY("\nremote|"), 0);
352 StrBufAppendBuf(QMessage, ThisItem->Recipient, 0);
353 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
354 StrBufAppendPrintf(QMessage, "%d", ThisItem->Status);
355 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
356 StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
359 StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
367 void NewMailQEntry(OneQueItem *Item)
369 Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
370 memset(Item->Current, 0, sizeof(MailQEntry));
372 if (Item->MailQEntries == NULL)
373 Item->MailQEntries = NewHash(1, Flathash);
374 Item->Current->StatusMessage = NewStrBuf();
375 Item->Current->n = GetCount(Item->MailQEntries);
376 Put(Item->MailQEntries,
377 IKEY(Item->Current->n),
382 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
384 Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
387 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
389 if (Item->EnvelopeFrom == NULL)
390 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
391 StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
394 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
396 if (Item->BounceTo == NULL)
397 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
398 StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
401 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
403 if (Item->SenderRoom == NULL)
404 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
405 StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
408 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
410 if (Item->Current == NULL)
412 if (Item->Current->Recipient == NULL)
413 Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
414 StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
415 Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
416 StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
417 Item->Current = NULL; // TODO: is this always right?
421 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
424 StrBufExtractNext_int(Line, Pos, '|');
429 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
431 Item->Submitted = atol(*Pos);
435 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
437 Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
443 * this one has to have the context for loading the message via the redirect buffer...
445 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
450 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
451 CtdlOutputMsg(MyQItem->MessageID,
452 MT_RFC822, HEADERS_ALL,
454 (ESC_DOT|SUPPRESS_ENV_TO) );
456 SendMsg = CCC->redirect_buffer;
457 CCC->redirect_buffer = NULL;
458 if ((StrLength(SendMsg) > 0) &&
459 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
461 "SMTP client[%d]: Possible problem: message did not "
462 "correctly terminate. (expecting 0x10, got 0x%02x)\n",
463 MsgCount, //yes uncool, but best choice here...
464 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
465 StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
473 * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
474 * instructions for "5" codes (permanent fatal errors) and produce/deliver
475 * a "bounce" message (delivery status notification).
477 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt)
481 struct CtdlMessage *bmsg = NULL;
485 struct recptypes *valid;
492 int successful_bounce = 0;
496 syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
498 if (!MyQItem->SendBounceMail)
501 if ( (ev_time() - MyQItem->Submitted) > SMTP_GIVE_UP ) {
502 give_up = 1;/// TODO: replace time by libevq timer get
506 * Now go through the instructions checking for stuff.
508 It = GetNewHashPos(MyQItem->MailQEntries, 0);
509 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
511 MailQEntry *ThisItem = vQE;
512 if ((ThisItem->Status == 5) || /* failed now? */
514 (ThisItem->Status != 2)))
515 /* giving up after failed attempts... */
517 if (num_bounces == 0)
518 Msg = NewStrBufPlain(NULL, 1024);
521 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
522 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
523 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
524 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
529 /* Deliver the bounce if there's anything worth mentioning */
530 syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
532 if (num_bounces == 0) {
537 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
538 StrBufAppendPrintf(boundary,
544 /* Start building our bounce message; go shopping for memory first. */
545 BounceMB = NewStrBufPlain(
547 1024 + /* mime stuff.... */
548 StrLength(Msg) + /* the bounce information... */
549 StrLength(OMsgTxt)); /* the original message */
550 if (BounceMB == NULL) {
551 FreeStrBuf(&boundary);
552 syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
557 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
559 FreeStrBuf(&boundary);
560 FreeStrBuf(&BounceMB);
561 syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
565 memset(bmsg, 0, sizeof(struct CtdlMessage));
568 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
569 StrBufAppendBuf(BounceMB, boundary, 0);
570 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
571 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
572 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
573 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
574 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
575 StrBufAppendBuf(BounceMB, boundary, 0);
576 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
577 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
580 StrBufAppendBufPlain(
583 "A message you sent could not be delivered "
584 "to some or all of its recipients\n"
585 "due to prolonged unavailability "
586 "of its destination(s).\n"
587 "Giving up on the following addresses:\n\n"
590 StrBufAppendBufPlain(
593 "A message you sent could not be delivered "
594 "to some or all of its recipients.\n"
595 "The following addresses "
596 "were undeliverable:\n\n"
599 StrBufAppendBuf(BounceMB, Msg, 0);
602 if (StrLength(MyQItem->SenderRoom) > 0)
604 StrBufAppendBufPlain(
606 HKEY("The message was originaly posted in: "), 0);
607 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
608 StrBufAppendBufPlain(
613 /* Attach the original message */
614 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
615 StrBufAppendBuf(BounceMB, boundary, 0);
616 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
617 StrBufAppendBufPlain(BounceMB,
618 HKEY("Content-type: message/rfc822\r\n"), 0);
619 StrBufAppendBufPlain(BounceMB,
620 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
621 StrBufAppendBufPlain(BounceMB,
622 HKEY("Content-Disposition: inline\r\n"), 0);
623 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
624 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
626 /* Close the multipart MIME scope */
627 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
628 StrBufAppendBuf(BounceMB, boundary, 0);
629 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
631 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
632 bmsg->cm_anon_type = MES_NORMAL;
633 bmsg->cm_format_type = FMT_RFC822;
635 bmsg->cm_fields['O'] = strdup(MAILROOM);
636 bmsg->cm_fields['A'] = strdup("Citadel");
637 bmsg->cm_fields['N'] = strdup(config.c_nodename);
638 bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
639 bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
641 /* First try the user who sent the message */
642 if (StrLength(MyQItem->BounceTo) == 0)
643 syslog(LOG_ERR, "No bounce address specified\n");
645 syslog(LOG_DEBUG, "bounce to user? <%s>\n",
646 ChrPtr(MyQItem->BounceTo));
648 /* Can we deliver the bounce to the original sender? */
649 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
650 if ((valid != NULL) && (valid->num_error == 0)) {
651 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
652 successful_bounce = 1;
655 /* If not, post it in the Aide> room */
656 if (successful_bounce == 0) {
657 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
660 /* Free up the memory we used */
661 free_recipients(valid);
662 FreeStrBuf(&boundary);
663 CtdlFreeMessage(bmsg);
664 syslog(LOG_DEBUG, "Done processing bounces\n");
670 * Called by smtp_do_queue() to handle an individual message.
672 void smtp_do_procmsg(long msgnum, void *userdata) {
673 int mynumsessions = num_sessions;
674 struct CtdlMessage *msg = NULL;
684 ParsedURL *RelayUrls = NULL;
688 if (mynumsessions > max_sessions_for_outbound_smtp) {
690 "SMTP Queue: skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
692 max_sessions_for_outbound_smtp);
695 syslog(LOG_DEBUG, "SMTP Queue: smtp_do_procmsg(%ld)\n", msgnum);
696 ///strcpy(envelope_from, "");
698 msg = CtdlFetchMessage(msgnum, 1);
700 syslog(LOG_ERR, "SMTP Queue: tried %ld but no such message!\n",
705 pch = instr = msg->cm_fields['M'];
707 /* Strip out the headers (no not amd any other non-instruction) line */
708 while (pch != NULL) {
709 pch = strchr(pch, '\n');
710 if ((pch != NULL) && (*(pch + 1) == '\n')) {
715 PlainQItem = NewStrBufPlain(instr, -1);
716 CtdlFreeMessage(msg);
717 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
718 FreeStrBuf(&PlainQItem);
720 if (MyQItem == NULL) {
722 "SMTP Queue: Msg No %ld: already in progress!\n",
724 return; /* s.b. else is already processing... */
728 * Postpone delivery if we've already tried recently.
730 if ((MyQItem->ReattemptWhen != 0) &&
731 (time(NULL) < MyQItem->ReattemptWhen) &&
732 (run_queue_now == 0))
734 syslog(LOG_DEBUG, "SMTP client: Retry time not yet reached.\n");
736 It = GetNewHashPos(MyQItem->MailQEntries, 0);
737 pthread_mutex_lock(&ActiveQItemsLock);
739 if (GetHashPosFromKey(ActiveQItems,
740 LKEY(MyQItem->MessageID),
743 DeleteEntryFromHash(ActiveQItems, It);
746 pthread_mutex_unlock(&ActiveQItemsLock);
747 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
753 * Bail out if there's no actual message associated with this
755 if (MyQItem->MessageID < 0L) {
756 syslog(LOG_ERR, "SMTP Queue: no 'msgid' directive found!\n");
757 It = GetNewHashPos(MyQItem->MailQEntries, 0);
758 pthread_mutex_lock(&ActiveQItemsLock);
760 if (GetHashPosFromKey(ActiveQItems,
761 LKEY(MyQItem->MessageID),
764 DeleteEntryFromHash(ActiveQItems, It);
767 pthread_mutex_unlock(&ActiveQItemsLock);
769 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
775 ParsedURL **Url = &MyQItem->URL;
776 nRelays = get_hosts(mxbuf, "smarthost");
780 const char *Pos = NULL;
781 All = NewStrBufPlain(mxbuf, -1);
782 One = NewStrBufPlain(NULL, StrLength(All) + 1);
784 while ((Pos != StrBufNOTNULL) &&
788 StrBufExtract_NextToken(One, All, &Pos, '|');
789 if (!ParseURL(Url, One, 25))
791 "Failed to parse: %s\n",
794 ///if (!Url->IsIP)) // todo dupe me fork ipv6
802 Url = &MyQItem->FallBackHost;
803 nRelays = get_hosts(mxbuf, "fallbackhost");
807 const char *Pos = NULL;
808 All = NewStrBufPlain(mxbuf, -1);
809 One = NewStrBufPlain(NULL, StrLength(All) + 1);
811 while ((Pos != StrBufNOTNULL) &&
815 StrBufExtract_NextToken(One, All, &Pos, '|');
816 if (!ParseURL(Url, One, 25))
818 "Failed to parse: %s\n",
828 It = GetNewHashPos(MyQItem->MailQEntries, 0);
829 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
831 MailQEntry *ThisItem = vQE;
832 syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
833 ChrPtr(ThisItem->Recipient),
838 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem);
840 /* failsafe against overload:
841 * will we exceed the limit set?
843 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
844 /* if yes, did we reach more than half of the quota? */
845 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
846 /* if... would we ever fit into half of the quota?? */
847 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
849 /* abort delivery for another time. */
851 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
853 MyQItem->ActiveDeliveries,
854 max_sessions_for_outbound_smtp);
856 FreeQueItem(&MyQItem);
862 if (MyQItem->ActiveDeliveries > 0)
866 int m = MyQItem->ActiveDeliveries;
868 Msg = smtp_load_msg(MyQItem, n);
869 It = GetNewHashPos(MyQItem->MailQEntries, 0);
871 (GetNextHashPos(MyQItem->MailQEntries,
872 It, &len, &Key, &vQE)))
874 MailQEntry *ThisItem = vQE;
876 if (ThisItem->Active == 1)
878 int KeepBuffers = (i == m);
881 if (nActivated % ndelay_count == 0)
884 if (i > 1) n = MsgCount++;
886 "SMTPQ: Trying <%ld> <%s> %d / %d \n",
888 ChrPtr(ThisItem->Recipient),
891 smtp_try_one_queue_entry(MyQItem,
898 if (KeepBuffers) HaveBuffers = 1;
907 It = GetNewHashPos(MyQItem->MailQEntries, 0);
908 pthread_mutex_lock(&ActiveQItemsLock);
910 if (GetHashPosFromKey(ActiveQItems,
911 LKEY(MyQItem->MessageID),
914 DeleteEntryFromHash(ActiveQItems, It);
923 "SMTP cleanup: unable to find "
924 "QItem with ID[%ld]",
926 while (GetNextHashPos(ActiveQItems,
933 "SMTP cleanup: have: ID[%ld]",
934 ((OneQueItem *)VData)->MessageID);
939 pthread_mutex_unlock(&ActiveQItemsLock);
941 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
943 // TODO: bounce & delete?
948 // TODO : free RelayUrls
955 * smtp_queue_thread()
957 * Run through the queue sending out messages.
959 void smtp_do_queue(void) {
960 static int is_running = 0;
961 int num_processed = 0;
964 return; /* Concurrency check - only one can run */
967 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
968 syslog(LOG_INFO, "SMTP client: processing outbound queue");
970 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
971 syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
974 num_processed = CtdlForEachMessage(MSGS_ALL,
983 "SMTP client: queue run completed; %d messages processed",
993 * Initialize the SMTP outbound queue
995 void smtp_init_spoolout(void) {
996 struct ctdlroom qrbuf;
999 * Create the room. This will silently fail if the room already
1000 * exists, and that's perfectly ok, because we want it to exist.
1002 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1005 * Make sure it's set to be a "system room" so it doesn't show up
1006 * in the <K>nown rooms list for Aides.
1008 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1009 qrbuf.QRflags2 |= QR2_SYSTEM;
1010 CtdlPutRoomLock(&qrbuf);
1017 /*****************************************************************************/
1018 /* SMTP UTILITY COMMANDS */
1019 /*****************************************************************************/
1021 void cmd_smtp(char *argbuf) {
1028 if (CtdlAccessCheck(ac_aide)) return;
1030 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1032 if (!strcasecmp(cmd, "mx")) {
1033 extract_token(node, argbuf, 1, '|', sizeof node);
1034 num_mxhosts = getmx(buf, node);
1035 cprintf("%d %d MX hosts listed for %s\n",
1036 LISTING_FOLLOWS, num_mxhosts, node);
1037 for (i=0; i<num_mxhosts; ++i) {
1038 extract_token(node, buf, i, '|', sizeof node);
1039 cprintf("%s\n", node);
1045 else if (!strcasecmp(cmd, "runqueue")) {
1047 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1052 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1058 CTDL_MODULE_INIT(smtp_queu)
1064 pstr = getenv("CITSERVER_n_session_max");
1065 if ((pstr != NULL) && (*pstr != '\0'))
1066 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1068 pstr = getenv("CITSERVER_smtp_n_delay_count");
1069 if ((pstr != NULL) && (*pstr != '\0'))
1070 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1072 pstr = getenv("CITSERVER_smtp_delay");
1073 if ((pstr != NULL) && (*pstr != '\0'))
1074 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1079 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1080 ActiveQItems = NewHash(1, lFlathash);
1081 pthread_mutex_init(&ActiveQItemsLock, NULL);
1083 QItemHandlers = NewHash(0, NULL);
1085 Put(QItemHandlers, HKEY("msgid"), QItem_Handle_MsgID, reference_free_handler);
1086 Put(QItemHandlers, HKEY("envelope_from"), QItem_Handle_EnvelopeFrom, reference_free_handler);
1087 Put(QItemHandlers, HKEY("retry"), QItem_Handle_retry, reference_free_handler);
1088 Put(QItemHandlers, HKEY("attempted"), QItem_Handle_Attempted, reference_free_handler);
1089 Put(QItemHandlers, HKEY("remote"), QItem_Handle_Recipient, reference_free_handler);
1090 Put(QItemHandlers, HKEY("bounceto"), QItem_Handle_BounceTo, reference_free_handler);
1091 Put(QItemHandlers, HKEY("source_room"), QItem_Handle_SenderRoom, reference_free_handler);
1092 Put(QItemHandlers, HKEY("submitted"), QItem_Handle_Submitted, reference_free_handler);
1093 smtp_init_spoolout();
1095 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1097 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1098 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER);
1101 /* return our Subversion id for the Log */
1102 return "smtpeventclient";