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;
493 int first_attempt = 0;
494 int successful_bounce = 0;
498 syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
500 if (MyQItem->SendBounceMail == 0)
505 if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
509 if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
514 * Now go through the instructions checking for stuff.
516 Msg = NewStrBufPlain(NULL, 1024);
517 It = GetNewHashPos(MyQItem->MailQEntries, 0);
518 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
520 MailQEntry *ThisItem = vQE;
521 if ((ThisItem->Active && (ThisItem->Status == 5)) || /* failed now? */
522 ((give_up == 1) && (ThisItem->Status != 2)) ||
523 ((first_attempt == 1) && (ThisItem->Status != 2)))
524 /* giving up after failed attempts... */
528 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
529 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
530 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
531 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
536 /* Deliver the bounce if there's anything worth mentioning */
537 syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
539 if (num_bounces == 0) {
544 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
545 StrBufAppendPrintf(boundary,
551 /* Start building our bounce message; go shopping for memory first. */
552 BounceMB = NewStrBufPlain(
554 1024 + /* mime stuff.... */
555 StrLength(Msg) + /* the bounce information... */
556 StrLength(OMsgTxt)); /* the original message */
557 if (BounceMB == NULL) {
558 FreeStrBuf(&boundary);
559 syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
564 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
566 FreeStrBuf(&boundary);
567 FreeStrBuf(&BounceMB);
568 syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
572 memset(bmsg, 0, sizeof(struct CtdlMessage));
575 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
576 StrBufAppendBuf(BounceMB, boundary, 0);
577 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
578 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
579 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
580 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
581 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
582 StrBufAppendBuf(BounceMB, boundary, 0);
583 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
584 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
587 StrBufAppendBufPlain(
590 "A message you sent could not be delivered "
591 "to some or all of its recipients\n"
592 "due to prolonged unavailability "
593 "of its destination(s).\n"
594 "Giving up on the following addresses:\n\n"
597 StrBufAppendBufPlain(
600 "A message you sent could not be delivered "
601 "to some or all of its recipients.\n"
602 "The following addresses "
603 "were undeliverable:\n\n"
606 StrBufAppendBuf(BounceMB, Msg, 0);
609 if (StrLength(MyQItem->SenderRoom) > 0)
611 StrBufAppendBufPlain(
613 HKEY("The message was originaly posted in: "), 0);
614 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
615 StrBufAppendBufPlain(
620 /* Attach the original message */
621 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
622 StrBufAppendBuf(BounceMB, boundary, 0);
623 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
624 StrBufAppendBufPlain(BounceMB,
625 HKEY("Content-type: message/rfc822\r\n"), 0);
626 StrBufAppendBufPlain(BounceMB,
627 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
628 StrBufAppendBufPlain(BounceMB,
629 HKEY("Content-Disposition: inline\r\n"), 0);
630 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
631 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
633 /* Close the multipart MIME scope */
634 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
635 StrBufAppendBuf(BounceMB, boundary, 0);
636 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
638 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
639 bmsg->cm_anon_type = MES_NORMAL;
640 bmsg->cm_format_type = FMT_RFC822;
642 bmsg->cm_fields['O'] = strdup(MAILROOM);
643 bmsg->cm_fields['A'] = strdup("Citadel");
644 bmsg->cm_fields['N'] = strdup(config.c_nodename);
645 bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
646 bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
648 /* First try the user who sent the message */
649 if (StrLength(MyQItem->BounceTo) == 0)
650 syslog(LOG_ERR, "No bounce address specified\n");
652 syslog(LOG_DEBUG, "bounce to user? <%s>\n",
653 ChrPtr(MyQItem->BounceTo));
655 /* Can we deliver the bounce to the original sender? */
656 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
657 if ((valid != NULL) && (valid->num_error == 0)) {
658 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
659 successful_bounce = 1;
662 /* If not, post it in the Aide> room */
663 if (successful_bounce == 0) {
664 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
667 /* Free up the memory we used */
668 free_recipients(valid);
669 FreeStrBuf(&boundary);
670 CtdlFreeMessage(bmsg);
671 syslog(LOG_DEBUG, "Done processing bounces\n");
677 * Called by smtp_do_queue() to handle an individual message.
679 void smtp_do_procmsg(long msgnum, void *userdata) {
680 int mynumsessions = num_sessions;
681 struct CtdlMessage *msg = NULL;
691 ParsedURL *RelayUrls = NULL;
695 if (mynumsessions > max_sessions_for_outbound_smtp) {
697 "SMTP Queue: skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
699 max_sessions_for_outbound_smtp);
702 syslog(LOG_DEBUG, "SMTP Queue: smtp_do_procmsg(%ld)\n", msgnum);
703 ///strcpy(envelope_from, "");
705 msg = CtdlFetchMessage(msgnum, 1);
707 syslog(LOG_ERR, "SMTP Queue: tried %ld but no such message!\n",
712 pch = instr = msg->cm_fields['M'];
714 /* Strip out the headers (no not amd any other non-instruction) line */
715 while (pch != NULL) {
716 pch = strchr(pch, '\n');
717 if ((pch != NULL) && (*(pch + 1) == '\n')) {
722 PlainQItem = NewStrBufPlain(instr, -1);
723 CtdlFreeMessage(msg);
724 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
725 FreeStrBuf(&PlainQItem);
727 if (MyQItem == NULL) {
729 "SMTP Queue: Msg No %ld: already in progress!\n",
731 return; /* s.b. else is already processing... */
735 * Postpone delivery if we've already tried recently.
737 if ((MyQItem->ReattemptWhen != 0) &&
738 (time(NULL) < MyQItem->ReattemptWhen) &&
739 (run_queue_now == 0))
741 syslog(LOG_DEBUG, "SMTP client: Retry time not yet reached.\n");
743 It = GetNewHashPos(MyQItem->MailQEntries, 0);
744 pthread_mutex_lock(&ActiveQItemsLock);
746 if (GetHashPosFromKey(ActiveQItems,
747 LKEY(MyQItem->MessageID),
750 DeleteEntryFromHash(ActiveQItems, It);
753 pthread_mutex_unlock(&ActiveQItemsLock);
754 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
760 * Bail out if there's no actual message associated with this
762 if (MyQItem->MessageID < 0L) {
763 syslog(LOG_ERR, "SMTP Queue: no 'msgid' directive found!\n");
764 It = GetNewHashPos(MyQItem->MailQEntries, 0);
765 pthread_mutex_lock(&ActiveQItemsLock);
767 if (GetHashPosFromKey(ActiveQItems,
768 LKEY(MyQItem->MessageID),
771 DeleteEntryFromHash(ActiveQItems, It);
774 pthread_mutex_unlock(&ActiveQItemsLock);
776 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
782 ParsedURL **Url = &MyQItem->URL;
783 nRelays = get_hosts(mxbuf, "smarthost");
787 const char *Pos = NULL;
788 All = NewStrBufPlain(mxbuf, -1);
789 One = NewStrBufPlain(NULL, StrLength(All) + 1);
791 while ((Pos != StrBufNOTNULL) &&
795 StrBufExtract_NextToken(One, All, &Pos, '|');
796 if (!ParseURL(Url, One, 25))
798 "Failed to parse: %s\n",
801 ///if (!Url->IsIP)) // todo dupe me fork ipv6
809 Url = &MyQItem->FallBackHost;
810 nRelays = get_hosts(mxbuf, "fallbackhost");
814 const char *Pos = NULL;
815 All = NewStrBufPlain(mxbuf, -1);
816 One = NewStrBufPlain(NULL, StrLength(All) + 1);
818 while ((Pos != StrBufNOTNULL) &&
822 StrBufExtract_NextToken(One, All, &Pos, '|');
823 if (!ParseURL(Url, One, 25))
825 "Failed to parse: %s\n",
835 It = GetNewHashPos(MyQItem->MailQEntries, 0);
836 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
838 MailQEntry *ThisItem = vQE;
839 syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
840 ChrPtr(ThisItem->Recipient),
845 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem);
847 /* failsafe against overload:
848 * will we exceed the limit set?
850 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
851 /* if yes, did we reach more than half of the quota? */
852 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
853 /* if... would we ever fit into half of the quota?? */
854 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
856 /* abort delivery for another time. */
858 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
860 MyQItem->ActiveDeliveries,
861 max_sessions_for_outbound_smtp);
863 FreeQueItem(&MyQItem);
869 if (MyQItem->ActiveDeliveries > 0)
873 int m = MyQItem->ActiveDeliveries;
875 Msg = smtp_load_msg(MyQItem, n);
876 It = GetNewHashPos(MyQItem->MailQEntries, 0);
878 (GetNextHashPos(MyQItem->MailQEntries,
879 It, &len, &Key, &vQE)))
881 MailQEntry *ThisItem = vQE;
883 if (ThisItem->Active == 1)
885 int KeepBuffers = (i == m);
888 if (nActivated % ndelay_count == 0)
891 if (i > 1) n = MsgCount++;
893 "SMTPQ: Trying <%ld> <%s> %d / %d \n",
895 ChrPtr(ThisItem->Recipient),
898 smtp_try_one_queue_entry(MyQItem,
905 if (KeepBuffers) HaveBuffers = 1;
914 It = GetNewHashPos(MyQItem->MailQEntries, 0);
915 pthread_mutex_lock(&ActiveQItemsLock);
917 if (GetHashPosFromKey(ActiveQItems,
918 LKEY(MyQItem->MessageID),
921 DeleteEntryFromHash(ActiveQItems, It);
930 "SMTP cleanup: unable to find "
931 "QItem with ID[%ld]",
933 while (GetNextHashPos(ActiveQItems,
940 "SMTP cleanup: have: ID[%ld]",
941 ((OneQueItem *)VData)->MessageID);
946 pthread_mutex_unlock(&ActiveQItemsLock);
948 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
950 // TODO: bounce & delete?
955 // TODO : free RelayUrls
962 * smtp_queue_thread()
964 * Run through the queue sending out messages.
966 void smtp_do_queue(void) {
967 static int is_running = 0;
968 int num_processed = 0;
971 return; /* Concurrency check - only one can run */
974 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
975 syslog(LOG_INFO, "SMTP client: processing outbound queue");
977 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
978 syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
981 num_processed = CtdlForEachMessage(MSGS_ALL,
990 "SMTP client: queue run completed; %d messages processed",
1000 * Initialize the SMTP outbound queue
1002 void smtp_init_spoolout(void) {
1003 struct ctdlroom qrbuf;
1006 * Create the room. This will silently fail if the room already
1007 * exists, and that's perfectly ok, because we want it to exist.
1009 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1012 * Make sure it's set to be a "system room" so it doesn't show up
1013 * in the <K>nown rooms list for Aides.
1015 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1016 qrbuf.QRflags2 |= QR2_SYSTEM;
1017 CtdlPutRoomLock(&qrbuf);
1024 /*****************************************************************************/
1025 /* SMTP UTILITY COMMANDS */
1026 /*****************************************************************************/
1028 void cmd_smtp(char *argbuf) {
1035 if (CtdlAccessCheck(ac_aide)) return;
1037 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1039 if (!strcasecmp(cmd, "mx")) {
1040 extract_token(node, argbuf, 1, '|', sizeof node);
1041 num_mxhosts = getmx(buf, node);
1042 cprintf("%d %d MX hosts listed for %s\n",
1043 LISTING_FOLLOWS, num_mxhosts, node);
1044 for (i=0; i<num_mxhosts; ++i) {
1045 extract_token(node, buf, i, '|', sizeof node);
1046 cprintf("%s\n", node);
1052 else if (!strcasecmp(cmd, "runqueue")) {
1054 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1059 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1065 CTDL_MODULE_INIT(smtp_queu)
1071 pstr = getenv("CITSERVER_n_session_max");
1072 if ((pstr != NULL) && (*pstr != '\0'))
1073 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1075 pstr = getenv("CITSERVER_smtp_n_delay_count");
1076 if ((pstr != NULL) && (*pstr != '\0'))
1077 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1079 pstr = getenv("CITSERVER_smtp_delay");
1080 if ((pstr != NULL) && (*pstr != '\0'))
1081 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1086 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1087 ActiveQItems = NewHash(1, lFlathash);
1088 pthread_mutex_init(&ActiveQItemsLock, NULL);
1090 QItemHandlers = NewHash(0, NULL);
1092 Put(QItemHandlers, HKEY("msgid"), QItem_Handle_MsgID, reference_free_handler);
1093 Put(QItemHandlers, HKEY("envelope_from"), QItem_Handle_EnvelopeFrom, reference_free_handler);
1094 Put(QItemHandlers, HKEY("retry"), QItem_Handle_retry, reference_free_handler);
1095 Put(QItemHandlers, HKEY("attempted"), QItem_Handle_Attempted, reference_free_handler);
1096 Put(QItemHandlers, HKEY("remote"), QItem_Handle_Recipient, reference_free_handler);
1097 Put(QItemHandlers, HKEY("bounceto"), QItem_Handle_BounceTo, reference_free_handler);
1098 Put(QItemHandlers, HKEY("source_room"), QItem_Handle_SenderRoom, reference_free_handler);
1099 Put(QItemHandlers, HKEY("submitted"), QItem_Handle_Submitted, reference_free_handler);
1100 smtp_init_spoolout();
1102 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1104 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1105 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER);
1108 /* return our Subversion id for the Log */
1109 return "smtpeventclient";