2 * Consolidate mail from remote POP3 accounts.
4 * Copyright (c) 2007-2017 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)
56 #define N ((pop3aggr*)IO->Data)->n
58 struct CitContext pop3_client_CC;
60 pthread_mutex_t POP3QueueMutex; /* locks the access to the following vars: */
61 HashList *POP3QueueRooms = NULL;
62 HashList *POP3FetchUrls = NULL;
64 typedef struct pop3aggr pop3aggr;
65 typedef eNextState(*Pop3ClientHandler)(pop3aggr* RecvMsg);
67 eNextState POP3_C_Shutdown(AsyncIO *IO);
68 eNextState POP3_C_Timeout(AsyncIO *IO);
69 eNextState POP3_C_ConnFail(AsyncIO *IO);
70 eNextState POP3_C_DNSFail(AsyncIO *IO);
71 eNextState POP3_C_DispatchReadDone(AsyncIO *IO);
72 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO);
73 eNextState POP3_C_Terminate(AsyncIO *IO);
74 eReadState POP3_C_ReadServerStatus(AsyncIO *IO);
75 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO);
77 typedef struct __pop3_room_counter {
82 typedef enum ePOP3_C_States {
89 ReadMessageBodyFollowing,
97 typedef struct _FetchItem {
103 struct CtdlMessage *Msg;
106 void HfreeFetchItem(void *vItem)
108 FetchItem *Item = (FetchItem*) vItem;
109 FreeStrBuf(&Item->MsgUIDL);
110 FreeStrBuf(&Item->MsgUID);
116 typedef enum _POP3State {
130 ConstStr POP3States[] = {
131 {HKEY("Aggregator created")},
132 {HKEY("Reading Greeting")},
133 {HKEY("Sending User")},
134 {HKEY("Sending Password")},
136 {HKEY("Fetching Usetable")},
137 {HKEY("Get MSG ID")},
138 {HKEY("Get Message")},
140 {HKEY("Delete Upstream")},
144 static void SetPOP3State(AsyncIO *IO, POP3State State)
146 CitContext* CCC = IO->CitContext;
148 memcpy(CCC->cs_clientname, POP3States[State].Key, POP3States[State].len + 1);
159 DNSQueryParts HostLookup;
162 HashList *OtherQRnumbers;
168 StrBuf *RoomName; // TODO: fill me
171 ePOP3_C_States State;
172 HashList *MsgNumbers;
177 void DeletePOP3Aggregator(void *vptr)
179 pop3aggr *ptr = vptr;
180 DeleteHashPos(&ptr->Pos);
181 DeleteHash(&ptr->MsgNumbers);
182 // FreeStrBuf(&ptr->rooms);
183 FreeStrBuf(&ptr->pop3user);
184 FreeStrBuf(&ptr->pop3pass);
185 FreeStrBuf(&ptr->Host);
186 FreeStrBuf(&ptr->RoomName);
187 FreeURL(&ptr->IO.ConnectMe);
188 FreeStrBuf(&ptr->Url);
189 FreeStrBuf(&ptr->IO.IOBuf);
190 FreeStrBuf(&ptr->IO.SendBuf.Buf);
191 FreeStrBuf(&ptr->IO.RecvBuf.Buf);
192 DeleteAsyncMsg(&ptr->IO.ReadMsg);
193 if (((struct CitContext*)ptr->IO.CitContext)) {
194 ((struct CitContext*)ptr->IO.CitContext)->state = CON_IDLE;
195 ((struct CitContext*)ptr->IO.CitContext)->kill_me = 1;
197 FreeAsyncIOContents(&ptr->IO);
201 eNextState FinalizePOP3AggrRun(AsyncIO *IO)
204 pop3aggr *cpptr = (pop3aggr *)IO->Data;
207 "%s@%s: fetched %ld new of %d messages in %fs. bye.",
208 ChrPtr(cpptr->pop3user),
211 GetCount(cpptr->MsgNumbers),
212 IO->Now - cpptr->IOStart
215 It = GetNewHashPos(POP3FetchUrls, 0);
216 pthread_mutex_lock(&POP3QueueMutex);
218 if (GetHashPosFromKey(POP3FetchUrls, SKEY(cpptr->Url), It))
219 DeleteEntryFromHash(POP3FetchUrls, It);
221 pthread_mutex_unlock(&POP3QueueMutex);
226 eNextState FailAggregationRun(AsyncIO *IO)
231 eNextState POP3C_ReadGreeting(pop3aggr *RecvMsg)
233 AsyncIO *IO = &RecvMsg->IO;
234 SetPOP3State(IO, eGreeting);
235 /* Read the server greeting */
236 if (!POP3C_OK) return eTerminateConnection;
237 else return eSendReply;
240 eNextState POP3C_SendUser(pop3aggr *RecvMsg)
242 AsyncIO *IO = &RecvMsg->IO;
243 SetPOP3State(IO, eUser);
244 /* Identify ourselves. NOTE: we have to append a CR to each command.
245 * The LF will automatically be appended by sock_puts(). Believe it
246 * or not, leaving out the CR will cause problems if the server happens
247 * to be Exchange, which is so b0rken it actually barfs on
248 * LF-terminated newlines.
250 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
251 "USER %s\r\n", ChrPtr(RecvMsg->pop3user));
255 eNextState POP3C_GetUserState(pop3aggr *RecvMsg)
257 if (!POP3C_OK) return eTerminateConnection;
258 else return eSendReply;
261 eNextState POP3C_SendPassword(pop3aggr *RecvMsg)
263 AsyncIO *IO = &RecvMsg->IO;
264 SetPOP3State(IO, ePassword);
266 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
267 "PASS %s\r\n", ChrPtr(RecvMsg->pop3pass));
268 syslog(LOG_DEBUG, "<PASS <password>\n");
272 eNextState POP3C_GetPassState(pop3aggr *RecvMsg)
274 if (!POP3C_OK) return eTerminateConnection;
275 else return eSendReply;
278 eNextState POP3C_SendListCommand(pop3aggr *RecvMsg)
280 AsyncIO *IO = &RecvMsg->IO;
281 SetPOP3State(IO, eListing);
283 /* Get the list of messages */
284 StrBufPlain(RecvMsg->IO.SendBuf.Buf, HKEY("LIST\r\n"));
288 eNextState POP3C_GetListCommandState(pop3aggr *RecvMsg)
290 if (!POP3C_OK) return eTerminateConnection;
291 RecvMsg->MsgNumbers = NewHash(1, NULL);
297 eNextState POP3C_GetListOneLine(pop3aggr *RecvMsg)
303 FetchItem *OneMsg = NULL;
305 if ((StrLength(RecvMsg->IO.IOBuf) == 1) &&
306 (ChrPtr(RecvMsg->IO.IOBuf)[0] == '.'))
308 if (GetCount(RecvMsg->MsgNumbers) == 0)
310 //// RecvMsg->Sate = ReadQuitState;
314 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
321 * work around buggy pop3 servers which send
322 * empty lines in their listings.
324 if ((StrLength(RecvMsg->IO.IOBuf) == 0) ||
325 !isdigit(ChrPtr(RecvMsg->IO.IOBuf)[0]))
330 OneMsg = (FetchItem*) malloc(sizeof(FetchItem));
331 memset(OneMsg, 0, sizeof(FetchItem));
332 OneMsg->MSGID = atol(ChrPtr(RecvMsg->IO.IOBuf));
334 pch = strchr(ChrPtr(RecvMsg->IO.IOBuf), ' ');
337 OneMsg->MSGSize = atol(pch + 1);
340 rc = TestValidateHash(RecvMsg->MsgNumbers);
342 syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
345 Put(RecvMsg->MsgNumbers, LKEY(OneMsg->MSGID), OneMsg, HfreeFetchItem);
347 rc = TestValidateHash(RecvMsg->MsgNumbers);
349 syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
351 //RecvMsg->State --; /* read next Line */
355 eNextState POP3_FetchNetworkUsetableEntry(AsyncIO *IO)
360 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
361 time_t seenstamp = 0;
363 SetPOP3State(IO, eUseTable);
365 if((RecvMsg->Pos != NULL) &&
366 GetNextHashPos(RecvMsg->MsgNumbers,
372 if (server_shutting_down)
375 RecvMsg->CurrMsg = (FetchItem*)vData;
377 seenstamp = CheckIfAlreadySeen(RecvMsg->CurrMsg->MsgUID,
379 EvGetNow(IO) - USETABLE_ANTIEXPIRE,
384 /* Item has already been seen */
385 RecvMsg->CurrMsg->NeedFetch = 0;
389 syslog(LOG_DEBUG, "NO\n");
390 RecvMsg->CurrMsg->NeedFetch = 1;
392 return NextDBOperation(&RecvMsg->IO,
393 POP3_FetchNetworkUsetableEntry);
397 /* ok, now we know them all,
398 * continue with reading the actual messages. */
399 DeleteHashPos(&RecvMsg->Pos);
400 return DBQueueEventContext(IO, POP3_C_ReAttachToFetchMessages);
404 eNextState POP3C_GetOneMessagID(pop3aggr *RecvMsg)
406 AsyncIO *IO = &RecvMsg->IO;
411 SetPOP3State(IO, eGetMsgID);
414 rc = TestValidateHash(RecvMsg->MsgNumbers);
416 syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
418 if((RecvMsg->Pos != NULL) &&
419 GetNextHashPos(RecvMsg->MsgNumbers,
424 RecvMsg->CurrMsg = (FetchItem*) vData;
425 /* Find out the UIDL of the message,
426 * to determine whether we've already downloaded it */
427 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
428 "UIDL %ld\r\n", RecvMsg->CurrMsg->MSGID);
433 DeleteHashPos(&RecvMsg->Pos);
434 /// done receiving uidls.. start looking them up now.
435 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
436 return EventQueueDBOperation(&RecvMsg->IO,
437 POP3_FetchNetworkUsetableEntry,
440 return eReadMore; /* TODO */
443 eNextState POP3C_GetOneMessageIDState(pop3aggr *RecvMsg)
447 rc = TestValidateHash(RecvMsg->MsgNumbers);
449 syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
452 if (!POP3C_OK) return eTerminateConnection;
453 RecvMsg->CurrMsg->MsgUIDL = NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf));
454 RecvMsg->CurrMsg->MsgUID = NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf) * 2);
456 StrBufExtract_token(RecvMsg->CurrMsg->MsgUIDL, RecvMsg->IO.IOBuf, 2, ' ');
458 StrBufPrintf(RecvMsg->CurrMsg->MsgUID,
460 ChrPtr(RecvMsg->RoomName),
461 ChrPtr(RecvMsg->CurrMsg->MsgUIDL),
462 RecvMsg->IO.ConnectMe->User,
463 RecvMsg->IO.ConnectMe->Host
470 eNextState POP3C_SendGetOneMsg(pop3aggr *RecvMsg)
472 AsyncIO *IO = &RecvMsg->IO;
477 SetPOP3State(IO, eGetMsg);
479 syslog(LOG_DEBUG, "fast forwarding to the next unknown message");
481 RecvMsg->CurrMsg = NULL;
482 while ((RecvMsg->Pos != NULL) &&
483 GetNextHashPos(RecvMsg->MsgNumbers,
487 (RecvMsg->CurrMsg = (FetchItem*) vData,
488 RecvMsg->CurrMsg->NeedFetch == 0))
491 if ((RecvMsg->CurrMsg != NULL ) && (RecvMsg->CurrMsg->NeedFetch == 1))
493 syslog(LOG_DEBUG, "fetching next");
494 /* Message has not been seen.
495 * Tell the server to fetch the message... */
496 StrBufPrintf(RecvMsg->IO.SendBuf.Buf, "RETR %ld\r\n", RecvMsg->CurrMsg->MSGID);
500 syslog(LOG_DEBUG, "no more messages to fetch.");
501 RecvMsg->State = ReadQuitState;
502 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
507 eNextState POP3C_ReadMessageBodyFollowing(pop3aggr *RecvMsg)
509 if (!POP3C_OK) return eTerminateConnection;
510 RecvMsg->IO.ReadMsg = NewAsyncMsg(HKEY("."),
511 RecvMsg->CurrMsg->MSGSize,
512 CtdlGetConfigLong("c_maxmsglen"),
521 eNextState POP3C_StoreMsgRead(AsyncIO *IO)
523 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
525 SetPOP3State(IO, eStoreMsg);
527 syslog(LOG_DEBUG, "MARKING: %s as seen: ", ChrPtr(RecvMsg->CurrMsg->MsgUID));
528 CheckIfAlreadySeen(RecvMsg->CurrMsg->MsgUID, EvGetNow(IO), EvGetNow(IO) - USETABLE_ANTIEXPIRE, eWrite);
530 return DBQueueEventContext(&RecvMsg->IO, POP3_C_ReAttachToFetchMessages);
534 eNextState POP3C_SaveMsg(AsyncIO *IO)
537 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
539 /* Do Something With It (tm) */
540 msgnum = CtdlSubmitMsg(RecvMsg->CurrMsg->Msg,
542 ChrPtr(RecvMsg->RoomName),
546 /* Message has been committed to the store
547 * write the uidl to the use table
548 * so we don't fetch this message again
551 CM_Free(RecvMsg->CurrMsg->Msg);
554 return NextDBOperation(&RecvMsg->IO, POP3C_StoreMsgRead);
558 eNextState POP3C_ReadMessageBody(pop3aggr *RecvMsg)
560 syslog(LOG_DEBUG, "Converting message...");
561 RecvMsg->CurrMsg->Msg = convert_internet_message_buf(&RecvMsg->IO.ReadMsg->MsgBuf);
562 return EventQueueDBOperation(&RecvMsg->IO, POP3C_SaveMsg, 0);
566 eNextState POP3C_SendDelete(pop3aggr *RecvMsg)
568 AsyncIO *IO = &RecvMsg->IO;
570 SetPOP3State(IO, eDelete);
572 if (!RecvMsg->keep) {
573 StrBufPrintf(RecvMsg->IO.SendBuf.Buf, "DELE %ld\r\n", RecvMsg->CurrMsg->MSGID);
577 RecvMsg->State = ReadMessageBodyFollowing;
578 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
583 eNextState POP3C_ReadDeleteState(pop3aggr *RecvMsg)
585 RecvMsg->State = GetOneMessageIDState;
586 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
590 eNextState POP3C_SendQuit(pop3aggr *RecvMsg)
592 AsyncIO *IO = &RecvMsg->IO;
593 SetPOP3State(IO, eQuit);
596 StrBufPlain(RecvMsg->IO.SendBuf.Buf,
602 eNextState POP3C_ReadQuitState(pop3aggr *RecvMsg)
604 return eTerminateConnection;
608 const long POP3_C_ConnTimeout = 1000;
609 const long DefaultPOP3Port = 110;
611 Pop3ClientHandler POP3C_ReadHandlers[] = {
615 POP3C_GetListCommandState,
616 POP3C_GetListOneLine,
617 POP3C_GetOneMessageIDState,
618 POP3C_ReadMessageBodyFollowing,
619 POP3C_ReadMessageBody,
620 POP3C_ReadDeleteState,
624 const long POP3_C_SendTimeouts[POP3C_MaxRead] = {
634 const ConstStr POP3C_ReadErrors[POP3C_MaxRead] = {
635 {HKEY("Connection broken during ")},
636 {HKEY("Connection broken during ")},
637 {HKEY("Connection broken during ")},
638 {HKEY("Connection broken during ")},
639 {HKEY("Connection broken during ")},
640 {HKEY("Connection broken during ")},
641 {HKEY("Connection broken during ")},
642 {HKEY("Connection broken during ")}
645 Pop3ClientHandler POP3C_SendHandlers[] = {
646 NULL, /* we don't send a greeting */
649 POP3C_SendListCommand,
651 POP3C_GetOneMessagID,
658 const long POP3_C_ReadTimeouts[] = {
670 /*****************************************************************************/
671 /* POP3 CLIENT DISPATCHER */
672 /*****************************************************************************/
674 void POP3SetTimeout(eNextState NextTCPState, pop3aggr *pMsg)
676 double Timeout = 0.0;
678 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
680 switch (NextTCPState) {
684 Timeout = POP3_C_SendTimeouts[pMsg->State];
686 if (pMsg->State == eDATABody) {
687 / * if we're sending a huge message, we need more time. * /
688 Timeout += StrLength(pMsg->msgtext) / 1024;
694 Timeout = POP3_C_ReadTimeouts[pMsg->State];
696 if (pMsg->State == eDATATerminateBody) {
698 * some mailservers take a nap before accepting the message
699 * content inspection and such.
701 Timeout += StrLength(pMsg->msgtext) / 1024;
712 case eTerminateConnection:
715 case eReadMore://// TODO
718 SetNextTimeout(&pMsg->IO, Timeout);
720 eNextState POP3_C_DispatchReadDone(AsyncIO *IO)
722 /* syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
723 pop3aggr *pMsg = IO->Data;
726 rc = POP3C_ReadHandlers[pMsg->State](pMsg);
729 POP3SetTimeout(rc, pMsg);
732 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO)
734 pop3aggr *pMsg = IO->Data;
737 /* syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
738 rc = POP3C_SendHandlers[pMsg->State](pMsg);
739 POP3SetTimeout(rc, pMsg);
744 /*****************************************************************************/
745 /* POP3 CLIENT ERROR CATCHERS */
746 /*****************************************************************************/
747 eNextState POP3_C_Terminate(AsyncIO *IO)
749 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
750 FinalizePOP3AggrRun(IO);
753 eNextState POP3_C_TerminateDB(AsyncIO *IO)
755 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
756 FinalizePOP3AggrRun(IO);
759 eNextState POP3_C_Timeout(AsyncIO *IO)
761 pop3aggr *pMsg = IO->Data;
763 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
764 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
765 return FailAggregationRun(IO);
767 eNextState POP3_C_ConnFail(AsyncIO *IO)
769 pop3aggr *pMsg = (pop3aggr *)IO->Data;
771 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
772 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
773 return FailAggregationRun(IO);
775 eNextState POP3_C_DNSFail(AsyncIO *IO)
777 pop3aggr *pMsg = (pop3aggr *)IO->Data;
779 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
780 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
781 return FailAggregationRun(IO);
783 eNextState POP3_C_Shutdown(AsyncIO *IO)
785 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
786 FinalizePOP3AggrRun(IO);
792 * lineread Handler; understands when to read more POP3 lines, and when this is a one-lined reply.
794 eReadState POP3_C_ReadServerStatus(AsyncIO *IO)
796 eReadState Finished = eBufferNotEmpty;
798 switch (IO->NextState) {
803 case eTerminateConnection:
805 Finished = eReadFail;
812 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
816 Finished = CtdlReadMessageBodyAsync(IO);
822 /*****************************************************************************
823 * So we connect our Server IP here. *
824 *****************************************************************************/
825 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO)
827 pop3aggr *cpptr = IO->Data;
829 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
830 ////??? cpptr->State ++;
831 if (cpptr->Pos == NULL)
832 cpptr->Pos = GetNewHashPos(cpptr->MsgNumbers, 0);
834 POP3_C_DispatchWriteDone(IO);
835 ReAttachIO(IO, cpptr, 0);
836 IO->NextState = eReadMessage;
837 return IO->NextState;
840 eNextState pop3_connect_ip(AsyncIO *IO)
842 pop3aggr *cpptr = IO->Data;
844 if (cpptr->IOStart == 0.0) /* whith or without DNS? */
845 cpptr->IOStart = IO->Now;
847 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
849 return EvConnectSock(IO,
851 POP3_C_ReadTimeouts[0],
855 eNextState pop3_get_one_host_ip_done(AsyncIO *IO)
857 pop3aggr *cpptr = IO->Data;
858 struct hostent *hostent;
862 hostent = cpptr->HostLookup.VParsedDNSReply;
863 if ((cpptr->HostLookup.DNSStatus == ARES_SUCCESS) &&
864 (hostent != NULL) ) {
865 memset(&cpptr->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
866 if (cpptr->IO.ConnectMe->IPv6) {
867 memcpy(&cpptr->IO.ConnectMe->Addr.sin6_addr.s6_addr,
868 &hostent->h_addr_list[0],
869 sizeof(struct in6_addr));
871 cpptr->IO.ConnectMe->Addr.sin6_family =
873 cpptr->IO.ConnectMe->Addr.sin6_port =
874 htons(DefaultPOP3Port);
877 struct sockaddr_in *addr =
878 (struct sockaddr_in*)
879 &cpptr->IO.ConnectMe->Addr;
881 memcpy(&addr->sin_addr.s_addr,
882 hostent->h_addr_list[0],
885 addr->sin_family = hostent->h_addrtype;
886 addr->sin_port = htons(DefaultPOP3Port);
888 return pop3_connect_ip(IO);
894 eNextState pop3_get_one_host_ip(AsyncIO *IO)
896 pop3aggr *cpptr = IO->Data;
898 cpptr->IOStart = IO->Now;
900 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
903 "POP3 client[%ld]: looking up %s-Record %s : %d ...\n",
905 (cpptr->IO.ConnectMe->IPv6)? "aaaa": "a",
906 cpptr->IO.ConnectMe->Host,
907 cpptr->IO.ConnectMe->Port);
909 QueueQuery((cpptr->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a,
910 cpptr->IO.ConnectMe->Host,
913 pop3_get_one_host_ip_done);
914 IO->NextState = eReadDNSReply;
915 return IO->NextState;
920 int pop3_do_fetching(pop3aggr *cpptr)
922 AsyncIO *IO = &cpptr->IO;
927 POP3_C_ReadServerStatus,
929 POP3_C_DispatchWriteDone,
930 POP3_C_DispatchReadDone,
937 safestrncpy(((CitContext *)cpptr->IO.CitContext)->cs_host,
939 sizeof(((CitContext *)cpptr->IO.CitContext)->cs_host));
941 if (cpptr->IO.ConnectMe->IsIP) {
942 QueueEventContext(&cpptr->IO,
946 QueueEventContext(&cpptr->IO,
947 pop3_get_one_host_ip);
953 * Scan a room's netconfig to determine whether it requires POP3 aggregation
955 void pop3client_scan_room(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCFG)
957 const RoomNetCfgLine *pLine;
960 pthread_mutex_lock(&POP3QueueMutex);
961 if (GetHash(POP3QueueRooms, LKEY(qrbuf->QRnumber), &vptr))
963 pthread_mutex_unlock(&POP3QueueMutex);
965 "pop3client: [%ld] %s already in progress.",
970 pthread_mutex_unlock(&POP3QueueMutex);
972 if (server_shutting_down) return;
974 pLine = OneRNCFG->NetConfigs[pop3client];
976 while (pLine != NULL)
980 cptr = (pop3aggr *) malloc(sizeof(pop3aggr));
981 memset(cptr, 0, sizeof(pop3aggr));
982 ///TODO do we need this? cptr->roomlist_parts=1;
983 cptr->RoomName = NewStrBufPlain(qrbuf->QRname, -1);
984 cptr->pop3user = NewStrBufDup(pLine->Value[1]);
985 cptr->pop3pass = NewStrBufDup(pLine->Value[2]);
986 cptr->Url = NewStrBuf();
987 cptr->Host = NewStrBufDup(pLine->Value[0]);
989 cptr->keep = atol(ChrPtr(pLine->Value[3]));
990 cptr->interval = atol(ChrPtr(pLine->Value[4]));
992 StrBufAppendBufPlain(cptr->Url, HKEY("pop3://"), 0);
993 StrBufUrlescUPAppend(cptr->Url, cptr->pop3user, NULL);
994 StrBufAppendBufPlain(cptr->Url, HKEY(":"), 0);
995 StrBufUrlescUPAppend(cptr->Url, cptr->pop3pass, NULL);
996 StrBufAppendBufPlain(cptr->Url, HKEY("@"), 0);
997 StrBufAppendBuf(cptr->Url, cptr->Host, 0);
998 StrBufAppendBufPlain(cptr->Url, HKEY("/"), 0);
999 StrBufUrlescAppend(cptr->Url, cptr->RoomName, NULL);
1001 ParseURL(&cptr->IO.ConnectMe, cptr->Url, 110);
1003 cptr->n = Pop3ClientID++;
1004 pthread_mutex_lock(&POP3QueueMutex);
1008 DeletePOP3Aggregator);
1010 pthread_mutex_unlock(&POP3QueueMutex);
1011 pLine = pLine->next;
1016 static int doing_pop3client = 0;
1018 void pop3client_scan(void) {
1019 static time_t last_run = 0L;
1020 time_t fastest_scan;
1027 become_session(&pop3_client_CC);
1029 if (CtdlGetConfigLong("c_pop3_fastest") < CtdlGetConfigLong("c_pop3_fetch"))
1030 fastest_scan = CtdlGetConfigLong("c_pop3_fastest");
1032 fastest_scan = CtdlGetConfigLong("c_pop3_fetch");
1035 * Run POP3 aggregation no more frequently than once every n seconds
1037 if ( (time(NULL) - last_run) < fastest_scan ) {
1042 * This is a simple concurrency check to make sure only one pop3client
1043 * run is done at a time. We could do this with a mutex, but since we
1044 * don't really require extremely fine granularity here, we'll do it
1045 * with a static variable instead.
1047 if (doing_pop3client) return;
1048 doing_pop3client = 1;
1050 syslog(LOG_DEBUG, "pop3client started");
1051 CtdlForEachNetCfgRoom(pop3client_scan_room, NULL);
1053 pthread_mutex_lock(&POP3QueueMutex);
1054 it = GetNewHashPos(POP3FetchUrls, 0);
1055 while (!server_shutting_down &&
1056 GetNextHashPos(POP3FetchUrls, it, &len, &Key, &vrptr) &&
1058 cptr = (pop3aggr *)vrptr;
1059 if (cptr->RefCount == 0) {
1060 if (!pop3_do_fetching(cptr)) {
1061 DeletePOP3Aggregator(cptr);////TODO
1066 pthread_mutex_unlock(&POP3QueueMutex);
1068 syslog(LOG_DEBUG, "pop3client ended");
1069 last_run = time(NULL);
1070 doing_pop3client = 0;
1074 void pop3_cleanup(void)
1076 /* citthread_mutex_destroy(&POP3QueueMutex); TODO */
1077 while (doing_pop3client != 0) ;
1078 DeleteHash(&POP3FetchUrls);
1079 DeleteHash(&POP3QueueRooms);
1084 CTDL_MODULE_INIT(pop3client)
1088 CtdlFillSystemContext(&pop3_client_CC, "POP3aggr");
1089 CtdlREGISTERRoomCfgType(pop3client, ParseGeneric, 0, 5, SerializeGeneric, DeleteGenericCfgLine);
1090 pthread_mutex_init(&POP3QueueMutex, NULL);
1091 POP3QueueRooms = NewHash(1, lFlathash);
1092 POP3FetchUrls = NewHash(1, NULL);
1093 CtdlRegisterSessionHook(pop3client_scan, EVT_TIMER, PRIO_AGGR + 50);
1094 CtdlRegisterEVCleanupHook(pop3_cleanup);
1097 /* return our module id for the log */
1098 return "pop3client";