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)
253 long ActiveDeliveries;
257 ActiveDeliveries = 0;
258 It = GetNewHashPos(MyQItem->MailQEntries, 0);
259 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
261 MailQEntry *ThisItem = vQE;
263 if (CheckQEntryActive(ThisItem))
266 ThisItem->Active = 1;
269 ThisItem->Active = 0;
272 return ActiveDeliveries;
275 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
278 const char *pLine = NULL;
283 Item = (OneQueItem*)malloc(sizeof(OneQueItem));
284 memset(Item, 0, sizeof(OneQueItem));
285 Item->Retry = SMTP_RETRY_INTERVAL;
286 Item->MessageID = -1;
287 Item->QueMsgID = QueMsgID;
290 Line = NewStrBufPlain(NULL, 128);
291 while (pLine != StrBufNOTNULL) {
292 const char *pItemPart = NULL;
295 StrBufExtract_NextToken(Line, RawQItem, &pLine, '\n');
296 if (StrLength(Line) == 0) continue;
297 StrBufExtract_NextToken(Token, Line, &pItemPart, '|');
298 if (GetHash(QItemHandlers, SKEY(Token), &vHandler))
300 QItemHandlerStruct *HS;
301 HS = (QItemHandlerStruct*) vHandler;
302 HS->H(Item, Line, &pItemPart);
308 if (Item->Retry >= MaxRetry)
311 pthread_mutex_lock(&ActiveQItemsLock);
312 if (GetHash(ActiveQItems,
313 LKEY(Item->MessageID),
316 /* WHOOPS. somebody else is already working on this. */
317 pthread_mutex_unlock(&ActiveQItemsLock);
322 /* mark our claim on this. */
324 LKEY(Item->MessageID),
327 pthread_mutex_unlock(&ActiveQItemsLock);
333 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
341 QMessage = NewStrBufPlain(NULL, SIZ);
342 StrBufPrintf(QMessage, "Content-type: %s\n", SPOOLMIME);
343 // "attempted|%ld\n" "retry|%ld\n",, (long)time(NULL), (long)retry );
344 StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
345 StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
347 StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
348 StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
350 if (StrLength(MyQItem->BounceTo) > 0) {
351 StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
352 StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
355 if (StrLength(MyQItem->EnvelopeFrom) > 0) {
356 StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
357 StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
360 if (StrLength(MyQItem->SenderRoom) > 0) {
361 StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
362 StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
365 StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
366 StrBufAppendPrintf(QMessage, "%ld",
369 StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
370 StrBufAppendPrintf(QMessage, "%ld",
371 time(NULL) /*ctdl_ev_now()*/ + MyQItem->Retry);
373 It = GetNewHashPos(MyQItem->MailQEntries, 0);
374 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
376 MailQEntry *ThisItem = vQE;
378 StrBufAppendBufPlain(QMessage, HKEY("\nremote|"), 0);
379 StrBufAppendBuf(QMessage, ThisItem->Recipient, 0);
380 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
381 StrBufAppendPrintf(QMessage, "%d", ThisItem->Status);
382 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
383 StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
386 StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
394 void NewMailQEntry(OneQueItem *Item)
396 Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
397 memset(Item->Current, 0, sizeof(MailQEntry));
399 if (Item->MailQEntries == NULL)
400 Item->MailQEntries = NewHash(1, Flathash);
401 /* alocate big buffer so we won't get problems reallocating later. */
402 Item->Current->StatusMessage = NewStrBufPlain(NULL, SIZ);
403 Item->Current->n = GetCount(Item->MailQEntries);
404 Put(Item->MailQEntries,
405 IKEY(Item->Current->n),
410 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
412 Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
415 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
417 if (Item->EnvelopeFrom == NULL)
418 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
419 StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
422 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
424 if (Item->BounceTo == NULL)
425 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
426 StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
429 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
431 if (Item->SenderRoom == NULL)
432 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
433 StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
436 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
438 if (Item->Current == NULL)
440 if (Item->Current->Recipient == NULL)
441 Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
442 StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
443 Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
444 StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
445 Item->Current = NULL; // TODO: is this always right?
449 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
452 StrBufExtractNext_int(Line, Pos, '|');
453 if (Item->Retry == 0)
454 Item->Retry = SMTP_RETRY_INTERVAL;
460 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
462 Item->Submitted = atol(*Pos);
466 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
468 Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
474 * this one has to have the context for loading the message via the redirect buffer...
476 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
481 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
482 CtdlOutputMsg(MyQItem->MessageID,
483 MT_RFC822, HEADERS_ALL,
485 (ESC_DOT|SUPPRESS_ENV_TO) );
487 SendMsg = CCC->redirect_buffer;
488 CCC->redirect_buffer = NULL;
489 if ((StrLength(SendMsg) > 0) &&
490 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
491 SMTPC_syslog(LOG_WARNING,
492 "[%d] Possible problem: message did not "
493 "correctly terminate. (expecting 0x10, got 0x%02x)\n",
494 MsgCount, //yes uncool, but best choice here...
495 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
496 StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
504 * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
505 * instructions for "5" codes (permanent fatal errors) and produce/deliver
506 * a "bounce" message (delivery status notification).
508 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt)
512 struct CtdlMessage *bmsg = NULL;
516 struct recptypes *valid;
524 int first_attempt = 0;
525 int successful_bounce = 0;
529 SMTPCM_syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
531 if (MyQItem->SendBounceMail == 0)
534 now = time (NULL); //ev_time();
536 if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
540 if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
545 * Now go through the instructions checking for stuff.
547 Msg = NewStrBufPlain(NULL, 1024);
548 It = GetNewHashPos(MyQItem->MailQEntries, 0);
549 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
551 MailQEntry *ThisItem = vQE;
552 if ((ThisItem->Active && (ThisItem->Status == 5)) || /* failed now? */
553 ((give_up == 1) && (ThisItem->Status != 2)) ||
554 ((first_attempt == 1) && (ThisItem->Status != 2)))
555 /* giving up after failed attempts... */
559 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
560 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
561 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
562 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
567 /* Deliver the bounce if there's anything worth mentioning */
568 SMTPC_syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
570 if (num_bounces == 0) {
575 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
576 StrBufAppendPrintf(boundary,
582 /* Start building our bounce message; go shopping for memory first. */
583 BounceMB = NewStrBufPlain(
585 1024 + /* mime stuff.... */
586 StrLength(Msg) + /* the bounce information... */
587 StrLength(OMsgTxt)); /* the original message */
588 if (BounceMB == NULL) {
589 FreeStrBuf(&boundary);
590 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
595 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
597 FreeStrBuf(&boundary);
598 FreeStrBuf(&BounceMB);
599 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
603 memset(bmsg, 0, sizeof(struct CtdlMessage));
606 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
607 StrBufAppendBuf(BounceMB, boundary, 0);
608 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
609 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
610 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
611 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
612 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
613 StrBufAppendBuf(BounceMB, boundary, 0);
614 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
615 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
618 StrBufAppendBufPlain(
621 "A message you sent could not be delivered "
622 "to some or all of its recipients\n"
623 "due to prolonged unavailability "
624 "of its destination(s).\n"
625 "Giving up on the following addresses:\n\n"
628 StrBufAppendBufPlain(
631 "A message you sent could not be delivered "
632 "to some or all of its recipients.\n"
633 "The following addresses "
634 "were undeliverable:\n\n"
637 StrBufAppendBuf(BounceMB, Msg, 0);
640 if (StrLength(MyQItem->SenderRoom) > 0)
642 StrBufAppendBufPlain(
644 HKEY("The message was originaly posted in: "), 0);
645 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
646 StrBufAppendBufPlain(
651 /* Attach the original message */
652 StrBufAppendBufPlain(BounceMB, HKEY("\r\n--"), 0);
653 StrBufAppendBuf(BounceMB, boundary, 0);
654 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
655 StrBufAppendBufPlain(BounceMB,
656 HKEY("Content-type: message/rfc822\r\n"), 0);
657 StrBufAppendBufPlain(BounceMB,
658 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
659 StrBufAppendBufPlain(BounceMB,
660 HKEY("Content-Disposition: inline\r\n"), 0);
661 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
662 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
664 /* Close the multipart MIME scope */
665 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
666 StrBufAppendBuf(BounceMB, boundary, 0);
667 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
669 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
670 bmsg->cm_anon_type = MES_NORMAL;
671 bmsg->cm_format_type = FMT_RFC822;
673 bmsg->cm_fields['O'] = strdup(MAILROOM);
674 bmsg->cm_fields['A'] = strdup("Citadel");
675 bmsg->cm_fields['N'] = strdup(config.c_nodename);
676 bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
677 bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
679 /* First try the user who sent the message */
680 if (StrLength(MyQItem->BounceTo) == 0) {
681 SMTPCM_syslog(LOG_ERR, "No bounce address specified\n");
684 SMTPC_syslog(LOG_DEBUG, "bounce to user? <%s>\n",
685 ChrPtr(MyQItem->BounceTo));
688 /* Can we deliver the bounce to the original sender? */
689 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
690 if ((valid != NULL) && (valid->num_error == 0)) {
691 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
692 successful_bounce = 1;
695 /* If not, post it in the Aide> room */
696 if (successful_bounce == 0) {
697 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
700 /* Free up the memory we used */
701 free_recipients(valid);
702 FreeStrBuf(&boundary);
703 CtdlFreeMessage(bmsg);
704 SMTPCM_syslog(LOG_DEBUG, "Done processing bounces\n");
710 * Called by smtp_do_queue() to handle an individual message.
712 void smtp_do_procmsg(long msgnum, void *userdata) {
714 int mynumsessions = num_sessions;
715 struct CtdlMessage *msg = NULL;
725 ParsedURL *RelayUrls = NULL;
729 if (mynumsessions > max_sessions_for_outbound_smtp) {
730 SMTPC_syslog(LOG_DEBUG,
731 "skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
733 max_sessions_for_outbound_smtp);
736 SMTPC_syslog(LOG_DEBUG, "smtp_do_procmsg(%ld)\n", msgnum);
737 ///strcpy(envelope_from, "");
739 msg = CtdlFetchMessage(msgnum, 1);
741 SMTPC_syslog(LOG_ERR, "tried %ld but no such message!\n",
746 pch = instr = msg->cm_fields['M'];
748 /* Strip out the headers (no not amd any other non-instruction) line */
749 while (pch != NULL) {
750 pch = strchr(pch, '\n');
751 if ((pch != NULL) && (*(pch + 1) == '\n')) {
756 PlainQItem = NewStrBufPlain(instr, -1);
757 CtdlFreeMessage(msg);
758 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
759 FreeStrBuf(&PlainQItem);
761 if (MyQItem == NULL) {
762 SMTPC_syslog(LOG_ERR,
763 "Msg No %ld: already in progress!\n",
765 return; /* s.b. else is already processing... */
769 * Postpone delivery if we've already tried recently.
772 if ((MyQItem->ReattemptWhen != 0) &&
773 (now < MyQItem->ReattemptWhen) &&
774 (run_queue_now == 0))
776 SMTPC_syslog(LOG_DEBUG,
777 "Retry time not yet reached. %ld seconds left.",
778 MyQItem->ReattemptWhen - now);
780 It = GetNewHashPos(MyQItem->MailQEntries, 0);
781 pthread_mutex_lock(&ActiveQItemsLock);
783 if (GetHashPosFromKey(ActiveQItems,
784 LKEY(MyQItem->MessageID),
787 DeleteEntryFromHash(ActiveQItems, It);
790 pthread_mutex_unlock(&ActiveQItemsLock);
791 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
797 * Bail out if there's no actual message associated with this
799 if (MyQItem->MessageID < 0L) {
800 SMTPCM_syslog(LOG_ERR, "no 'msgid' directive found!\n");
801 It = GetNewHashPos(MyQItem->MailQEntries, 0);
802 pthread_mutex_lock(&ActiveQItemsLock);
804 if (GetHashPosFromKey(ActiveQItems,
805 LKEY(MyQItem->MessageID),
808 DeleteEntryFromHash(ActiveQItems, It);
811 pthread_mutex_unlock(&ActiveQItemsLock);
813 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
819 ParsedURL **Url = &MyQItem->URL;
820 nRelays = get_hosts(mxbuf, "smarthost");
824 const char *Pos = NULL;
825 All = NewStrBufPlain(mxbuf, -1);
826 One = NewStrBufPlain(NULL, StrLength(All) + 1);
828 while ((Pos != StrBufNOTNULL) &&
832 StrBufExtract_NextToken(One, All, &Pos, '|');
833 if (!ParseURL(Url, One, DefaultMXPort)) {
834 SMTPC_syslog(LOG_DEBUG,
835 "Failed to parse: %s\n",
839 ///if (!Url->IsIP)) // todo dupe me fork ipv6
847 Url = &MyQItem->FallBackHost;
848 nRelays = get_hosts(mxbuf, "fallbackhost");
852 const char *Pos = NULL;
853 All = NewStrBufPlain(mxbuf, -1);
854 One = NewStrBufPlain(NULL, StrLength(All) + 1);
856 while ((Pos != StrBufNOTNULL) &&
860 StrBufExtract_NextToken(One, All, &Pos, '|');
861 if (!ParseURL(Url, One, DefaultMXPort)) {
862 SMTPC_syslog(LOG_DEBUG,
863 "Failed to parse: %s\n",
874 It = GetNewHashPos(MyQItem->MailQEntries, 0);
875 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
877 MailQEntry *ThisItem = vQE;
878 SMTPC_syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
879 ChrPtr(ThisItem->Recipient),
884 MyQItem->NotYetShutdownDeliveries =
885 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem);
887 /* failsafe against overload:
888 * will we exceed the limit set?
890 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
891 /* if yes, did we reach more than half of the quota? */
892 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
893 /* if... would we ever fit into half of the quota?? */
894 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
896 /* abort delivery for another time. */
897 SMTPC_syslog(LOG_DEBUG,
898 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
900 MyQItem->ActiveDeliveries,
901 max_sessions_for_outbound_smtp);
903 FreeQueItem(&MyQItem);
909 if (MyQItem->ActiveDeliveries > 0)
913 int m = MyQItem->ActiveDeliveries;
915 Msg = smtp_load_msg(MyQItem, n);
916 It = GetNewHashPos(MyQItem->MailQEntries, 0);
918 (GetNextHashPos(MyQItem->MailQEntries,
919 It, &len, &Key, &vQE)))
921 MailQEntry *ThisItem = vQE;
923 if (ThisItem->Active == 1)
925 int KeepBuffers = (i == m);
928 if (nActivated % ndelay_count == 0)
931 if (i > 1) n = MsgCount++;
933 "SMTPC: Trying <%ld> <%s> %d / %d \n",
935 ChrPtr(ThisItem->Recipient),
938 (*((int*) userdata)) ++;
939 smtp_try_one_queue_entry(MyQItem,
946 if (KeepBuffers) HaveBuffers = 1;
955 It = GetNewHashPos(MyQItem->MailQEntries, 0);
956 pthread_mutex_lock(&ActiveQItemsLock);
958 if (GetHashPosFromKey(ActiveQItems,
959 LKEY(MyQItem->MessageID),
962 DeleteEntryFromHash(ActiveQItems, It);
970 SMTPC_syslog(LOG_WARNING,
971 "unable to find QItem with ID[%ld]",
973 while (GetNextHashPos(ActiveQItems,
979 SMTPC_syslog(LOG_WARNING,
981 ((OneQueItem *)VData)->MessageID);
986 pthread_mutex_unlock(&ActiveQItemsLock);
988 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
990 // TODO: bounce & delete?
995 // TODO : free RelayUrls
1002 * smtp_queue_thread()
1004 * Run through the queue sending out messages.
1006 void smtp_do_queue(void) {
1007 int num_processed = 0;
1008 int num_activated = 0;
1010 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
1011 SMTPCM_syslog(LOG_INFO, "processing outbound queue");
1013 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
1014 SMTPC_syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
1017 num_processed = CtdlForEachMessage(MSGS_ALL,
1025 SMTPC_syslog(LOG_INFO,
1026 "queue run completed; %d messages processed %d activated",
1027 num_processed, num_activated);
1034 * Initialize the SMTP outbound queue
1036 void smtp_init_spoolout(void) {
1037 struct ctdlroom qrbuf;
1040 * Create the room. This will silently fail if the room already
1041 * exists, and that's perfectly ok, because we want it to exist.
1043 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1046 * Make sure it's set to be a "system room" so it doesn't show up
1047 * in the <K>nown rooms list for Aides.
1049 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1050 qrbuf.QRflags2 |= QR2_SYSTEM;
1051 CtdlPutRoomLock(&qrbuf);
1058 /*****************************************************************************/
1059 /* SMTP UTILITY COMMANDS */
1060 /*****************************************************************************/
1062 void cmd_smtp(char *argbuf) {
1069 if (CtdlAccessCheck(ac_aide)) return;
1071 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1073 if (!strcasecmp(cmd, "mx")) {
1074 extract_token(node, argbuf, 1, '|', sizeof node);
1075 num_mxhosts = getmx(buf, node);
1076 cprintf("%d %d MX hosts listed for %s\n",
1077 LISTING_FOLLOWS, num_mxhosts, node);
1078 for (i=0; i<num_mxhosts; ++i) {
1079 extract_token(node, buf, i, '|', sizeof node);
1080 cprintf("%s\n", node);
1086 else if (!strcasecmp(cmd, "runqueue")) {
1088 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1093 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1099 CTDL_MODULE_INIT(smtp_queu)
1105 pstr = getenv("CITSERVER_n_session_max");
1106 if ((pstr != NULL) && (*pstr != '\0'))
1107 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1109 pstr = getenv("CITSERVER_smtp_n_delay_count");
1110 if ((pstr != NULL) && (*pstr != '\0'))
1111 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1113 pstr = getenv("CITSERVER_smtp_delay");
1114 if ((pstr != NULL) && (*pstr != '\0'))
1115 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1120 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1121 ActiveQItems = NewHash(1, lFlathash);
1122 pthread_mutex_init(&ActiveQItemsLock, NULL);
1124 QItemHandlers = NewHash(0, NULL);
1126 RegisterQItemHandler(HKEY("msgid"), QItem_Handle_MsgID);
1127 RegisterQItemHandler(HKEY("envelope_from"), QItem_Handle_EnvelopeFrom);
1128 RegisterQItemHandler(HKEY("retry"), QItem_Handle_retry);
1129 RegisterQItemHandler(HKEY("attempted"), QItem_Handle_Attempted);
1130 RegisterQItemHandler(HKEY("remote"), QItem_Handle_Recipient);
1131 RegisterQItemHandler(HKEY("bounceto"), QItem_Handle_BounceTo);
1132 RegisterQItemHandler(HKEY("source_room"), QItem_Handle_SenderRoom);
1133 RegisterQItemHandler(HKEY("submitted"), QItem_Handle_Submitted);
1135 smtp_init_spoolout();
1137 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1139 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1140 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER);
1143 /* return our Subversion id for the Log */
1144 return "smtpeventclient";