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 "smtp_clienthandlers.h"
90 #include "event_client.h"
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. */
102 static const long MaxRetry = SMTP_RETRY_INTERVAL * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
104 int run_queue_now = 0; /* Set to 1 to ignore SMTP send retry times */
106 void RegisterQItemHandler(const char *Key, long Len, QItemHandler H)
108 QItemHandlerStruct *HS = (QItemHandlerStruct*)malloc(sizeof(QItemHandlerStruct));
110 Put(QItemHandlers, Key, Len, HS, NULL);
115 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
116 MailQEntry *MyQEntry,
118 /* KeepMsgText allows us to use MsgText as ours. */
121 ParsedURL *RelayUrls);
124 void smtp_evq_cleanup(void)
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 */
135 int DecreaseQReference(OneQueItem *MyQItem)
137 int IDestructQueItem;
139 pthread_mutex_lock(&ActiveQItemsLock);
140 MyQItem->ActiveDeliveries--;
141 IDestructQueItem = MyQItem->ActiveDeliveries == 0;
142 pthread_mutex_unlock(&ActiveQItemsLock);
143 return IDestructQueItem;
146 void DecreaseShutdownDeliveries(OneQueItem *MyQItem)
148 pthread_mutex_lock(&ActiveQItemsLock);
149 MyQItem->NotYetShutdownDeliveries--;
150 pthread_mutex_unlock(&ActiveQItemsLock);
153 int GetShutdownDeliveries(OneQueItem *MyQItem)
157 pthread_mutex_lock(&ActiveQItemsLock);
158 DestructNow = MyQItem->ActiveDeliveries == 0;
159 pthread_mutex_unlock(&ActiveQItemsLock);
162 void RemoveQItem(OneQueItem *MyQItem)
169 pthread_mutex_lock(&ActiveQItemsLock);
170 It = GetNewHashPos(ActiveQItems, 0);
171 if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
172 DeleteEntryFromHash(ActiveQItems, It);
175 SMTPC_syslog(LOG_WARNING,
176 "unable to find QItem with ID[%ld]",
178 while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
179 SMTPC_syslog(LOG_WARNING,
181 ((OneQueItem *)VData)->MessageID);
183 pthread_mutex_unlock(&ActiveQItemsLock);
188 void FreeMailQEntry(void *qv)
192 SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
195 FreeStrBuf(&Q->Recipient);
196 FreeStrBuf(&Q->StatusMessage);
198 memset(Q, 0, sizeof(MailQEntry));
201 void FreeQueItem(OneQueItem **Item)
204 SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
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));
216 void HFreeQueItem(void *Item)
218 FreeQueItem((OneQueItem**)&Item);
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)
226 int CheckQEntryActive(MailQEntry *ThisItem)
228 if ((ThisItem->Status == 0) ||
229 (ThisItem->Status == 3) ||
230 (ThisItem->Status == 4))
237 int CheckQEntryIsBounce(MailQEntry *ThisItem)
239 if ((ThisItem->Status == 3) ||
240 (ThisItem->Status == 4) ||
241 (ThisItem->Status == 5))
249 int CountActiveQueueEntries(OneQueItem *MyQItem, int before)
253 long ActiveDeliveries;
257 ActiveDeliveries = 0;
258 It = GetNewHashPos(MyQItem->MailQEntries, 0);
259 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
262 MailQEntry *ThisItem = vQE;
264 if (CheckQEntryActive(ThisItem))
272 ThisItem->Active = Active;
274 ThisItem->StillActive = Active;
277 return ActiveDeliveries;
280 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
283 const char *pLine = NULL;
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;
295 Line = NewStrBufPlain(NULL, 128);
296 while (pLine != StrBufNOTNULL) {
297 const char *pItemPart = NULL;
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))
305 QItemHandlerStruct *HS;
306 HS = (QItemHandlerStruct*) vHandler;
307 HS->H(Item, Line, &pItemPart);
313 if (Item->Retry >= MaxRetry)
316 pthread_mutex_lock(&ActiveQItemsLock);
317 if (GetHash(ActiveQItems,
318 LKEY(Item->MessageID),
321 /* WHOOPS. somebody else is already working on this. */
322 pthread_mutex_unlock(&ActiveQItemsLock);
327 /* mark our claim on this. */
329 LKEY(Item->MessageID),
332 pthread_mutex_unlock(&ActiveQItemsLock);
338 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
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);
352 StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
353 StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
355 if (StrLength(MyQItem->BounceTo) > 0) {
356 StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
357 StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
360 if (StrLength(MyQItem->EnvelopeFrom) > 0) {
361 StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
362 StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
365 if (StrLength(MyQItem->SenderRoom) > 0) {
366 StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
367 StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
370 StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
371 StrBufAppendPrintf(QMessage, "%ld",
374 StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
375 StrBufAppendPrintf(QMessage, "%ld",
376 time(NULL) /*ctdl_ev_now()*/ + MyQItem->Retry);
378 It = GetNewHashPos(MyQItem->MailQEntries, 0);
379 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
381 MailQEntry *ThisItem = vQE;
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);
391 StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
399 void NewMailQEntry(OneQueItem *Item)
401 Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
402 memset(Item->Current, 0, sizeof(MailQEntry));
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),
415 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
417 Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
420 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
422 if (Item->EnvelopeFrom == NULL)
423 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
424 StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
427 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
429 if (Item->BounceTo == NULL)
430 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
431 StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
434 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
436 if (Item->SenderRoom == NULL)
437 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
438 StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
441 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
443 if (Item->Current == NULL)
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?
454 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
457 StrBufExtractNext_int(Line, Pos, '|');
458 if (Item->Retry == 0)
459 Item->Retry = SMTP_RETRY_INTERVAL;
465 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
467 Item->Submitted = atol(*Pos);
471 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
473 Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
479 * this one has to have the context for loading the message via the redirect buffer...
481 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
486 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
487 CtdlOutputMsg(MyQItem->MessageID,
488 MT_RFC822, HEADERS_ALL,
490 (ESC_DOT|SUPPRESS_ENV_TO) );
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);
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).
513 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt)
517 struct CtdlMessage *bmsg = NULL;
521 struct recptypes *valid;
529 int first_attempt = 0;
530 int successful_bounce = 0;
534 SMTPCM_syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
536 if (MyQItem->SendBounceMail == 0)
539 now = time (NULL); //ev_time();
541 if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
545 if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
550 * Now go through the instructions checking for stuff.
552 Msg = NewStrBufPlain(NULL, 1024);
553 It = GetNewHashPos(MyQItem->MailQEntries, 0);
554 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
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... */
564 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
565 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
566 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
567 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
572 /* Deliver the bounce if there's anything worth mentioning */
573 SMTPC_syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
575 if (num_bounces == 0) {
580 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
581 StrBufAppendPrintf(boundary,
587 /* Start building our bounce message; go shopping for memory first. */
588 BounceMB = NewStrBufPlain(
590 1024 + /* mime stuff.... */
591 StrLength(Msg) + /* the bounce information... */
592 StrLength(OMsgTxt)); /* the original message */
593 if (BounceMB == NULL) {
594 FreeStrBuf(&boundary);
595 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
600 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
602 FreeStrBuf(&boundary);
603 FreeStrBuf(&BounceMB);
604 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
608 memset(bmsg, 0, sizeof(struct CtdlMessage));
611 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
612 StrBufAppendBuf(BounceMB, boundary, 0);
613 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
614 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
615 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
616 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
617 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
618 StrBufAppendBuf(BounceMB, boundary, 0);
619 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
620 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
623 StrBufAppendBufPlain(
626 "A message you sent could not be delivered "
627 "to some or all of its recipients\n"
628 "due to prolonged unavailability "
629 "of its destination(s).\n"
630 "Giving up on the following addresses:\n\n"
633 StrBufAppendBufPlain(
636 "A message you sent could not be delivered "
637 "to some or all of its recipients.\n"
638 "The following addresses "
639 "were undeliverable:\n\n"
642 StrBufAppendBuf(BounceMB, Msg, 0);
645 if (StrLength(MyQItem->SenderRoom) > 0)
647 StrBufAppendBufPlain(
649 HKEY("The message was originaly posted in: "), 0);
650 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
651 StrBufAppendBufPlain(
656 /* Attach the original message */
657 StrBufAppendBufPlain(BounceMB, HKEY("\r\n--"), 0);
658 StrBufAppendBuf(BounceMB, boundary, 0);
659 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
660 StrBufAppendBufPlain(BounceMB,
661 HKEY("Content-type: message/rfc822\r\n"), 0);
662 StrBufAppendBufPlain(BounceMB,
663 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
664 StrBufAppendBufPlain(BounceMB,
665 HKEY("Content-Disposition: inline\r\n"), 0);
666 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
667 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
669 /* Close the multipart MIME scope */
670 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
671 StrBufAppendBuf(BounceMB, boundary, 0);
672 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
674 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
675 bmsg->cm_anon_type = MES_NORMAL;
676 bmsg->cm_format_type = FMT_RFC822;
678 bmsg->cm_fields['O'] = strdup(MAILROOM);
679 bmsg->cm_fields['A'] = strdup("Citadel");
680 bmsg->cm_fields['N'] = strdup(config.c_nodename);
681 bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
682 bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
684 /* First try the user who sent the message */
685 if (StrLength(MyQItem->BounceTo) == 0) {
686 SMTPCM_syslog(LOG_ERR, "No bounce address specified\n");
689 SMTPC_syslog(LOG_DEBUG, "bounce to user? <%s>\n",
690 ChrPtr(MyQItem->BounceTo));
693 /* Can we deliver the bounce to the original sender? */
694 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
695 if ((valid != NULL) && (valid->num_error == 0)) {
696 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
697 successful_bounce = 1;
700 /* If not, post it in the Aide> room */
701 if (successful_bounce == 0) {
702 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
705 /* Free up the memory we used */
706 free_recipients(valid);
707 FreeStrBuf(&boundary);
708 CtdlFreeMessage(bmsg);
709 SMTPCM_syslog(LOG_DEBUG, "Done processing bounces\n");
715 * Called by smtp_do_queue() to handle an individual message.
717 void smtp_do_procmsg(long msgnum, void *userdata) {
719 int mynumsessions = num_sessions;
720 struct CtdlMessage *msg = NULL;
730 ParsedURL *RelayUrls = NULL;
734 if (mynumsessions > max_sessions_for_outbound_smtp) {
735 SMTPC_syslog(LOG_DEBUG,
736 "skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
738 max_sessions_for_outbound_smtp);
741 SMTPC_syslog(LOG_DEBUG, "smtp_do_procmsg(%ld)\n", msgnum);
742 ///strcpy(envelope_from, "");
744 msg = CtdlFetchMessage(msgnum, 1);
746 SMTPC_syslog(LOG_ERR, "tried %ld but no such message!\n",
751 pch = instr = msg->cm_fields['M'];
753 /* Strip out the headers (no not amd any other non-instruction) line */
754 while (pch != NULL) {
755 pch = strchr(pch, '\n');
756 if ((pch != NULL) && (*(pch + 1) == '\n')) {
761 PlainQItem = NewStrBufPlain(instr, -1);
762 CtdlFreeMessage(msg);
763 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
764 FreeStrBuf(&PlainQItem);
766 if (MyQItem == NULL) {
767 SMTPC_syslog(LOG_ERR,
768 "Msg No %ld: already in progress!\n",
770 return; /* s.b. else is already processing... */
774 * Postpone delivery if we've already tried recently.
777 if ((MyQItem->ReattemptWhen != 0) &&
778 (now < MyQItem->ReattemptWhen) &&
779 (run_queue_now == 0))
781 SMTPC_syslog(LOG_DEBUG,
782 "Retry time not yet reached. %ld seconds left.",
783 MyQItem->ReattemptWhen - now);
785 It = GetNewHashPos(MyQItem->MailQEntries, 0);
786 pthread_mutex_lock(&ActiveQItemsLock);
788 if (GetHashPosFromKey(ActiveQItems,
789 LKEY(MyQItem->MessageID),
792 DeleteEntryFromHash(ActiveQItems, It);
795 pthread_mutex_unlock(&ActiveQItemsLock);
796 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
802 * Bail out if there's no actual message associated with this
804 if (MyQItem->MessageID < 0L) {
805 SMTPCM_syslog(LOG_ERR, "no 'msgid' directive found!\n");
806 It = GetNewHashPos(MyQItem->MailQEntries, 0);
807 pthread_mutex_lock(&ActiveQItemsLock);
809 if (GetHashPosFromKey(ActiveQItems,
810 LKEY(MyQItem->MessageID),
813 DeleteEntryFromHash(ActiveQItems, It);
816 pthread_mutex_unlock(&ActiveQItemsLock);
818 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
824 ParsedURL **Url = &MyQItem->URL;
825 nRelays = get_hosts(mxbuf, "fallbackhost");
829 const char *Pos = NULL;
830 All = NewStrBufPlain(mxbuf, -1);
831 One = NewStrBufPlain(NULL, StrLength(All) + 1);
833 while ((Pos != StrBufNOTNULL) &&
837 StrBufExtract_NextToken(One, All, &Pos, '|');
838 if (!ParseURL(Url, One, DefaultMXPort)) {
839 SMTPC_syslog(LOG_DEBUG,
840 "Failed to parse: %s\n",
845 MyQItem->HaveRelay = 1;
851 nRelays = get_hosts(mxbuf, "smarthost");
855 const char *Pos = NULL;
856 All = NewStrBufPlain(mxbuf, -1);
857 One = NewStrBufPlain(NULL, StrLength(All) + 1);
859 while ((Pos != StrBufNOTNULL) &&
863 StrBufExtract_NextToken(One, All, &Pos, '|');
864 if (!ParseURL(Url, One, DefaultMXPort)) {
865 SMTPC_syslog(LOG_DEBUG,
866 "Failed to parse: %s\n",
870 ///if (!Url->IsIP)) // todo dupe me fork ipv6
872 MyQItem->HaveRelay = 1;
881 It = GetNewHashPos(MyQItem->MailQEntries, 0);
882 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
884 MailQEntry *ThisItem = vQE;
885 SMTPC_syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
886 ChrPtr(ThisItem->Recipient),
891 MyQItem->NotYetShutdownDeliveries =
892 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem, 1);
894 /* failsafe against overload:
895 * will we exceed the limit set?
897 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
898 /* if yes, did we reach more than half of the quota? */
899 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
900 /* if... would we ever fit into half of the quota?? */
901 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
903 /* abort delivery for another time. */
904 SMTPC_syslog(LOG_DEBUG,
905 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
907 MyQItem->ActiveDeliveries,
908 max_sessions_for_outbound_smtp);
910 FreeQueItem(&MyQItem);
916 if (MyQItem->ActiveDeliveries > 0)
920 int m = MyQItem->ActiveDeliveries;
922 Msg = smtp_load_msg(MyQItem, n);
923 It = GetNewHashPos(MyQItem->MailQEntries, 0);
925 (GetNextHashPos(MyQItem->MailQEntries,
926 It, &len, &Key, &vQE)))
928 MailQEntry *ThisItem = vQE;
930 if (ThisItem->Active == 1)
932 int KeepBuffers = (i == m);
935 if (nActivated % ndelay_count == 0)
938 if (i > 1) n = MsgCount++;
940 "SMTPC: Trying <%ld> <%s> %d / %d \n",
942 ChrPtr(ThisItem->Recipient),
945 (*((int*) userdata)) ++;
946 smtp_try_one_queue_entry(MyQItem,
953 if (KeepBuffers) HaveBuffers = 1;
962 It = GetNewHashPos(MyQItem->MailQEntries, 0);
963 pthread_mutex_lock(&ActiveQItemsLock);
965 if (GetHashPosFromKey(ActiveQItems,
966 LKEY(MyQItem->MessageID),
969 DeleteEntryFromHash(ActiveQItems, It);
977 SMTPC_syslog(LOG_WARNING,
978 "unable to find QItem with ID[%ld]",
980 while (GetNextHashPos(ActiveQItems,
986 SMTPC_syslog(LOG_WARNING,
988 ((OneQueItem *)VData)->MessageID);
993 pthread_mutex_unlock(&ActiveQItemsLock);
995 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
997 // TODO: bounce & delete?
1002 // TODO : free RelayUrls
1009 * smtp_queue_thread()
1011 * Run through the queue sending out messages.
1013 void smtp_do_queue(void) {
1014 int num_processed = 0;
1015 int num_activated = 0;
1017 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
1018 SMTPCM_syslog(LOG_INFO, "processing outbound queue");
1020 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
1021 SMTPC_syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
1024 num_processed = CtdlForEachMessage(MSGS_ALL,
1032 SMTPC_syslog(LOG_INFO,
1033 "queue run completed; %d messages processed %d activated",
1034 num_processed, num_activated);
1041 * Initialize the SMTP outbound queue
1043 void smtp_init_spoolout(void) {
1044 struct ctdlroom qrbuf;
1047 * Create the room. This will silently fail if the room already
1048 * exists, and that's perfectly ok, because we want it to exist.
1050 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1053 * Make sure it's set to be a "system room" so it doesn't show up
1054 * in the <K>nown rooms list for Aides.
1056 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1057 qrbuf.QRflags2 |= QR2_SYSTEM;
1058 CtdlPutRoomLock(&qrbuf);
1065 /*****************************************************************************/
1066 /* SMTP UTILITY COMMANDS */
1067 /*****************************************************************************/
1069 void cmd_smtp(char *argbuf) {
1076 if (CtdlAccessCheck(ac_aide)) return;
1078 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1080 if (!strcasecmp(cmd, "mx")) {
1081 extract_token(node, argbuf, 1, '|', sizeof node);
1082 num_mxhosts = getmx(buf, node);
1083 cprintf("%d %d MX hosts listed for %s\n",
1084 LISTING_FOLLOWS, num_mxhosts, node);
1085 for (i=0; i<num_mxhosts; ++i) {
1086 extract_token(node, buf, i, '|', sizeof node);
1087 cprintf("%s\n", node);
1093 else if (!strcasecmp(cmd, "runqueue")) {
1095 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1100 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1106 CTDL_MODULE_INIT(smtp_queu)
1112 pstr = getenv("CITSERVER_n_session_max");
1113 if ((pstr != NULL) && (*pstr != '\0'))
1114 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1116 pstr = getenv("CITSERVER_smtp_n_delay_count");
1117 if ((pstr != NULL) && (*pstr != '\0'))
1118 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1120 pstr = getenv("CITSERVER_smtp_delay");
1121 if ((pstr != NULL) && (*pstr != '\0'))
1122 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1127 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1128 ActiveQItems = NewHash(1, lFlathash);
1129 pthread_mutex_init(&ActiveQItemsLock, NULL);
1131 QItemHandlers = NewHash(0, NULL);
1133 RegisterQItemHandler(HKEY("msgid"), QItem_Handle_MsgID);
1134 RegisterQItemHandler(HKEY("envelope_from"), QItem_Handle_EnvelopeFrom);
1135 RegisterQItemHandler(HKEY("retry"), QItem_Handle_retry);
1136 RegisterQItemHandler(HKEY("attempted"), QItem_Handle_Attempted);
1137 RegisterQItemHandler(HKEY("remote"), QItem_Handle_Recipient);
1138 RegisterQItemHandler(HKEY("bounceto"), QItem_Handle_BounceTo);
1139 RegisterQItemHandler(HKEY("source_room"), QItem_Handle_SenderRoom);
1140 RegisterQItemHandler(HKEY("submitted"), QItem_Handle_Submitted);
1142 smtp_init_spoolout();
1144 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1146 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1147 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER, PRIO_SEND + 10);
1150 /* return our Subversion id for the Log */
1151 return "smtpeventclient";