2 * Consolidate mail from remote POP3 accounts.
4 * Copyright (c) 2007-2015 by the citadel.org team
6 * This program is open source software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as published
8 * by the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
20 #include <sysconfig.h>
22 #if TIME_WITH_SYS_TIME
23 # include <sys/time.h>
27 # include <sys/time.h>
36 #include <sys/types.h>
38 #include <libcitadel.h>
41 #include "citserver.h"
44 #include "ctdl_module.h"
45 #include "clientsocket.h"
47 #include "internet_addressing.h"
49 #include "citadel_dirs.h"
50 #include "event_client.h"
53 #define POP3C_OK (strncasecmp(ChrPtr(RecvMsg->IO.IOBuf), "+OK", 3) == 0)
55 int POP3ClientDebugEnabled = 0;
57 #define N ((pop3aggr*)IO->Data)->n
59 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (POP3ClientDebugEnabled != 0))
61 #define EVP3C_syslog(LEVEL, FORMAT, ...) \
62 DBGLOG(LEVEL) syslog(LEVEL, \
63 "%s[%ld]CC[%d][%ld]POP3: " FORMAT, \
64 IOSTR, IO->ID, CCID, N, __VA_ARGS__)
66 #define EVP3CM_syslog(LEVEL, FORMAT) \
67 DBGLOG(LEVEL) syslog(LEVEL, \
68 "%s[%ld]CC[%d][%ld]POP3: " FORMAT, \
69 IOSTR, IO->ID, CCID, N)
71 #define EVP3CQ_syslog(LEVEL, FORMAT, ...) \
72 DBGLOG(LEVEL) syslog(LEVEL, \
76 #define EVP3CQM_syslog(LEVEL, FORMAT) \
77 DBGLOG(LEVEL) syslog(LEVEL, \
81 #define EVP3CCS_syslog(LEVEL, FORMAT, ...) \
82 DBGLOG(LEVEL) syslog(LEVEL, "%s[%ld][%ld]POP3: " FORMAT, \
83 IOSTR, IO->ID, N, __VA_ARGS__)
85 #define EVP3CCSM_syslog(LEVEL, FORMAT) \
86 DBGLOG(LEVEL) syslog(LEVEL, "%s[%ld][%ld]POP3: " FORMAT, \
89 #define POP3C_DBG_SEND() \
90 EVP3C_syslog(LOG_DEBUG, \
91 "%s[%ld]CC[%d][%ld]POP3: > %s\n", \
92 IOSTR, IO->ID, CCID, N, \
93 ChrPtr(RecvMsg->IO.SendBuf.Buf))
95 #define POP3C_DBG_READ() \
96 EVP3C_syslog(LOG_DEBUG, \
97 "%s[%ld]CC[%d][%ld]POP3: < %s\n", \
98 IOSTR, IO->ID, CCID, N, \
99 ChrPtr(RecvMsg->IO.IOBuf))
102 struct CitContext pop3_client_CC;
104 pthread_mutex_t POP3QueueMutex; /* locks the access to the following vars: */
105 HashList *POP3QueueRooms = NULL;
106 HashList *POP3FetchUrls = NULL;
108 typedef struct pop3aggr pop3aggr;
109 typedef eNextState(*Pop3ClientHandler)(pop3aggr* RecvMsg);
111 eNextState POP3_C_Shutdown(AsyncIO *IO);
112 eNextState POP3_C_Timeout(AsyncIO *IO);
113 eNextState POP3_C_ConnFail(AsyncIO *IO);
114 eNextState POP3_C_DNSFail(AsyncIO *IO);
115 eNextState POP3_C_DispatchReadDone(AsyncIO *IO);
116 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO);
117 eNextState POP3_C_Terminate(AsyncIO *IO);
118 eReadState POP3_C_ReadServerStatus(AsyncIO *IO);
119 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO);
121 typedef struct __pop3_room_counter {
126 typedef enum ePOP3_C_States {
132 GetOneMessageIDState,
133 ReadMessageBodyFollowing,
141 typedef struct _FetchItem {
147 struct CtdlMessage *Msg;
150 void HfreeFetchItem(void *vItem)
152 FetchItem *Item = (FetchItem*) vItem;
153 FreeStrBuf(&Item->MsgUIDL);
154 FreeStrBuf(&Item->MsgUID);
160 typedef enum _POP3State {
174 ConstStr POP3States[] = {
175 {HKEY("Aggregator created")},
176 {HKEY("Reading Greeting")},
177 {HKEY("Sending User")},
178 {HKEY("Sending Password")},
180 {HKEY("Fetching Usetable")},
181 {HKEY("Get MSG ID")},
182 {HKEY("Get Message")},
184 {HKEY("Delete Upstream")},
188 static void SetPOP3State(AsyncIO *IO, POP3State State)
190 CitContext* CCC = IO->CitContext;
192 memcpy(CCC->cs_clientname, POP3States[State].Key, POP3States[State].len + 1);
203 DNSQueryParts HostLookup;
206 HashList *OtherQRnumbers;
212 StrBuf *RoomName; // TODO: fill me
215 ePOP3_C_States State;
216 HashList *MsgNumbers;
221 void DeletePOP3Aggregator(void *vptr)
223 pop3aggr *ptr = vptr;
224 DeleteHashPos(&ptr->Pos);
225 DeleteHash(&ptr->MsgNumbers);
226 // FreeStrBuf(&ptr->rooms);
227 FreeStrBuf(&ptr->pop3user);
228 FreeStrBuf(&ptr->pop3pass);
229 FreeStrBuf(&ptr->Host);
230 FreeStrBuf(&ptr->RoomName);
231 FreeURL(&ptr->IO.ConnectMe);
232 FreeStrBuf(&ptr->Url);
233 FreeStrBuf(&ptr->IO.IOBuf);
234 FreeStrBuf(&ptr->IO.SendBuf.Buf);
235 FreeStrBuf(&ptr->IO.RecvBuf.Buf);
236 DeleteAsyncMsg(&ptr->IO.ReadMsg);
237 if (((struct CitContext*)ptr->IO.CitContext)) {
238 ((struct CitContext*)ptr->IO.CitContext)->state = CON_IDLE;
239 ((struct CitContext*)ptr->IO.CitContext)->kill_me = 1;
241 FreeAsyncIOContents(&ptr->IO);
245 eNextState FinalizePOP3AggrRun(AsyncIO *IO)
248 pop3aggr *cpptr = (pop3aggr *)IO->Data;
250 EVP3C_syslog(LOG_INFO,
251 "%s@%s: fetched %ld new of %d messages in %fs. bye.",
252 ChrPtr(cpptr->pop3user),
255 GetCount(cpptr->MsgNumbers),
256 IO->Now - cpptr->IOStart
259 It = GetNewHashPos(POP3FetchUrls, 0);
260 pthread_mutex_lock(&POP3QueueMutex);
262 if (GetHashPosFromKey(POP3FetchUrls, SKEY(cpptr->Url), It))
263 DeleteEntryFromHash(POP3FetchUrls, It);
265 pthread_mutex_unlock(&POP3QueueMutex);
270 eNextState FailAggregationRun(AsyncIO *IO)
275 eNextState POP3C_ReadGreeting(pop3aggr *RecvMsg)
277 AsyncIO *IO = &RecvMsg->IO;
278 SetPOP3State(IO, eGreeting);
280 /* Read the server greeting */
281 if (!POP3C_OK) return eTerminateConnection;
282 else return eSendReply;
285 eNextState POP3C_SendUser(pop3aggr *RecvMsg)
287 AsyncIO *IO = &RecvMsg->IO;
288 SetPOP3State(IO, eUser);
289 /* Identify ourselves. NOTE: we have to append a CR to each command.
290 * The LF will automatically be appended by sock_puts(). Believe it
291 * or not, leaving out the CR will cause problems if the server happens
292 * to be Exchange, which is so b0rken it actually barfs on
293 * LF-terminated newlines.
295 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
296 "USER %s\r\n", ChrPtr(RecvMsg->pop3user));
301 eNextState POP3C_GetUserState(pop3aggr *RecvMsg)
303 AsyncIO *IO = &RecvMsg->IO;
305 if (!POP3C_OK) return eTerminateConnection;
306 else return eSendReply;
309 eNextState POP3C_SendPassword(pop3aggr *RecvMsg)
311 AsyncIO *IO = &RecvMsg->IO;
312 SetPOP3State(IO, ePassword);
314 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
315 "PASS %s\r\n", ChrPtr(RecvMsg->pop3pass));
316 EVP3CM_syslog(LOG_DEBUG, "<PASS <password>\n");
317 // POP3C_DBG_SEND(); No, we won't write the passvoid to syslog...
321 eNextState POP3C_GetPassState(pop3aggr *RecvMsg)
323 AsyncIO *IO = &RecvMsg->IO;
325 if (!POP3C_OK) return eTerminateConnection;
326 else return eSendReply;
329 eNextState POP3C_SendListCommand(pop3aggr *RecvMsg)
331 AsyncIO *IO = &RecvMsg->IO;
332 SetPOP3State(IO, eListing);
334 /* Get the list of messages */
335 StrBufPlain(RecvMsg->IO.SendBuf.Buf, HKEY("LIST\r\n"));
340 eNextState POP3C_GetListCommandState(pop3aggr *RecvMsg)
342 AsyncIO *IO = &RecvMsg->IO;
344 if (!POP3C_OK) return eTerminateConnection;
345 RecvMsg->MsgNumbers = NewHash(1, NULL);
351 eNextState POP3C_GetListOneLine(pop3aggr *RecvMsg)
353 AsyncIO *IO = &RecvMsg->IO;
358 FetchItem *OneMsg = NULL;
361 if ((StrLength(RecvMsg->IO.IOBuf) == 1) &&
362 (ChrPtr(RecvMsg->IO.IOBuf)[0] == '.'))
364 if (GetCount(RecvMsg->MsgNumbers) == 0)
366 //// RecvMsg->Sate = ReadQuitState;
370 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
377 * work around buggy pop3 servers which send
378 * empty lines in their listings.
380 if ((StrLength(RecvMsg->IO.IOBuf) == 0) ||
381 !isdigit(ChrPtr(RecvMsg->IO.IOBuf)[0]))
386 OneMsg = (FetchItem*) malloc(sizeof(FetchItem));
387 memset(OneMsg, 0, sizeof(FetchItem));
388 OneMsg->MSGID = atol(ChrPtr(RecvMsg->IO.IOBuf));
390 pch = strchr(ChrPtr(RecvMsg->IO.IOBuf), ' ');
393 OneMsg->MSGSize = atol(pch + 1);
396 rc = TestValidateHash(RecvMsg->MsgNumbers);
398 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
401 Put(RecvMsg->MsgNumbers, LKEY(OneMsg->MSGID), OneMsg, HfreeFetchItem);
403 rc = TestValidateHash(RecvMsg->MsgNumbers);
405 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
407 //RecvMsg->State --; /* read next Line */
411 eNextState POP3_FetchNetworkUsetableEntry(AsyncIO *IO)
416 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
417 time_t seenstamp = 0;
419 SetPOP3State(IO, eUseTable);
421 if((RecvMsg->Pos != NULL) &&
422 GetNextHashPos(RecvMsg->MsgNumbers,
428 if (server_shutting_down)
431 RecvMsg->CurrMsg = (FetchItem*)vData;
433 seenstamp = CheckIfAlreadySeen("POP3 Item Seen",
434 RecvMsg->CurrMsg->MsgUID,
436 EvGetNow(IO) - USETABLE_ANTIEXPIRE,
441 /* Item has already been seen */
442 RecvMsg->CurrMsg->NeedFetch = 0;
446 EVP3CCSM_syslog(LOG_DEBUG, "NO\n");
447 RecvMsg->CurrMsg->NeedFetch = 1;
449 return NextDBOperation(&RecvMsg->IO,
450 POP3_FetchNetworkUsetableEntry);
454 /* ok, now we know them all,
455 * continue with reading the actual messages. */
456 DeleteHashPos(&RecvMsg->Pos);
457 return DBQueueEventContext(IO, POP3_C_ReAttachToFetchMessages);
461 eNextState POP3C_GetOneMessagID(pop3aggr *RecvMsg)
463 AsyncIO *IO = &RecvMsg->IO;
468 SetPOP3State(IO, eGetMsgID);
471 rc = TestValidateHash(RecvMsg->MsgNumbers);
473 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
475 if((RecvMsg->Pos != NULL) &&
476 GetNextHashPos(RecvMsg->MsgNumbers,
481 RecvMsg->CurrMsg = (FetchItem*) vData;
482 /* Find out the UIDL of the message,
483 * to determine whether we've already downloaded it */
484 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
485 "UIDL %ld\r\n", RecvMsg->CurrMsg->MSGID);
491 DeleteHashPos(&RecvMsg->Pos);
492 /// done receiving uidls.. start looking them up now.
493 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
494 return EventQueueDBOperation(&RecvMsg->IO,
495 POP3_FetchNetworkUsetableEntry,
498 return eReadMore; /* TODO */
501 eNextState POP3C_GetOneMessageIDState(pop3aggr *RecvMsg)
503 AsyncIO *IO = &RecvMsg->IO;
506 rc = TestValidateHash(RecvMsg->MsgNumbers);
508 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
512 if (!POP3C_OK) return eTerminateConnection;
513 RecvMsg->CurrMsg->MsgUIDL =
514 NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf));
515 RecvMsg->CurrMsg->MsgUID =
516 NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf) * 2);
518 StrBufExtract_token(RecvMsg->CurrMsg->MsgUIDL,
519 RecvMsg->IO.IOBuf, 2, ' ');
521 StrBufPrintf(RecvMsg->CurrMsg->MsgUID,
523 ChrPtr(RecvMsg->RoomName),
524 ChrPtr(RecvMsg->CurrMsg->MsgUIDL),
525 RecvMsg->IO.ConnectMe->User,
526 RecvMsg->IO.ConnectMe->Host);
532 eNextState POP3C_SendGetOneMsg(pop3aggr *RecvMsg)
534 AsyncIO *IO = &RecvMsg->IO;
539 SetPOP3State(IO, eGetMsg);
541 EVP3CM_syslog(LOG_DEBUG, "fast forwarding to the next unknown message");
543 RecvMsg->CurrMsg = NULL;
544 while ((RecvMsg->Pos != NULL) &&
545 GetNextHashPos(RecvMsg->MsgNumbers,
549 (RecvMsg->CurrMsg = (FetchItem*) vData,
550 RecvMsg->CurrMsg->NeedFetch == 0))
553 if ((RecvMsg->CurrMsg != NULL ) && (RecvMsg->CurrMsg->NeedFetch == 1))
555 EVP3CM_syslog(LOG_DEBUG, "fetching next");
556 /* Message has not been seen.
557 * Tell the server to fetch the message... */
558 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
559 "RETR %ld\r\n", RecvMsg->CurrMsg->MSGID);
564 EVP3CM_syslog(LOG_DEBUG, "no more messages to fetch.");
565 RecvMsg->State = ReadQuitState;
566 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
571 eNextState POP3C_ReadMessageBodyFollowing(pop3aggr *RecvMsg)
573 AsyncIO *IO = &RecvMsg->IO;
575 if (!POP3C_OK) return eTerminateConnection;
576 RecvMsg->IO.ReadMsg = NewAsyncMsg(HKEY("."),
577 RecvMsg->CurrMsg->MSGSize,
578 CtdlGetConfigLong("c_maxmsglen"),
586 eNextState POP3C_StoreMsgRead(AsyncIO *IO)
588 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
590 SetPOP3State(IO, eStoreMsg);
592 EVP3CCS_syslog(LOG_DEBUG,
593 "MARKING: %s as seen: ",
594 ChrPtr(RecvMsg->CurrMsg->MsgUID));
595 CheckIfAlreadySeen("POP3 Item Seen",
596 RecvMsg->CurrMsg->MsgUID,
598 EvGetNow(IO) - USETABLE_ANTIEXPIRE,
602 return DBQueueEventContext(&RecvMsg->IO, POP3_C_ReAttachToFetchMessages);
604 eNextState POP3C_SaveMsg(AsyncIO *IO)
607 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
609 /* Do Something With It (tm) */
610 msgnum = CtdlSubmitMsg(RecvMsg->CurrMsg->Msg,
612 ChrPtr(RecvMsg->RoomName),
616 /* Message has been committed to the store
617 * write the uidl to the use table
618 * so we don't fetch this message again
621 CM_Free(RecvMsg->CurrMsg->Msg);
624 return NextDBOperation(&RecvMsg->IO, POP3C_StoreMsgRead);
627 eNextState POP3C_ReadMessageBody(pop3aggr *RecvMsg)
629 AsyncIO *IO = &RecvMsg->IO;
630 EVP3CM_syslog(LOG_DEBUG, "Converting message...");
631 RecvMsg->CurrMsg->Msg =
632 convert_internet_message_buf(&RecvMsg->IO.ReadMsg->MsgBuf);
633 return EventQueueDBOperation(&RecvMsg->IO, POP3C_SaveMsg, 0);
636 eNextState POP3C_SendDelete(pop3aggr *RecvMsg)
638 AsyncIO *IO = &RecvMsg->IO;
640 SetPOP3State(IO, eDelete);
642 if (!RecvMsg->keep) {
643 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
644 "DELE %ld\r\n", RecvMsg->CurrMsg->MSGID);
649 RecvMsg->State = ReadMessageBodyFollowing;
650 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
653 eNextState POP3C_ReadDeleteState(pop3aggr *RecvMsg)
655 AsyncIO *IO = &RecvMsg->IO;
657 RecvMsg->State = GetOneMessageIDState;
658 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
661 eNextState POP3C_SendQuit(pop3aggr *RecvMsg)
663 AsyncIO *IO = &RecvMsg->IO;
664 SetPOP3State(IO, eQuit);
667 StrBufPlain(RecvMsg->IO.SendBuf.Buf,
674 eNextState POP3C_ReadQuitState(pop3aggr *RecvMsg)
676 AsyncIO *IO = &RecvMsg->IO;
678 return eTerminateConnection;
681 const long POP3_C_ConnTimeout = 1000;
682 const long DefaultPOP3Port = 110;
684 Pop3ClientHandler POP3C_ReadHandlers[] = {
688 POP3C_GetListCommandState,
689 POP3C_GetListOneLine,
690 POP3C_GetOneMessageIDState,
691 POP3C_ReadMessageBodyFollowing,
692 POP3C_ReadMessageBody,
693 POP3C_ReadDeleteState,
697 const long POP3_C_SendTimeouts[POP3C_MaxRead] = {
707 const ConstStr POP3C_ReadErrors[POP3C_MaxRead] = {
708 {HKEY("Connection broken during ")},
709 {HKEY("Connection broken during ")},
710 {HKEY("Connection broken during ")},
711 {HKEY("Connection broken during ")},
712 {HKEY("Connection broken during ")},
713 {HKEY("Connection broken during ")},
714 {HKEY("Connection broken during ")},
715 {HKEY("Connection broken during ")}
718 Pop3ClientHandler POP3C_SendHandlers[] = {
719 NULL, /* we don't send a greeting */
722 POP3C_SendListCommand,
724 POP3C_GetOneMessagID,
731 const long POP3_C_ReadTimeouts[] = {
743 /*****************************************************************************/
744 /* POP3 CLIENT DISPATCHER */
745 /*****************************************************************************/
747 void POP3SetTimeout(eNextState NextTCPState, pop3aggr *pMsg)
749 AsyncIO *IO = &pMsg->IO;
750 double Timeout = 0.0;
752 EVP3C_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
754 switch (NextTCPState) {
758 Timeout = POP3_C_SendTimeouts[pMsg->State];
760 if (pMsg->State == eDATABody) {
761 / * if we're sending a huge message, we need more time. * /
762 Timeout += StrLength(pMsg->msgtext) / 1024;
768 Timeout = POP3_C_ReadTimeouts[pMsg->State];
770 if (pMsg->State == eDATATerminateBody) {
772 * some mailservers take a nap before accepting the message
773 * content inspection and such.
775 Timeout += StrLength(pMsg->msgtext) / 1024;
786 case eTerminateConnection:
789 case eReadMore://// TODO
792 SetNextTimeout(&pMsg->IO, Timeout);
794 eNextState POP3_C_DispatchReadDone(AsyncIO *IO)
796 /* EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
797 pop3aggr *pMsg = IO->Data;
800 rc = POP3C_ReadHandlers[pMsg->State](pMsg);
803 POP3SetTimeout(rc, pMsg);
806 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO)
808 pop3aggr *pMsg = IO->Data;
811 /* EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
812 rc = POP3C_SendHandlers[pMsg->State](pMsg);
813 POP3SetTimeout(rc, pMsg);
818 /*****************************************************************************/
819 /* POP3 CLIENT ERROR CATCHERS */
820 /*****************************************************************************/
821 eNextState POP3_C_Terminate(AsyncIO *IO)
823 /// pop3aggr *pMsg = (pop3aggr *)IO->Data;
825 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
826 FinalizePOP3AggrRun(IO);
829 eNextState POP3_C_TerminateDB(AsyncIO *IO)
831 /// pop3aggr *pMsg = (pop3aggr *)IO->Data;
833 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
834 FinalizePOP3AggrRun(IO);
837 eNextState POP3_C_Timeout(AsyncIO *IO)
839 pop3aggr *pMsg = IO->Data;
841 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
842 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
843 return FailAggregationRun(IO);
845 eNextState POP3_C_ConnFail(AsyncIO *IO)
847 pop3aggr *pMsg = (pop3aggr *)IO->Data;
849 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
850 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
851 return FailAggregationRun(IO);
853 eNextState POP3_C_DNSFail(AsyncIO *IO)
855 pop3aggr *pMsg = (pop3aggr *)IO->Data;
857 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
858 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
859 return FailAggregationRun(IO);
861 eNextState POP3_C_Shutdown(AsyncIO *IO)
863 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
864 //// pop3aggr *pMsg = IO->Data;
866 ////pMsg->MyQEntry->Status = 3;
867 ///StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message retrieval."));
868 FinalizePOP3AggrRun(IO);
874 * @brief lineread Handler; understands when to read more POP3 lines,
875 * and when this is a one-lined reply.
877 eReadState POP3_C_ReadServerStatus(AsyncIO *IO)
879 eReadState Finished = eBufferNotEmpty;
881 switch (IO->NextState) {
886 case eTerminateConnection:
888 Finished = eReadFail;
895 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
899 Finished = CtdlReadMessageBodyAsync(IO);
905 /*****************************************************************************
906 * So we connect our Server IP here. *
907 *****************************************************************************/
908 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO)
910 pop3aggr *cpptr = IO->Data;
912 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
913 ////??? cpptr->State ++;
914 if (cpptr->Pos == NULL)
915 cpptr->Pos = GetNewHashPos(cpptr->MsgNumbers, 0);
917 POP3_C_DispatchWriteDone(IO);
918 ReAttachIO(IO, cpptr, 0);
919 IO->NextState = eReadMessage;
920 return IO->NextState;
923 eNextState pop3_connect_ip(AsyncIO *IO)
925 pop3aggr *cpptr = IO->Data;
927 if (cpptr->IOStart == 0.0) /* whith or without DNS? */
928 cpptr->IOStart = IO->Now;
930 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
932 return EvConnectSock(IO,
934 POP3_C_ReadTimeouts[0],
938 eNextState pop3_get_one_host_ip_done(AsyncIO *IO)
940 pop3aggr *cpptr = IO->Data;
941 struct hostent *hostent;
945 hostent = cpptr->HostLookup.VParsedDNSReply;
946 if ((cpptr->HostLookup.DNSStatus == ARES_SUCCESS) &&
947 (hostent != NULL) ) {
948 memset(&cpptr->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
949 if (cpptr->IO.ConnectMe->IPv6) {
950 memcpy(&cpptr->IO.ConnectMe->Addr.sin6_addr.s6_addr,
951 &hostent->h_addr_list[0],
952 sizeof(struct in6_addr));
954 cpptr->IO.ConnectMe->Addr.sin6_family =
956 cpptr->IO.ConnectMe->Addr.sin6_port =
957 htons(DefaultPOP3Port);
960 struct sockaddr_in *addr =
961 (struct sockaddr_in*)
962 &cpptr->IO.ConnectMe->Addr;
964 memcpy(&addr->sin_addr.s_addr,
965 hostent->h_addr_list[0],
968 addr->sin_family = hostent->h_addrtype;
969 addr->sin_port = htons(DefaultPOP3Port);
971 return pop3_connect_ip(IO);
977 eNextState pop3_get_one_host_ip(AsyncIO *IO)
979 pop3aggr *cpptr = IO->Data;
981 cpptr->IOStart = IO->Now;
983 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
985 EVP3CCS_syslog(LOG_DEBUG,
986 "POP3 client[%ld]: looking up %s-Record %s : %d ...\n",
988 (cpptr->IO.ConnectMe->IPv6)? "aaaa": "a",
989 cpptr->IO.ConnectMe->Host,
990 cpptr->IO.ConnectMe->Port);
992 QueueQuery((cpptr->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a,
993 cpptr->IO.ConnectMe->Host,
996 pop3_get_one_host_ip_done);
997 IO->NextState = eReadDNSReply;
998 return IO->NextState;
1003 int pop3_do_fetching(pop3aggr *cpptr)
1005 AsyncIO *IO = &cpptr->IO;
1010 POP3_C_ReadServerStatus,
1012 POP3_C_DispatchWriteDone,
1013 POP3_C_DispatchReadDone,
1020 safestrncpy(((CitContext *)cpptr->IO.CitContext)->cs_host,
1022 sizeof(((CitContext *)cpptr->IO.CitContext)->cs_host));
1024 if (cpptr->IO.ConnectMe->IsIP) {
1025 QueueEventContext(&cpptr->IO,
1029 QueueEventContext(&cpptr->IO,
1030 pop3_get_one_host_ip);
1036 * Scan a room's netconfig to determine whether it requires POP3 aggregation
1038 void pop3client_scan_room(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCFG)
1040 const RoomNetCfgLine *pLine;
1043 pthread_mutex_lock(&POP3QueueMutex);
1044 if (GetHash(POP3QueueRooms, LKEY(qrbuf->QRnumber), &vptr))
1046 pthread_mutex_unlock(&POP3QueueMutex);
1047 EVP3CQ_syslog(LOG_DEBUG,
1048 "pop3client: [%ld] %s already in progress.",
1053 pthread_mutex_unlock(&POP3QueueMutex);
1055 if (server_shutting_down) return;
1057 pLine = OneRNCFG->NetConfigs[pop3client];
1059 while (pLine != NULL)
1063 cptr = (pop3aggr *) malloc(sizeof(pop3aggr));
1064 memset(cptr, 0, sizeof(pop3aggr));
1065 ///TODO do we need this? cptr->roomlist_parts=1;
1066 cptr->RoomName = NewStrBufPlain(qrbuf->QRname, -1);
1067 cptr->pop3user = NewStrBufDup(pLine->Value[1]);
1068 cptr->pop3pass = NewStrBufDup(pLine->Value[2]);
1069 cptr->Url = NewStrBuf();
1070 cptr->Host = NewStrBufDup(pLine->Value[0]);
1072 cptr->keep = atol(ChrPtr(pLine->Value[3]));
1073 cptr->interval = atol(ChrPtr(pLine->Value[4]));
1075 StrBufAppendBufPlain(cptr->Url, HKEY("pop3://"), 0);
1076 StrBufUrlescUPAppend(cptr->Url, cptr->pop3user, NULL);
1077 StrBufAppendBufPlain(cptr->Url, HKEY(":"), 0);
1078 StrBufUrlescUPAppend(cptr->Url, cptr->pop3pass, NULL);
1079 StrBufAppendBufPlain(cptr->Url, HKEY("@"), 0);
1080 StrBufAppendBuf(cptr->Url, cptr->Host, 0);
1081 StrBufAppendBufPlain(cptr->Url, HKEY("/"), 0);
1082 StrBufUrlescAppend(cptr->Url, cptr->RoomName, NULL);
1084 ParseURL(&cptr->IO.ConnectMe, cptr->Url, 110);
1088 /* todo: we need to reunite the url to be shure. */
1090 pthread_mutex_lock(&POP3ueueMutex);
1091 GetHash(POP3FetchUrls, SKEY(ptr->Url), &vptr);
1092 use_this_cptr = (pop3aggr *)vptr;
1094 if (use_this_rncptr != NULL)
1096 /* mustn't attach to an active session */
1097 if (use_this_cptr->RefCount > 0)
1099 DeletePOP3Cfg(cptr);
1105 StrBufAppendBufPlain(
1106 use_this_cptr->rooms,
1109 if (use_this_cptr->roomlist_parts == 1)
1111 use_this_cptr->OtherQRnumbers
1112 = NewHash(1, lFlathash);
1114 QRnumber = (long*)malloc(sizeof(long));
1115 *QRnumber = qrbuf->QRnumber;
1116 Put(use_this_cptr->OtherQRnumbers,
1117 LKEY(qrbuf->QRnumber),
1121 use_this_cptr->roomlist_parts++;
1123 pthread_mutex_unlock(&POP3QueueMutex);
1126 pthread_mutex_unlock(&RSSQueueMutex);
1128 cptr->n = Pop3ClientID++;
1129 pthread_mutex_lock(&POP3QueueMutex);
1133 DeletePOP3Aggregator);
1135 pthread_mutex_unlock(&POP3QueueMutex);
1136 pLine = pLine->next;
1141 static int doing_pop3client = 0;
1143 void pop3client_scan(void) {
1144 static time_t last_run = 0L;
1145 time_t fastest_scan;
1152 become_session(&pop3_client_CC);
1154 if (CtdlGetConfigLong("c_pop3_fastest") < CtdlGetConfigLong("c_pop3_fetch"))
1155 fastest_scan = CtdlGetConfigLong("c_pop3_fastest");
1157 fastest_scan = CtdlGetConfigLong("c_pop3_fetch");
1160 * Run POP3 aggregation no more frequently than once every n seconds
1162 if ( (time(NULL) - last_run) < fastest_scan ) {
1167 * This is a simple concurrency check to make sure only one pop3client
1168 * run is done at a time. We could do this with a mutex, but since we
1169 * don't really require extremely fine granularity here, we'll do it
1170 * with a static variable instead.
1172 if (doing_pop3client) return;
1173 doing_pop3client = 1;
1175 EVP3CQM_syslog(LOG_DEBUG, "pop3client started");
1176 CtdlForEachNetCfgRoom(pop3client_scan_room, NULL, pop3client);
1178 pthread_mutex_lock(&POP3QueueMutex);
1179 it = GetNewHashPos(POP3FetchUrls, 0);
1180 while (!server_shutting_down &&
1181 GetNextHashPos(POP3FetchUrls, it, &len, &Key, &vrptr) &&
1183 cptr = (pop3aggr *)vrptr;
1184 if (cptr->RefCount == 0)
1185 if (!pop3_do_fetching(cptr))
1186 DeletePOP3Aggregator(cptr);////TODO
1189 if ((palist->interval && time(NULL) > (last_run + palist->interval))
1190 || (time(NULL) > last_run + CtdlGetConfigLong("c_pop3_fetch")))
1191 pop3_do_fetching(palist->roomname, palist->pop3host,
1192 palist->pop3user, palist->pop3pass, palist->keep);
1194 palist = palist->next;
1199 pthread_mutex_unlock(&POP3QueueMutex);
1201 EVP3CQM_syslog(LOG_DEBUG, "pop3client ended");
1202 last_run = time(NULL);
1203 doing_pop3client = 0;
1207 void pop3_cleanup(void)
1209 /* citthread_mutex_destroy(&POP3QueueMutex); TODO */
1210 while (doing_pop3client != 0) ;
1211 DeleteHash(&POP3FetchUrls);
1212 DeleteHash(&POP3QueueRooms);
1217 void LogDebugEnablePOP3Client(const int n)
1219 POP3ClientDebugEnabled = n;
1222 CTDL_MODULE_INIT(pop3client)
1226 CtdlFillSystemContext(&pop3_client_CC, "POP3aggr");
1227 CtdlREGISTERRoomCfgType(pop3client, ParseGeneric, 0, 5, SerializeGeneric, DeleteGenericCfgLine);
1228 pthread_mutex_init(&POP3QueueMutex, NULL);
1229 POP3QueueRooms = NewHash(1, lFlathash);
1230 POP3FetchUrls = NewHash(1, NULL);
1231 CtdlRegisterSessionHook(pop3client_scan, EVT_TIMER, PRIO_AGGR + 50);
1232 CtdlRegisterEVCleanupHook(pop3_cleanup);
1233 CtdlRegisterDebugFlagHook(HKEY("pop3client"), LogDebugEnablePOP3Client, &POP3ClientDebugEnabled);
1236 /* return our module id for the log */
1237 return "pop3client";