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 CountActiveQueueEntries(OneQueItem *MyQItem)
203 long ActiveDeliveries;
207 ActiveDeliveries = 0;
208 It = GetNewHashPos(MyQItem->MailQEntries, 0);
209 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
211 MailQEntry *ThisItem = vQE;
212 if ((ThisItem->Status == 0) ||
213 (ThisItem->Status == 3) ||
214 (ThisItem->Status == 4))
217 ThisItem->Active = 1;
220 ThisItem->Active = 0;
223 return ActiveDeliveries;
226 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
229 const char *pLine = NULL;
234 Item = (OneQueItem*)malloc(sizeof(OneQueItem));
235 memset(Item, 0, sizeof(OneQueItem));
236 Item->Retry = SMTP_RETRY_INTERVAL;
237 Item->MessageID = -1;
238 Item->QueMsgID = QueMsgID;
241 Line = NewStrBufPlain(NULL, 128);
242 while (pLine != StrBufNOTNULL) {
243 const char *pItemPart = NULL;
246 StrBufExtract_NextToken(Line, RawQItem, &pLine, '\n');
247 if (StrLength(Line) == 0) continue;
248 StrBufExtract_NextToken(Token, Line, &pItemPart, '|');
249 if (GetHash(QItemHandlers, SKEY(Token), &vHandler))
252 H = (QItemHandler) vHandler;
253 H(Item, Line, &pItemPart);
259 if (Item->Retry >= MaxRetry)
262 pthread_mutex_lock(&ActiveQItemsLock);
263 if (GetHash(ActiveQItems,
264 LKEY(Item->MessageID),
267 /* WHOOPS. somebody else is already working on this. */
268 pthread_mutex_unlock(&ActiveQItemsLock);
273 /* mark our claim on this. */
275 LKEY(Item->MessageID),
278 pthread_mutex_unlock(&ActiveQItemsLock);
284 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
292 QMessage = NewStrBufPlain(NULL, SIZ);
293 StrBufPrintf(QMessage, "Content-type: %s\n", SPOOLMIME);
294 // "attempted|%ld\n" "retry|%ld\n",, (long)time(NULL), (long)retry );
295 StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
296 StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
298 StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
299 StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
301 if (StrLength(MyQItem->BounceTo) > 0) {
302 StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
303 StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
306 if (StrLength(MyQItem->EnvelopeFrom) > 0) {
307 StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
308 StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
311 if (StrLength(MyQItem->SenderRoom) > 0) {
312 StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
313 StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
316 StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
317 StrBufAppendPrintf(QMessage, "%ld",
320 StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
321 StrBufAppendPrintf(QMessage, "%ld",
322 MyQItem->ReattemptWhen);
324 It = GetNewHashPos(MyQItem->MailQEntries, 0);
325 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
327 MailQEntry *ThisItem = vQE;
329 if (!ThisItem->Active)
331 /* skip already sent ones from the spoolfile. */
334 StrBufAppendBufPlain(QMessage, HKEY("\nremote|"), 0);
335 StrBufAppendBuf(QMessage, ThisItem->Recipient, 0);
336 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
337 StrBufAppendPrintf(QMessage, "%d", ThisItem->Status);
338 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
339 StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
342 StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
350 void NewMailQEntry(OneQueItem *Item)
352 Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
353 memset(Item->Current, 0, sizeof(MailQEntry));
355 if (Item->MailQEntries == NULL)
356 Item->MailQEntries = NewHash(1, Flathash);
357 Item->Current->StatusMessage = NewStrBuf();
358 Item->Current->n = GetCount(Item->MailQEntries);
359 Put(Item->MailQEntries,
360 IKEY(Item->Current->n),
365 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
367 Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
370 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
372 if (Item->EnvelopeFrom == NULL)
373 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
374 StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
377 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
379 if (Item->BounceTo == NULL)
380 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
381 StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
384 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
386 if (Item->SenderRoom == NULL)
387 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
388 StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
391 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
393 if (Item->Current == NULL)
395 if (Item->Current->Recipient == NULL)
396 Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
397 StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
398 Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
399 StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
400 Item->Current = NULL; // TODO: is this always right?
404 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
407 StrBufExtractNext_int(Line, Pos, '|');
412 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
414 Item->Submitted = atol(*Pos);
418 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
420 Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
426 * this one has to have the context for loading the message via the redirect buffer...
428 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
433 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
434 CtdlOutputMsg(MyQItem->MessageID,
435 MT_RFC822, HEADERS_ALL,
437 (ESC_DOT|SUPPRESS_ENV_TO) );
439 SendMsg = CCC->redirect_buffer;
440 CCC->redirect_buffer = NULL;
441 if ((StrLength(SendMsg) > 0) &&
442 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
444 "SMTP client[%d]: Possible problem: message did not "
445 "correctly terminate. (expecting 0x10, got 0x%02x)\n",
446 MsgCount, //yes uncool, but best choice here...
447 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
448 StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
456 * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
457 * instructions for "5" codes (permanent fatal errors) and produce/deliver
458 * a "bounce" message (delivery status notification).
460 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt)
464 struct CtdlMessage *bmsg = NULL;
468 struct recptypes *valid;
475 int successful_bounce = 0;
479 syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
481 if ( (ev_time() - MyQItem->Submitted) > SMTP_GIVE_UP ) {
482 give_up = 1;/// TODO: replace time by libevq timer get
486 * Now go through the instructions checking for stuff.
488 It = GetNewHashPos(MyQItem->MailQEntries, 0);
489 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
491 MailQEntry *ThisItem = vQE;
492 if ((ThisItem->Status == 5) || /* failed now? */
494 (ThisItem->Status != 2)))
495 /* giving up after failed attempts... */
497 if (num_bounces == 0)
498 Msg = NewStrBufPlain(NULL, 1024);
501 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
502 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
503 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
504 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
509 /* Deliver the bounce if there's anything worth mentioning */
510 syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
512 if (num_bounces == 0) {
517 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
518 StrBufAppendPrintf(boundary,
524 /* Start building our bounce message; go shopping for memory first. */
525 BounceMB = NewStrBufPlain(
527 1024 + /* mime stuff.... */
528 StrLength(Msg) + /* the bounce information... */
529 StrLength(OMsgTxt)); /* the original message */
530 if (BounceMB == NULL) {
531 FreeStrBuf(&boundary);
532 syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
537 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
539 FreeStrBuf(&boundary);
540 FreeStrBuf(&BounceMB);
541 syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
545 memset(bmsg, 0, sizeof(struct CtdlMessage));
548 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
549 StrBufAppendBuf(BounceMB, boundary, 0);
550 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
551 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
552 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
553 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
554 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
555 StrBufAppendBuf(BounceMB, boundary, 0);
556 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
557 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
560 StrBufAppendBufPlain(
563 "A message you sent could not be delivered "
564 "to some or all of its recipients\n"
565 "due to prolonged unavailability "
566 "of its destination(s).\n"
567 "Giving up on the following addresses:\n\n"
570 StrBufAppendBufPlain(
573 "A message you sent could not be delivered "
574 "to some or all of its recipients.\n"
575 "The following addresses "
576 "were undeliverable:\n\n"
579 StrBufAppendBuf(BounceMB, Msg, 0);
582 if (StrLength(MyQItem->SenderRoom) > 0)
584 StrBufAppendBufPlain(
586 HKEY("The message was originaly posted in: "), 0);
587 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
588 StrBufAppendBufPlain(
593 /* Attach the original message */
594 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
595 StrBufAppendBuf(BounceMB, boundary, 0);
596 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
597 StrBufAppendBufPlain(BounceMB,
598 HKEY("Content-type: message/rfc822\r\n"), 0);
599 StrBufAppendBufPlain(BounceMB,
600 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
601 StrBufAppendBufPlain(BounceMB,
602 HKEY("Content-Disposition: inline\r\n"), 0);
603 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
604 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
606 /* Close the multipart MIME scope */
607 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
608 StrBufAppendBuf(BounceMB, boundary, 0);
609 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
611 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
612 bmsg->cm_anon_type = MES_NORMAL;
613 bmsg->cm_format_type = FMT_RFC822;
615 bmsg->cm_fields['O'] = strdup(MAILROOM);
616 bmsg->cm_fields['A'] = strdup("Citadel");
617 bmsg->cm_fields['N'] = strdup(config.c_nodename);
618 bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
619 bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
621 /* First try the user who sent the message */
622 if (StrLength(MyQItem->BounceTo) == 0)
623 syslog(LOG_ERR, "No bounce address specified\n");
625 syslog(LOG_DEBUG, "bounce to user? <%s>\n",
626 ChrPtr(MyQItem->BounceTo));
628 /* Can we deliver the bounce to the original sender? */
629 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
630 if ((valid != NULL) && (valid->num_error == 0)) {
631 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
632 successful_bounce = 1;
635 /* If not, post it in the Aide> room */
636 if (successful_bounce == 0) {
637 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
640 /* Free up the memory we used */
641 free_recipients(valid);
642 FreeStrBuf(&boundary);
643 CtdlFreeMessage(bmsg);
644 syslog(LOG_DEBUG, "Done processing bounces\n");
650 * Called by smtp_do_queue() to handle an individual message.
652 void smtp_do_procmsg(long msgnum, void *userdata) {
653 int mynumsessions = num_sessions;
654 struct CtdlMessage *msg = NULL;
664 ParsedURL *RelayUrls = NULL;
668 if (mynumsessions > max_sessions_for_outbound_smtp) {
670 "SMTP Queue: skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
672 max_sessions_for_outbound_smtp);
675 syslog(LOG_DEBUG, "SMTP Queue: smtp_do_procmsg(%ld)\n", msgnum);
676 ///strcpy(envelope_from, "");
678 msg = CtdlFetchMessage(msgnum, 1);
680 syslog(LOG_ERR, "SMTP Queue: tried %ld but no such message!\n",
685 pch = instr = msg->cm_fields['M'];
687 /* Strip out the headers (no not amd any other non-instruction) line */
688 while (pch != NULL) {
689 pch = strchr(pch, '\n');
690 if ((pch != NULL) && (*(pch + 1) == '\n')) {
695 PlainQItem = NewStrBufPlain(instr, -1);
696 CtdlFreeMessage(msg);
697 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
698 FreeStrBuf(&PlainQItem);
700 if (MyQItem == NULL) {
702 "SMTP Queue: Msg No %ld: already in progress!\n",
704 return; /* s.b. else is already processing... */
708 * Postpone delivery if we've already tried recently.
710 if ((MyQItem->ReattemptWhen != 0) &&
711 (time(NULL) < MyQItem->ReattemptWhen) &&
712 (run_queue_now == 0))
714 syslog(LOG_DEBUG, "SMTP client: Retry time not yet reached.\n");
716 It = GetNewHashPos(MyQItem->MailQEntries, 0);
717 pthread_mutex_lock(&ActiveQItemsLock);
719 if (GetHashPosFromKey(ActiveQItems,
720 LKEY(MyQItem->MessageID),
723 DeleteEntryFromHash(ActiveQItems, It);
726 pthread_mutex_unlock(&ActiveQItemsLock);
727 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
733 * Bail out if there's no actual message associated with this
735 if (MyQItem->MessageID < 0L) {
736 syslog(LOG_ERR, "SMTP Queue: no 'msgid' directive found!\n");
737 It = GetNewHashPos(MyQItem->MailQEntries, 0);
738 pthread_mutex_lock(&ActiveQItemsLock);
740 if (GetHashPosFromKey(ActiveQItems,
741 LKEY(MyQItem->MessageID),
744 DeleteEntryFromHash(ActiveQItems, It);
747 pthread_mutex_unlock(&ActiveQItemsLock);
749 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
755 ParsedURL **Url = &MyQItem->URL;
756 nRelays = get_hosts(mxbuf, "smarthost");
760 const char *Pos = NULL;
761 All = NewStrBufPlain(mxbuf, -1);
762 One = NewStrBufPlain(NULL, StrLength(All) + 1);
764 while ((Pos != StrBufNOTNULL) &&
768 StrBufExtract_NextToken(One, All, &Pos, '|');
769 if (!ParseURL(Url, One, 25))
771 "Failed to parse: %s\n",
774 ///if (!Url->IsIP)) // todo dupe me fork ipv6
782 Url = &MyQItem->FallBackHost;
783 nRelays = get_hosts(mxbuf, "fallbackhost");
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",
808 It = GetNewHashPos(MyQItem->MailQEntries, 0);
809 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
811 MailQEntry *ThisItem = vQE;
812 syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
813 ChrPtr(ThisItem->Recipient),
818 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem);
820 /* failsafe against overload:
821 * will we exceed the limit set?
823 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
824 /* if yes, did we reach more than half of the quota? */
825 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
826 /* if... would we ever fit into half of the quota?? */
827 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
829 /* abort delivery for another time. */
831 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
833 MyQItem->ActiveDeliveries,
834 max_sessions_for_outbound_smtp);
836 FreeQueItem(&MyQItem);
842 if (MyQItem->ActiveDeliveries > 0)
846 int m = MyQItem->ActiveDeliveries;
848 Msg = smtp_load_msg(MyQItem, n);
849 It = GetNewHashPos(MyQItem->MailQEntries, 0);
851 (GetNextHashPos(MyQItem->MailQEntries,
852 It, &len, &Key, &vQE)))
854 MailQEntry *ThisItem = vQE;
856 if (ThisItem->Active == 1)
858 int KeepBuffers = (i == m);
861 if (nActivated % ndelay_count == 0)
864 if (i > 1) n = MsgCount++;
866 "SMTPQ: Trying <%ld> <%s> %d / %d \n",
868 ChrPtr(ThisItem->Recipient),
871 smtp_try_one_queue_entry(MyQItem,
878 if (KeepBuffers) HaveBuffers = 1;
887 It = GetNewHashPos(MyQItem->MailQEntries, 0);
888 pthread_mutex_lock(&ActiveQItemsLock);
890 if (GetHashPosFromKey(ActiveQItems,
891 LKEY(MyQItem->MessageID),
894 DeleteEntryFromHash(ActiveQItems, It);
903 "SMTP cleanup: unable to find "
904 "QItem with ID[%ld]",
906 while (GetNextHashPos(ActiveQItems,
913 "SMTP cleanup: have: ID[%ld]",
914 ((OneQueItem *)VData)->MessageID);
919 pthread_mutex_unlock(&ActiveQItemsLock);
921 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
923 // TODO: bounce & delete?
928 // TODO : free RelayUrls
935 * smtp_queue_thread()
937 * Run through the queue sending out messages.
939 void smtp_do_queue(void) {
940 static int is_running = 0;
941 int num_processed = 0;
944 return; /* Concurrency check - only one can run */
947 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
948 syslog(LOG_INFO, "SMTP client: processing outbound queue");
950 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
951 syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
954 num_processed = CtdlForEachMessage(MSGS_ALL,
963 "SMTP client: queue run completed; %d messages processed",
973 * Initialize the SMTP outbound queue
975 void smtp_init_spoolout(void) {
976 struct ctdlroom qrbuf;
979 * Create the room. This will silently fail if the room already
980 * exists, and that's perfectly ok, because we want it to exist.
982 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
985 * Make sure it's set to be a "system room" so it doesn't show up
986 * in the <K>nown rooms list for Aides.
988 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
989 qrbuf.QRflags2 |= QR2_SYSTEM;
990 CtdlPutRoomLock(&qrbuf);
997 /*****************************************************************************/
998 /* SMTP UTILITY COMMANDS */
999 /*****************************************************************************/
1001 void cmd_smtp(char *argbuf) {
1008 if (CtdlAccessCheck(ac_aide)) return;
1010 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1012 if (!strcasecmp(cmd, "mx")) {
1013 extract_token(node, argbuf, 1, '|', sizeof node);
1014 num_mxhosts = getmx(buf, node);
1015 cprintf("%d %d MX hosts listed for %s\n",
1016 LISTING_FOLLOWS, num_mxhosts, node);
1017 for (i=0; i<num_mxhosts; ++i) {
1018 extract_token(node, buf, i, '|', sizeof node);
1019 cprintf("%s\n", node);
1025 else if (!strcasecmp(cmd, "runqueue")) {
1027 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1032 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1038 CTDL_MODULE_INIT(smtp_queu)
1044 pstr = getenv("CITSERVER_n_session_max");
1045 if ((pstr != NULL) && (*pstr != '\0'))
1046 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1048 pstr = getenv("CITSERVER_smtp_n_delay_count");
1049 if ((pstr != NULL) && (*pstr != '\0'))
1050 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1052 pstr = getenv("CITSERVER_smtp_delay");
1053 if ((pstr != NULL) && (*pstr != '\0'))
1054 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1059 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1060 ActiveQItems = NewHash(1, lFlathash);
1061 pthread_mutex_init(&ActiveQItemsLock, NULL);
1063 QItemHandlers = NewHash(0, NULL);
1065 Put(QItemHandlers, HKEY("msgid"), QItem_Handle_MsgID, reference_free_handler);
1066 Put(QItemHandlers, HKEY("envelope_from"), QItem_Handle_EnvelopeFrom, reference_free_handler);
1067 Put(QItemHandlers, HKEY("retry"), QItem_Handle_retry, reference_free_handler);
1068 Put(QItemHandlers, HKEY("attempted"), QItem_Handle_Attempted, reference_free_handler);
1069 Put(QItemHandlers, HKEY("remote"), QItem_Handle_Recipient, reference_free_handler);
1070 Put(QItemHandlers, HKEY("bounceto"), QItem_Handle_BounceTo, reference_free_handler);
1071 Put(QItemHandlers, HKEY("source_room"), QItem_Handle_SenderRoom, reference_free_handler);
1072 Put(QItemHandlers, HKEY("submitted"), QItem_Handle_Submitted, reference_free_handler);
1073 smtp_init_spoolout();
1075 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1077 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1078 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER);
1081 /* return our Subversion id for the Log */
1082 return "smtpeventclient";