2 * Consolidate mail from remote POP3 accounts.
4 * Copyright (c) 2007-2011 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.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
30 # include <sys/time.h>
39 #include <sys/types.h>
41 #include <libcitadel.h>
44 #include "citserver.h"
47 #include "ctdl_module.h"
48 #include "clientsocket.h"
50 #include "internet_addressing.h"
52 #include "citadel_dirs.h"
53 #include "event_client.h"
56 #define POP3C_OK (strncasecmp(ChrPtr(RecvMsg->IO.IOBuf), "+OK", 3) == 0)
58 int POP3ClientDebugEnabled = 0;
60 #define N ((pop3aggr*)IO->Data)->n
62 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (POP3ClientDebugEnabled != 0))
64 #define EVP3C_syslog(LEVEL, FORMAT, ...) \
65 DBGLOG(LEVEL) syslog(LEVEL, \
66 "%s[%ld]CC[%d][%ld]POP3: " FORMAT, \
67 IOSTR, IO->ID, CCID, N, __VA_ARGS__)
69 #define EVP3CM_syslog(LEVEL, FORMAT) \
70 DBGLOG(LEVEL) syslog(LEVEL, \
71 "%s[%ld]CC[%d][%ld]POP3: " FORMAT, \
72 IOSTR, IO->ID, CCID, N)
74 #define EVP3CQ_syslog(LEVEL, FORMAT, ...) \
75 DBGLOG(LEVEL) syslog(LEVEL, \
79 #define EVP3CQM_syslog(LEVEL, FORMAT) \
80 DBGLOG(LEVEL) syslog(LEVEL, \
84 #define EVP3CCS_syslog(LEVEL, FORMAT, ...) \
85 DBGLOG(LEVEL) syslog(LEVEL, "%s[%ld][%ld]POP3: " FORMAT, \
86 IOSTR, IO->ID, N, __VA_ARGS__)
88 #define EVP3CCSM_syslog(LEVEL, FORMAT) \
89 DBGLOG(LEVEL) syslog(LEVEL, "%s[%ld][%ld]POP3: " FORMAT, \
92 #define POP3C_DBG_SEND() \
93 EVP3C_syslog(LOG_DEBUG, \
94 "%s[%ld]CC[%d][%ld]POP3: > %s\n", \
95 IOSTR, IO->ID, CCID, N, \
96 ChrPtr(RecvMsg->IO.SendBuf.Buf))
98 #define POP3C_DBG_READ() \
99 EVP3C_syslog(LOG_DEBUG, \
100 "%s[%ld]CC[%d][%ld]POP3: < %s\n", \
101 IOSTR, IO->ID, CCID, N, \
102 ChrPtr(RecvMsg->IO.IOBuf))
105 struct CitContext pop3_client_CC;
107 pthread_mutex_t POP3QueueMutex; /* locks the access to the following vars: */
108 HashList *POP3QueueRooms = NULL;
109 HashList *POP3FetchUrls = NULL;
111 typedef struct pop3aggr pop3aggr;
112 typedef eNextState(*Pop3ClientHandler)(pop3aggr* RecvMsg);
114 eNextState POP3_C_Shutdown(AsyncIO *IO);
115 eNextState POP3_C_Timeout(AsyncIO *IO);
116 eNextState POP3_C_ConnFail(AsyncIO *IO);
117 eNextState POP3_C_DNSFail(AsyncIO *IO);
118 eNextState POP3_C_DispatchReadDone(AsyncIO *IO);
119 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO);
120 eNextState POP3_C_Terminate(AsyncIO *IO);
121 eReadState POP3_C_ReadServerStatus(AsyncIO *IO);
122 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO);
124 typedef struct __pop3_room_counter {
129 typedef enum ePOP3_C_States {
135 GetOneMessageIDState,
136 ReadMessageBodyFollowing,
144 typedef struct _FetchItem {
150 struct CtdlMessage *Msg;
153 void HfreeFetchItem(void *vItem)
155 FetchItem *Item = (FetchItem*) vItem;
156 FreeStrBuf(&Item->MsgUIDL);
157 FreeStrBuf(&Item->MsgUID);
163 typedef enum _POP3State {
177 ConstStr POP3States[] = {
178 {HKEY("Aggregator created")},
179 {HKEY("Reading Greeting")},
180 {HKEY("Sending User")},
181 {HKEY("Sending Password")},
183 {HKEY("Fetching Usetable")},
184 {HKEY("Get MSG ID")},
185 {HKEY("Get Message")},
187 {HKEY("Delete Upstream")},
191 static void SetPOP3State(AsyncIO *IO, POP3State State)
193 CitContext* CCC = IO->CitContext;
195 memcpy(CCC->cs_clientname, POP3States[State].Key, POP3States[State].len + 1);
206 DNSQueryParts HostLookup;
209 HashList *OtherQRnumbers;
215 StrBuf *RoomName; // TODO: fill me
218 ePOP3_C_States State;
219 HashList *MsgNumbers;
224 void DeletePOP3Aggregator(void *vptr)
226 pop3aggr *ptr = vptr;
227 DeleteHashPos(&ptr->Pos);
228 DeleteHash(&ptr->MsgNumbers);
229 // FreeStrBuf(&ptr->rooms);
230 FreeStrBuf(&ptr->pop3user);
231 FreeStrBuf(&ptr->pop3pass);
232 FreeStrBuf(&ptr->Host);
233 FreeStrBuf(&ptr->RoomName);
234 FreeURL(&ptr->IO.ConnectMe);
235 FreeStrBuf(&ptr->Url);
236 FreeStrBuf(&ptr->IO.IOBuf);
237 FreeStrBuf(&ptr->IO.SendBuf.Buf);
238 FreeStrBuf(&ptr->IO.RecvBuf.Buf);
239 DeleteAsyncMsg(&ptr->IO.ReadMsg);
240 if (((struct CitContext*)ptr->IO.CitContext)) {
241 ((struct CitContext*)ptr->IO.CitContext)->state = CON_IDLE;
242 ((struct CitContext*)ptr->IO.CitContext)->kill_me = 1;
244 FreeAsyncIOContents(&ptr->IO);
248 eNextState FinalizePOP3AggrRun(AsyncIO *IO)
251 pop3aggr *cpptr = (pop3aggr *)IO->Data;
253 EVP3C_syslog(LOG_INFO,
254 "%s@%s: fetched %ld new of %d messages in %fs. bye.",
255 ChrPtr(cpptr->pop3user),
258 GetCount(cpptr->MsgNumbers),
259 IO->Now - cpptr->IOStart
262 It = GetNewHashPos(POP3FetchUrls, 0);
263 pthread_mutex_lock(&POP3QueueMutex);
265 if (GetHashPosFromKey(POP3FetchUrls, SKEY(cpptr->Url), It))
266 DeleteEntryFromHash(POP3FetchUrls, It);
268 pthread_mutex_unlock(&POP3QueueMutex);
273 eNextState FailAggregationRun(AsyncIO *IO)
278 eNextState POP3C_ReadGreeting(pop3aggr *RecvMsg)
280 AsyncIO *IO = &RecvMsg->IO;
281 SetPOP3State(IO, eGreeting);
283 /* Read the server greeting */
284 if (!POP3C_OK) return eTerminateConnection;
285 else return eSendReply;
288 eNextState POP3C_SendUser(pop3aggr *RecvMsg)
290 AsyncIO *IO = &RecvMsg->IO;
291 SetPOP3State(IO, eUser);
292 /* Identify ourselves. NOTE: we have to append a CR to each command.
293 * The LF will automatically be appended by sock_puts(). Believe it
294 * or not, leaving out the CR will cause problems if the server happens
295 * to be Exchange, which is so b0rken it actually barfs on
296 * LF-terminated newlines.
298 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
299 "USER %s\r\n", ChrPtr(RecvMsg->pop3user));
304 eNextState POP3C_GetUserState(pop3aggr *RecvMsg)
306 AsyncIO *IO = &RecvMsg->IO;
308 if (!POP3C_OK) return eTerminateConnection;
309 else return eSendReply;
312 eNextState POP3C_SendPassword(pop3aggr *RecvMsg)
314 AsyncIO *IO = &RecvMsg->IO;
315 SetPOP3State(IO, ePassword);
317 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
318 "PASS %s\r\n", ChrPtr(RecvMsg->pop3pass));
319 EVP3CM_syslog(LOG_DEBUG, "<PASS <password>\n");
320 // POP3C_DBG_SEND(); No, we won't write the passvoid to syslog...
324 eNextState POP3C_GetPassState(pop3aggr *RecvMsg)
326 AsyncIO *IO = &RecvMsg->IO;
328 if (!POP3C_OK) return eTerminateConnection;
329 else return eSendReply;
332 eNextState POP3C_SendListCommand(pop3aggr *RecvMsg)
334 AsyncIO *IO = &RecvMsg->IO;
335 SetPOP3State(IO, eListing);
337 /* Get the list of messages */
338 StrBufPlain(RecvMsg->IO.SendBuf.Buf, HKEY("LIST\r\n"));
343 eNextState POP3C_GetListCommandState(pop3aggr *RecvMsg)
345 AsyncIO *IO = &RecvMsg->IO;
347 if (!POP3C_OK) return eTerminateConnection;
348 RecvMsg->MsgNumbers = NewHash(1, NULL);
354 eNextState POP3C_GetListOneLine(pop3aggr *RecvMsg)
356 AsyncIO *IO = &RecvMsg->IO;
361 FetchItem *OneMsg = NULL;
364 if ((StrLength(RecvMsg->IO.IOBuf) == 1) &&
365 (ChrPtr(RecvMsg->IO.IOBuf)[0] == '.'))
367 if (GetCount(RecvMsg->MsgNumbers) == 0)
369 //// RecvMsg->Sate = ReadQuitState;
373 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
380 * work around buggy pop3 servers which send
381 * empty lines in their listings.
383 if ((StrLength(RecvMsg->IO.IOBuf) == 0) ||
384 !isdigit(ChrPtr(RecvMsg->IO.IOBuf)[0]))
389 OneMsg = (FetchItem*) malloc(sizeof(FetchItem));
390 memset(OneMsg, 0, sizeof(FetchItem));
391 OneMsg->MSGID = atol(ChrPtr(RecvMsg->IO.IOBuf));
393 pch = strchr(ChrPtr(RecvMsg->IO.IOBuf), ' ');
396 OneMsg->MSGSize = atol(pch + 1);
399 rc = TestValidateHash(RecvMsg->MsgNumbers);
401 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
404 Put(RecvMsg->MsgNumbers, LKEY(OneMsg->MSGID), OneMsg, HfreeFetchItem);
406 rc = TestValidateHash(RecvMsg->MsgNumbers);
408 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
410 //RecvMsg->State --; /* read next Line */
414 eNextState POP3_FetchNetworkUsetableEntry(AsyncIO *IO)
419 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
421 SetPOP3State(IO, eUseTable);
423 if((RecvMsg->Pos != NULL) &&
424 GetNextHashPos(RecvMsg->MsgNumbers,
430 if (server_shutting_down)
433 if (CheckIfAlreadySeen("POP3 Item Seen",
434 RecvMsg->CurrMsg->MsgUID,
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 RecvMsg->CurrMsg = NULL;
542 while ((RecvMsg->Pos != NULL) &&
543 GetNextHashPos(RecvMsg->MsgNumbers,
547 (RecvMsg->CurrMsg = (FetchItem*) vData,
548 RecvMsg->CurrMsg->NeedFetch == 0))
551 if ((RecvMsg->CurrMsg != NULL ) && (RecvMsg->CurrMsg->NeedFetch == 1))
553 /* Message has not been seen.
554 * Tell the server to fetch the message... */
555 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
556 "RETR %ld\r\n", RecvMsg->CurrMsg->MSGID);
561 RecvMsg->State = ReadQuitState;
562 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
567 eNextState POP3C_ReadMessageBodyFollowing(pop3aggr *RecvMsg)
569 AsyncIO *IO = &RecvMsg->IO;
571 if (!POP3C_OK) return eTerminateConnection;
572 RecvMsg->IO.ReadMsg = NewAsyncMsg(HKEY("."),
573 RecvMsg->CurrMsg->MSGSize,
582 eNextState POP3C_StoreMsgRead(AsyncIO *IO)
584 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
586 SetPOP3State(IO, eStoreMsg);
588 EVP3CCS_syslog(LOG_DEBUG,
589 "MARKING: %s as seen: ",
590 ChrPtr(RecvMsg->CurrMsg->MsgUID));
591 CheckIfAlreadySeen("POP3 Item Seen",
592 RecvMsg->CurrMsg->MsgUID,
598 return DBQueueEventContext(&RecvMsg->IO, POP3_C_ReAttachToFetchMessages);
600 eNextState POP3C_SaveMsg(AsyncIO *IO)
603 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
605 /* Do Something With It (tm) */
606 msgnum = CtdlSubmitMsg(RecvMsg->CurrMsg->Msg,
608 ChrPtr(RecvMsg->RoomName),
612 /* Message has been committed to the store
613 * write the uidl to the use table
614 * so we don't fetch this message again
617 CM_Free(RecvMsg->CurrMsg->Msg);
620 return NextDBOperation(&RecvMsg->IO, POP3C_StoreMsgRead);
623 eNextState POP3C_ReadMessageBody(pop3aggr *RecvMsg)
625 AsyncIO *IO = &RecvMsg->IO;
626 EVP3CM_syslog(LOG_DEBUG, "Converting message...");
627 RecvMsg->CurrMsg->Msg =
628 convert_internet_message_buf(&RecvMsg->IO.ReadMsg->MsgBuf);
629 return EventQueueDBOperation(&RecvMsg->IO, POP3C_SaveMsg, 0);
632 eNextState POP3C_SendDelete(pop3aggr *RecvMsg)
634 AsyncIO *IO = &RecvMsg->IO;
636 SetPOP3State(IO, eDelete);
638 if (!RecvMsg->keep) {
639 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
640 "DELE %ld\r\n", RecvMsg->CurrMsg->MSGID);
645 RecvMsg->State = ReadMessageBodyFollowing;
646 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
649 eNextState POP3C_ReadDeleteState(pop3aggr *RecvMsg)
651 AsyncIO *IO = &RecvMsg->IO;
653 RecvMsg->State = GetOneMessageIDState;
657 eNextState POP3C_SendQuit(pop3aggr *RecvMsg)
659 AsyncIO *IO = &RecvMsg->IO;
660 SetPOP3State(IO, eQuit);
663 StrBufPlain(RecvMsg->IO.SendBuf.Buf,
670 eNextState POP3C_ReadQuitState(pop3aggr *RecvMsg)
672 AsyncIO *IO = &RecvMsg->IO;
674 return eTerminateConnection;
677 const long POP3_C_ConnTimeout = 1000;
678 const long DefaultPOP3Port = 110;
680 Pop3ClientHandler POP3C_ReadHandlers[] = {
684 POP3C_GetListCommandState,
685 POP3C_GetListOneLine,
686 POP3C_GetOneMessageIDState,
687 POP3C_ReadMessageBodyFollowing,
688 POP3C_ReadMessageBody,
689 POP3C_ReadDeleteState,
693 const long POP3_C_SendTimeouts[POP3C_MaxRead] = {
703 const ConstStr POP3C_ReadErrors[POP3C_MaxRead] = {
704 {HKEY("Connection broken during ")},
705 {HKEY("Connection broken during ")},
706 {HKEY("Connection broken during ")},
707 {HKEY("Connection broken during ")},
708 {HKEY("Connection broken during ")},
709 {HKEY("Connection broken during ")},
710 {HKEY("Connection broken during ")},
711 {HKEY("Connection broken during ")}
714 Pop3ClientHandler POP3C_SendHandlers[] = {
715 NULL, /* we don't send a greeting */
718 POP3C_SendListCommand,
720 POP3C_GetOneMessagID,
727 const long POP3_C_ReadTimeouts[] = {
739 /*****************************************************************************/
740 /* POP3 CLIENT DISPATCHER */
741 /*****************************************************************************/
743 void POP3SetTimeout(eNextState NextTCPState, pop3aggr *pMsg)
745 AsyncIO *IO = &pMsg->IO;
746 double Timeout = 0.0;
748 EVP3C_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
750 switch (NextTCPState) {
754 Timeout = POP3_C_SendTimeouts[pMsg->State];
756 if (pMsg->State == eDATABody) {
757 / * if we're sending a huge message, we need more time. * /
758 Timeout += StrLength(pMsg->msgtext) / 1024;
764 Timeout = POP3_C_ReadTimeouts[pMsg->State];
766 if (pMsg->State == eDATATerminateBody) {
768 * some mailservers take a nap before accepting the message
769 * content inspection and such.
771 Timeout += StrLength(pMsg->msgtext) / 1024;
782 case eTerminateConnection:
785 case eReadMore://// TODO
788 SetNextTimeout(&pMsg->IO, Timeout);
790 eNextState POP3_C_DispatchReadDone(AsyncIO *IO)
792 /* EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
793 pop3aggr *pMsg = IO->Data;
796 rc = POP3C_ReadHandlers[pMsg->State](pMsg);
799 POP3SetTimeout(rc, pMsg);
802 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO)
804 pop3aggr *pMsg = IO->Data;
807 /* EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
808 rc = POP3C_SendHandlers[pMsg->State](pMsg);
809 POP3SetTimeout(rc, pMsg);
814 /*****************************************************************************/
815 /* POP3 CLIENT ERROR CATCHERS */
816 /*****************************************************************************/
817 eNextState POP3_C_Terminate(AsyncIO *IO)
819 /// pop3aggr *pMsg = (pop3aggr *)IO->Data;
821 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
822 FinalizePOP3AggrRun(IO);
825 eNextState POP3_C_TerminateDB(AsyncIO *IO)
827 /// pop3aggr *pMsg = (pop3aggr *)IO->Data;
829 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
830 FinalizePOP3AggrRun(IO);
833 eNextState POP3_C_Timeout(AsyncIO *IO)
835 pop3aggr *pMsg = IO->Data;
837 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
838 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
839 return FailAggregationRun(IO);
841 eNextState POP3_C_ConnFail(AsyncIO *IO)
843 pop3aggr *pMsg = (pop3aggr *)IO->Data;
845 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
846 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
847 return FailAggregationRun(IO);
849 eNextState POP3_C_DNSFail(AsyncIO *IO)
851 pop3aggr *pMsg = (pop3aggr *)IO->Data;
853 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
854 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
855 return FailAggregationRun(IO);
857 eNextState POP3_C_Shutdown(AsyncIO *IO)
859 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
860 //// pop3aggr *pMsg = IO->Data;
862 ////pMsg->MyQEntry->Status = 3;
863 ///StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message retrieval."));
864 FinalizePOP3AggrRun(IO);
870 * @brief lineread Handler; understands when to read more POP3 lines,
871 * and when this is a one-lined reply.
873 eReadState POP3_C_ReadServerStatus(AsyncIO *IO)
875 eReadState Finished = eBufferNotEmpty;
877 switch (IO->NextState) {
882 case eTerminateConnection:
884 Finished = eReadFail;
891 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
895 Finished = CtdlReadMessageBodyAsync(IO);
901 /*****************************************************************************
902 * So we connect our Server IP here. *
903 *****************************************************************************/
904 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO)
906 pop3aggr *cpptr = IO->Data;
908 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
909 ////??? cpptr->State ++;
910 if (cpptr->Pos == NULL)
911 cpptr->Pos = GetNewHashPos(cpptr->MsgNumbers, 0);
913 POP3_C_DispatchWriteDone(IO);
914 ReAttachIO(IO, cpptr, 0);
915 IO->NextState = eReadMessage;
916 return IO->NextState;
919 eNextState pop3_connect_ip(AsyncIO *IO)
921 pop3aggr *cpptr = IO->Data;
923 if (cpptr->IOStart == 0.0) /* whith or without DNS? */
924 cpptr->IOStart = IO->Now;
926 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
928 return EvConnectSock(IO,
930 POP3_C_ReadTimeouts[0],
934 eNextState pop3_get_one_host_ip_done(AsyncIO *IO)
936 pop3aggr *cpptr = IO->Data;
937 struct hostent *hostent;
941 hostent = cpptr->HostLookup.VParsedDNSReply;
942 if ((cpptr->HostLookup.DNSStatus == ARES_SUCCESS) &&
943 (hostent != NULL) ) {
944 memset(&cpptr->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
945 if (cpptr->IO.ConnectMe->IPv6) {
946 memcpy(&cpptr->IO.ConnectMe->Addr.sin6_addr.s6_addr,
947 &hostent->h_addr_list[0],
948 sizeof(struct in6_addr));
950 cpptr->IO.ConnectMe->Addr.sin6_family =
952 cpptr->IO.ConnectMe->Addr.sin6_port =
953 htons(DefaultPOP3Port);
956 struct sockaddr_in *addr =
957 (struct sockaddr_in*)
958 &cpptr->IO.ConnectMe->Addr;
960 memcpy(&addr->sin_addr.s_addr,
961 hostent->h_addr_list[0],
964 addr->sin_family = hostent->h_addrtype;
965 addr->sin_port = htons(DefaultPOP3Port);
967 return pop3_connect_ip(IO);
973 eNextState pop3_get_one_host_ip(AsyncIO *IO)
975 pop3aggr *cpptr = IO->Data;
977 cpptr->IOStart = IO->Now;
979 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
981 EVP3CCS_syslog(LOG_DEBUG,
982 "POP3 client[%ld]: looking up %s-Record %s : %d ...\n",
984 (cpptr->IO.ConnectMe->IPv6)? "aaaa": "a",
985 cpptr->IO.ConnectMe->Host,
986 cpptr->IO.ConnectMe->Port);
988 QueueQuery((cpptr->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a,
989 cpptr->IO.ConnectMe->Host,
992 pop3_get_one_host_ip_done);
993 IO->NextState = eReadDNSReply;
994 return IO->NextState;
999 int pop3_do_fetching(pop3aggr *cpptr)
1001 AsyncIO *IO = &cpptr->IO;
1006 POP3_C_ReadServerStatus,
1008 POP3_C_DispatchWriteDone,
1009 POP3_C_DispatchReadDone,
1016 safestrncpy(((CitContext *)cpptr->IO.CitContext)->cs_host,
1018 sizeof(((CitContext *)cpptr->IO.CitContext)->cs_host));
1020 if (cpptr->IO.ConnectMe->IsIP) {
1021 QueueEventContext(&cpptr->IO,
1025 QueueEventContext(&cpptr->IO,
1026 pop3_get_one_host_ip);
1032 * Scan a room's netconfig to determine whether it requires POP3 aggregation
1034 void pop3client_scan_room(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCFG)
1036 const RoomNetCfgLine *pLine;
1039 pthread_mutex_lock(&POP3QueueMutex);
1040 if (GetHash(POP3QueueRooms, LKEY(qrbuf->QRnumber), &vptr))
1042 pthread_mutex_unlock(&POP3QueueMutex);
1043 EVP3CQ_syslog(LOG_DEBUG,
1044 "pop3client: [%ld] %s already in progress.",
1049 pthread_mutex_unlock(&POP3QueueMutex);
1051 if (server_shutting_down) return;
1053 pLine = OneRNCFG->NetConfigs[pop3client];
1055 while (pLine != NULL)
1059 cptr = (pop3aggr *) malloc(sizeof(pop3aggr));
1060 memset(cptr, 0, sizeof(pop3aggr));
1061 ///TODO do we need this? cptr->roomlist_parts=1;
1062 cptr->RoomName = NewStrBufPlain(qrbuf->QRname, -1);
1063 cptr->pop3user = NewStrBufDup(pLine->Value[1]);
1064 cptr->pop3pass = NewStrBufDup(pLine->Value[2]);
1065 cptr->Url = NewStrBuf();
1066 cptr->Host = NewStrBufDup(pLine->Value[0]);
1068 cptr->keep = atol(ChrPtr(pLine->Value[3]));
1069 cptr->interval = atol(ChrPtr(pLine->Value[4]));
1071 StrBufAppendBufPlain(cptr->Url, HKEY("pop3://"), 0);
1072 StrBufUrlescUPAppend(cptr->Url, cptr->pop3user, NULL);
1073 StrBufAppendBufPlain(cptr->Url, HKEY(":"), 0);
1074 StrBufUrlescUPAppend(cptr->Url, cptr->pop3pass, NULL);
1075 StrBufAppendBufPlain(cptr->Url, HKEY("@"), 0);
1076 StrBufAppendBuf(cptr->Url, cptr->Host, 0);
1077 StrBufAppendBufPlain(cptr->Url, HKEY("/"), 0);
1078 StrBufUrlescAppend(cptr->Url, cptr->RoomName, NULL);
1080 ParseURL(&cptr->IO.ConnectMe, cptr->Url, 110);
1084 /* todo: we need to reunite the url to be shure. */
1086 pthread_mutex_lock(&POP3ueueMutex);
1087 GetHash(POP3FetchUrls, SKEY(ptr->Url), &vptr);
1088 use_this_cptr = (pop3aggr *)vptr;
1090 if (use_this_rncptr != NULL)
1092 /* mustn't attach to an active session */
1093 if (use_this_cptr->RefCount > 0)
1095 DeletePOP3Cfg(cptr);
1101 StrBufAppendBufPlain(
1102 use_this_cptr->rooms,
1105 if (use_this_cptr->roomlist_parts == 1)
1107 use_this_cptr->OtherQRnumbers
1108 = NewHash(1, lFlathash);
1110 QRnumber = (long*)malloc(sizeof(long));
1111 *QRnumber = qrbuf->QRnumber;
1112 Put(use_this_cptr->OtherQRnumbers,
1113 LKEY(qrbuf->QRnumber),
1117 use_this_cptr->roomlist_parts++;
1119 pthread_mutex_unlock(&POP3QueueMutex);
1122 pthread_mutex_unlock(&RSSQueueMutex);
1124 cptr->n = Pop3ClientID++;
1125 pthread_mutex_lock(&POP3QueueMutex);
1129 DeletePOP3Aggregator);
1131 pthread_mutex_unlock(&POP3QueueMutex);
1132 pLine = pLine->next;
1137 static int doing_pop3client = 0;
1139 void pop3client_scan(void) {
1140 static time_t last_run = 0L;
1141 time_t fastest_scan;
1148 become_session(&pop3_client_CC);
1150 if (config.c_pop3_fastest < config.c_pop3_fetch)
1151 fastest_scan = config.c_pop3_fastest;
1153 fastest_scan = config.c_pop3_fetch;
1156 * Run POP3 aggregation no more frequently than once every n seconds
1158 if ( (time(NULL) - last_run) < fastest_scan ) {
1163 * This is a simple concurrency check to make sure only one pop3client
1164 * run is done at a time. We could do this with a mutex, but since we
1165 * don't really require extremely fine granularity here, we'll do it
1166 * with a static variable instead.
1168 if (doing_pop3client) return;
1169 doing_pop3client = 1;
1171 EVP3CQM_syslog(LOG_DEBUG, "pop3client started");
1172 CtdlForEachNetCfgRoom(pop3client_scan_room, NULL, pop3client);
1174 pthread_mutex_lock(&POP3QueueMutex);
1175 it = GetNewHashPos(POP3FetchUrls, 0);
1176 while (!server_shutting_down &&
1177 GetNextHashPos(POP3FetchUrls, it, &len, &Key, &vrptr) &&
1179 cptr = (pop3aggr *)vrptr;
1180 if (cptr->RefCount == 0)
1181 if (!pop3_do_fetching(cptr))
1182 DeletePOP3Aggregator(cptr);////TODO
1185 if ((palist->interval && time(NULL) > (last_run + palist->interval))
1186 || (time(NULL) > last_run + config.c_pop3_fetch))
1187 pop3_do_fetching(palist->roomname, palist->pop3host,
1188 palist->pop3user, palist->pop3pass, palist->keep);
1190 palist = palist->next;
1195 pthread_mutex_unlock(&POP3QueueMutex);
1197 EVP3CQM_syslog(LOG_DEBUG, "pop3client ended");
1198 last_run = time(NULL);
1199 doing_pop3client = 0;
1203 void pop3_cleanup(void)
1205 /* citthread_mutex_destroy(&POP3QueueMutex); TODO */
1206 while (doing_pop3client != 0) ;
1207 DeleteHash(&POP3FetchUrls);
1208 DeleteHash(&POP3QueueRooms);
1213 void LogDebugEnablePOP3Client(const int n)
1215 POP3ClientDebugEnabled = n;
1218 CTDL_MODULE_INIT(pop3client)
1222 CtdlFillSystemContext(&pop3_client_CC, "POP3aggr");
1223 CtdlREGISTERRoomCfgType(pop3client, ParseGeneric, 0, 5, SerializeGeneric, DeleteGenericCfgLine);
1224 pthread_mutex_init(&POP3QueueMutex, NULL);
1225 POP3QueueRooms = NewHash(1, lFlathash);
1226 POP3FetchUrls = NewHash(1, NULL);
1227 CtdlRegisterSessionHook(pop3client_scan, EVT_TIMER, PRIO_AGGR + 50);
1228 CtdlRegisterEVCleanupHook(pop3_cleanup);
1229 CtdlRegisterDebugFlagHook(HKEY("pop3client"), LogDebugEnablePOP3Client, &POP3ClientDebugEnabled);
1232 /* return our module id for the log */
1233 return "pop3client";