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
24 #include <sysconfig.h>
26 #if TIME_WITH_SYS_TIME
27 # include <sys/time.h>
31 # include <sys/time.h>
40 #include <sys/types.h>
42 #include <libcitadel.h>
45 #include "citserver.h"
48 #include "ctdl_module.h"
49 #include "clientsocket.h"
51 #include "internet_addressing.h"
53 #include "citadel_dirs.h"
54 #include "event_client.h"
57 #define POP3C_OK (strncasecmp(ChrPtr(RecvMsg->IO.IOBuf), "+OK", 3) == 0)
59 int POP3ClientDebugEnabled = 0;
61 #define N ((pop3aggr*)IO->Data)->n
63 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (POP3ClientDebugEnabled != 0))
65 #define EVP3C_syslog(LEVEL, FORMAT, ...) \
66 DBGLOG(LEVEL) syslog(LEVEL, \
67 "%s[%ld]CC[%d][%ld]POP3: " FORMAT, \
68 IOSTR, IO->ID, CCID, N, __VA_ARGS__)
70 #define EVP3CM_syslog(LEVEL, FORMAT) \
71 DBGLOG(LEVEL) syslog(LEVEL, \
72 "%s[%ld]CC[%d][%ld]POP3: " FORMAT, \
73 IOSTR, IO->ID, CCID, N)
75 #define EVP3CQ_syslog(LEVEL, FORMAT, ...) \
76 DBGLOG(LEVEL) syslog(LEVEL, \
80 #define EVP3CQM_syslog(LEVEL, FORMAT) \
81 DBGLOG(LEVEL) syslog(LEVEL, \
85 #define EVP3CCS_syslog(LEVEL, FORMAT, ...) \
86 DBGLOG(LEVEL) syslog(LEVEL, "%s[%ld][%ld]POP3: " FORMAT, \
87 IOSTR, IO->ID, N, __VA_ARGS__)
89 #define EVP3CCSM_syslog(LEVEL, FORMAT) \
90 DBGLOG(LEVEL) syslog(LEVEL, "%s[%ld][%ld]POP3: " FORMAT, \
93 #define POP3C_DBG_SEND() \
94 EVP3C_syslog(LOG_DEBUG, \
95 "%s[%ld]CC[%d][%ld]POP3: > %s\n", \
96 IOSTR, IO->ID, CCID, N, \
97 ChrPtr(RecvMsg->IO.SendBuf.Buf))
99 #define POP3C_DBG_READ() \
100 EVP3C_syslog(LOG_DEBUG, \
101 "%s[%ld]CC[%d][%ld]POP3: < %s\n", \
102 IOSTR, IO->ID, CCID, N, \
103 ChrPtr(RecvMsg->IO.IOBuf))
106 struct CitContext pop3_client_CC;
108 pthread_mutex_t POP3QueueMutex; /* locks the access to the following vars: */
109 HashList *POP3QueueRooms = NULL;
110 HashList *POP3FetchUrls = NULL;
112 typedef struct pop3aggr pop3aggr;
113 typedef eNextState(*Pop3ClientHandler)(pop3aggr* RecvMsg);
115 eNextState POP3_C_Shutdown(AsyncIO *IO);
116 eNextState POP3_C_Timeout(AsyncIO *IO);
117 eNextState POP3_C_ConnFail(AsyncIO *IO);
118 eNextState POP3_C_DNSFail(AsyncIO *IO);
119 eNextState POP3_C_DispatchReadDone(AsyncIO *IO);
120 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO);
121 eNextState POP3_C_Terminate(AsyncIO *IO);
122 eReadState POP3_C_ReadServerStatus(AsyncIO *IO);
123 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO);
125 typedef struct __pop3_room_counter {
130 typedef enum ePOP3_C_States {
136 GetOneMessageIDState,
137 ReadMessageBodyFollowing,
145 typedef struct _FetchItem {
151 struct CtdlMessage *Msg;
154 void HfreeFetchItem(void *vItem)
156 FetchItem *Item = (FetchItem*) vItem;
157 FreeStrBuf(&Item->MsgUIDL);
158 FreeStrBuf(&Item->MsgUID);
164 typedef enum _POP3State {
178 ConstStr POP3States[] = {
179 {HKEY("Aggregator created")},
180 {HKEY("Reading Greeting")},
181 {HKEY("Sending User")},
182 {HKEY("Sending Password")},
184 {HKEY("Fetching Usetable")},
185 {HKEY("Get MSG ID")},
186 {HKEY("Get Message")},
188 {HKEY("Delete Upstream")},
192 static void SetPOP3State(AsyncIO *IO, POP3State State)
194 CitContext* CCC = IO->CitContext;
196 memcpy(CCC->cs_clientname, POP3States[State].Key, POP3States[State].len + 1);
207 DNSQueryParts HostLookup;
210 HashList *OtherQRnumbers;
216 StrBuf *RoomName; // TODO: fill me
219 ePOP3_C_States State;
220 HashList *MsgNumbers;
225 void DeletePOP3Aggregator(void *vptr)
227 pop3aggr *ptr = vptr;
228 DeleteHashPos(&ptr->Pos);
229 DeleteHash(&ptr->MsgNumbers);
230 // FreeStrBuf(&ptr->rooms);
231 FreeStrBuf(&ptr->pop3user);
232 FreeStrBuf(&ptr->pop3pass);
233 FreeStrBuf(&ptr->Host);
234 FreeStrBuf(&ptr->RoomName);
235 FreeURL(&ptr->IO.ConnectMe);
236 FreeStrBuf(&ptr->Url);
237 FreeStrBuf(&ptr->IO.IOBuf);
238 FreeStrBuf(&ptr->IO.SendBuf.Buf);
239 FreeStrBuf(&ptr->IO.RecvBuf.Buf);
240 DeleteAsyncMsg(&ptr->IO.ReadMsg);
241 if (((struct CitContext*)ptr->IO.CitContext)) {
242 ((struct CitContext*)ptr->IO.CitContext)->state = CON_IDLE;
243 ((struct CitContext*)ptr->IO.CitContext)->kill_me = 1;
245 FreeAsyncIOContents(&ptr->IO);
249 eNextState FinalizePOP3AggrRun(AsyncIO *IO)
252 pop3aggr *cpptr = (pop3aggr *)IO->Data;
254 EVP3C_syslog(LOG_INFO,
255 "%s@%s: fetched %ld new of %d messages in %fs. bye.",
256 ChrPtr(cpptr->pop3user),
259 GetCount(cpptr->MsgNumbers),
260 IO->Now - cpptr->IOStart
263 It = GetNewHashPos(POP3FetchUrls, 0);
264 pthread_mutex_lock(&POP3QueueMutex);
266 if (GetHashPosFromKey(POP3FetchUrls, SKEY(cpptr->Url), It))
267 DeleteEntryFromHash(POP3FetchUrls, It);
269 pthread_mutex_unlock(&POP3QueueMutex);
274 eNextState FailAggregationRun(AsyncIO *IO)
279 eNextState POP3C_ReadGreeting(pop3aggr *RecvMsg)
281 AsyncIO *IO = &RecvMsg->IO;
282 SetPOP3State(IO, eGreeting);
284 /* Read the server greeting */
285 if (!POP3C_OK) return eTerminateConnection;
286 else return eSendReply;
289 eNextState POP3C_SendUser(pop3aggr *RecvMsg)
291 AsyncIO *IO = &RecvMsg->IO;
292 SetPOP3State(IO, eUser);
293 /* Identify ourselves. NOTE: we have to append a CR to each command.
294 * The LF will automatically be appended by sock_puts(). Believe it
295 * or not, leaving out the CR will cause problems if the server happens
296 * to be Exchange, which is so b0rken it actually barfs on
297 * LF-terminated newlines.
299 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
300 "USER %s\r\n", ChrPtr(RecvMsg->pop3user));
305 eNextState POP3C_GetUserState(pop3aggr *RecvMsg)
307 AsyncIO *IO = &RecvMsg->IO;
309 if (!POP3C_OK) return eTerminateConnection;
310 else return eSendReply;
313 eNextState POP3C_SendPassword(pop3aggr *RecvMsg)
315 AsyncIO *IO = &RecvMsg->IO;
316 SetPOP3State(IO, ePassword);
318 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
319 "PASS %s\r\n", ChrPtr(RecvMsg->pop3pass));
320 EVP3CM_syslog(LOG_DEBUG, "<PASS <password>\n");
321 // POP3C_DBG_SEND(); No, we won't write the passvoid to syslog...
325 eNextState POP3C_GetPassState(pop3aggr *RecvMsg)
327 AsyncIO *IO = &RecvMsg->IO;
329 if (!POP3C_OK) return eTerminateConnection;
330 else return eSendReply;
333 eNextState POP3C_SendListCommand(pop3aggr *RecvMsg)
335 AsyncIO *IO = &RecvMsg->IO;
336 SetPOP3State(IO, eListing);
338 /* Get the list of messages */
339 StrBufPlain(RecvMsg->IO.SendBuf.Buf, HKEY("LIST\r\n"));
344 eNextState POP3C_GetListCommandState(pop3aggr *RecvMsg)
346 AsyncIO *IO = &RecvMsg->IO;
348 if (!POP3C_OK) return eTerminateConnection;
349 RecvMsg->MsgNumbers = NewHash(1, NULL);
355 eNextState POP3C_GetListOneLine(pop3aggr *RecvMsg)
357 AsyncIO *IO = &RecvMsg->IO;
362 FetchItem *OneMsg = NULL;
365 if ((StrLength(RecvMsg->IO.IOBuf) == 1) &&
366 (ChrPtr(RecvMsg->IO.IOBuf)[0] == '.'))
368 if (GetCount(RecvMsg->MsgNumbers) == 0)
370 //// RecvMsg->Sate = ReadQuitState;
374 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
381 * work around buggy pop3 servers which send
382 * empty lines in their listings.
384 if ((StrLength(RecvMsg->IO.IOBuf) == 0) ||
385 !isdigit(ChrPtr(RecvMsg->IO.IOBuf)[0]))
390 OneMsg = (FetchItem*) malloc(sizeof(FetchItem));
391 memset(OneMsg, 0, sizeof(FetchItem));
392 OneMsg->MSGID = atol(ChrPtr(RecvMsg->IO.IOBuf));
394 pch = strchr(ChrPtr(RecvMsg->IO.IOBuf), ' ');
397 OneMsg->MSGSize = atol(pch + 1);
400 rc = TestValidateHash(RecvMsg->MsgNumbers);
402 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
405 Put(RecvMsg->MsgNumbers, LKEY(OneMsg->MSGID), OneMsg, HfreeFetchItem);
407 rc = TestValidateHash(RecvMsg->MsgNumbers);
409 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
411 //RecvMsg->State --; /* read next Line */
415 eNextState POP3_FetchNetworkUsetableEntry(AsyncIO *IO)
420 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
422 SetPOP3State(IO, eUseTable);
424 if((RecvMsg->Pos != NULL) &&
425 GetNextHashPos(RecvMsg->MsgNumbers,
431 if (server_shutting_down)
434 if (CheckIfAlreadySeen("POP3 Item Seen",
435 RecvMsg->CurrMsg->MsgUID,
437 EvGetNow(IO) - USETABLE_ANTIEXPIRE,
442 /* Item has already been seen */
443 RecvMsg->CurrMsg->NeedFetch = 0;
447 EVP3CCSM_syslog(LOG_DEBUG, "NO\n");
448 RecvMsg->CurrMsg->NeedFetch = 1;
450 return NextDBOperation(&RecvMsg->IO,
451 POP3_FetchNetworkUsetableEntry);
455 /* ok, now we know them all,
456 * continue with reading the actual messages. */
457 DeleteHashPos(&RecvMsg->Pos);
458 return DBQueueEventContext(IO, POP3_C_ReAttachToFetchMessages);
462 eNextState POP3C_GetOneMessagID(pop3aggr *RecvMsg)
464 AsyncIO *IO = &RecvMsg->IO;
469 SetPOP3State(IO, eGetMsgID);
472 rc = TestValidateHash(RecvMsg->MsgNumbers);
474 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
476 if((RecvMsg->Pos != NULL) &&
477 GetNextHashPos(RecvMsg->MsgNumbers,
482 RecvMsg->CurrMsg = (FetchItem*) vData;
483 /* Find out the UIDL of the message,
484 * to determine whether we've already downloaded it */
485 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
486 "UIDL %ld\r\n", RecvMsg->CurrMsg->MSGID);
492 DeleteHashPos(&RecvMsg->Pos);
493 /// done receiving uidls.. start looking them up now.
494 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
495 return EventQueueDBOperation(&RecvMsg->IO,
496 POP3_FetchNetworkUsetableEntry,
499 return eReadMore; /* TODO */
502 eNextState POP3C_GetOneMessageIDState(pop3aggr *RecvMsg)
504 AsyncIO *IO = &RecvMsg->IO;
507 rc = TestValidateHash(RecvMsg->MsgNumbers);
509 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
513 if (!POP3C_OK) return eTerminateConnection;
514 RecvMsg->CurrMsg->MsgUIDL =
515 NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf));
516 RecvMsg->CurrMsg->MsgUID =
517 NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf) * 2);
519 StrBufExtract_token(RecvMsg->CurrMsg->MsgUIDL,
520 RecvMsg->IO.IOBuf, 2, ' ');
522 StrBufPrintf(RecvMsg->CurrMsg->MsgUID,
524 ChrPtr(RecvMsg->RoomName),
525 ChrPtr(RecvMsg->CurrMsg->MsgUIDL),
526 RecvMsg->IO.ConnectMe->User,
527 RecvMsg->IO.ConnectMe->Host);
533 eNextState POP3C_SendGetOneMsg(pop3aggr *RecvMsg)
535 AsyncIO *IO = &RecvMsg->IO;
540 SetPOP3State(IO, eGetMsg);
542 RecvMsg->CurrMsg = NULL;
543 while ((RecvMsg->Pos != NULL) &&
544 GetNextHashPos(RecvMsg->MsgNumbers,
548 (RecvMsg->CurrMsg = (FetchItem*) vData,
549 RecvMsg->CurrMsg->NeedFetch == 0))
552 if ((RecvMsg->CurrMsg != NULL ) && (RecvMsg->CurrMsg->NeedFetch == 1))
554 /* Message has not been seen.
555 * Tell the server to fetch the message... */
556 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
557 "RETR %ld\r\n", RecvMsg->CurrMsg->MSGID);
562 RecvMsg->State = ReadQuitState;
563 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
568 eNextState POP3C_ReadMessageBodyFollowing(pop3aggr *RecvMsg)
570 AsyncIO *IO = &RecvMsg->IO;
572 if (!POP3C_OK) return eTerminateConnection;
573 RecvMsg->IO.ReadMsg = NewAsyncMsg(HKEY("."),
574 RecvMsg->CurrMsg->MSGSize,
583 eNextState POP3C_StoreMsgRead(AsyncIO *IO)
585 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
587 SetPOP3State(IO, eStoreMsg);
589 EVP3CCS_syslog(LOG_DEBUG,
590 "MARKING: %s as seen: ",
591 ChrPtr(RecvMsg->CurrMsg->MsgUID));
592 CheckIfAlreadySeen("POP3 Item Seen",
593 RecvMsg->CurrMsg->MsgUID,
595 EvGetNow(IO) - USETABLE_ANTIEXPIRE,
599 return DBQueueEventContext(&RecvMsg->IO, POP3_C_ReAttachToFetchMessages);
601 eNextState POP3C_SaveMsg(AsyncIO *IO)
604 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
606 /* Do Something With It (tm) */
607 msgnum = CtdlSubmitMsg(RecvMsg->CurrMsg->Msg,
609 ChrPtr(RecvMsg->RoomName),
613 /* Message has been committed to the store
614 * write the uidl to the use table
615 * so we don't fetch this message again
618 CM_Free(RecvMsg->CurrMsg->Msg);
621 return NextDBOperation(&RecvMsg->IO, POP3C_StoreMsgRead);
624 eNextState POP3C_ReadMessageBody(pop3aggr *RecvMsg)
626 AsyncIO *IO = &RecvMsg->IO;
627 EVP3CM_syslog(LOG_DEBUG, "Converting message...");
628 RecvMsg->CurrMsg->Msg =
629 convert_internet_message_buf(&RecvMsg->IO.ReadMsg->MsgBuf);
630 return EventQueueDBOperation(&RecvMsg->IO, POP3C_SaveMsg, 0);
633 eNextState POP3C_SendDelete(pop3aggr *RecvMsg)
635 AsyncIO *IO = &RecvMsg->IO;
637 SetPOP3State(IO, eDelete);
639 if (!RecvMsg->keep) {
640 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
641 "DELE %ld\r\n", RecvMsg->CurrMsg->MSGID);
646 RecvMsg->State = ReadMessageBodyFollowing;
647 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
650 eNextState POP3C_ReadDeleteState(pop3aggr *RecvMsg)
652 AsyncIO *IO = &RecvMsg->IO;
654 RecvMsg->State = GetOneMessageIDState;
658 eNextState POP3C_SendQuit(pop3aggr *RecvMsg)
660 AsyncIO *IO = &RecvMsg->IO;
661 SetPOP3State(IO, eQuit);
664 StrBufPlain(RecvMsg->IO.SendBuf.Buf,
671 eNextState POP3C_ReadQuitState(pop3aggr *RecvMsg)
673 AsyncIO *IO = &RecvMsg->IO;
675 return eTerminateConnection;
678 const long POP3_C_ConnTimeout = 1000;
679 const long DefaultPOP3Port = 110;
681 Pop3ClientHandler POP3C_ReadHandlers[] = {
685 POP3C_GetListCommandState,
686 POP3C_GetListOneLine,
687 POP3C_GetOneMessageIDState,
688 POP3C_ReadMessageBodyFollowing,
689 POP3C_ReadMessageBody,
690 POP3C_ReadDeleteState,
694 const long POP3_C_SendTimeouts[POP3C_MaxRead] = {
704 const ConstStr POP3C_ReadErrors[POP3C_MaxRead] = {
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 ")},
712 {HKEY("Connection broken during ")}
715 Pop3ClientHandler POP3C_SendHandlers[] = {
716 NULL, /* we don't send a greeting */
719 POP3C_SendListCommand,
721 POP3C_GetOneMessagID,
728 const long POP3_C_ReadTimeouts[] = {
740 /*****************************************************************************/
741 /* POP3 CLIENT DISPATCHER */
742 /*****************************************************************************/
744 void POP3SetTimeout(eNextState NextTCPState, pop3aggr *pMsg)
746 AsyncIO *IO = &pMsg->IO;
747 double Timeout = 0.0;
749 EVP3C_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
751 switch (NextTCPState) {
755 Timeout = POP3_C_SendTimeouts[pMsg->State];
757 if (pMsg->State == eDATABody) {
758 / * if we're sending a huge message, we need more time. * /
759 Timeout += StrLength(pMsg->msgtext) / 1024;
765 Timeout = POP3_C_ReadTimeouts[pMsg->State];
767 if (pMsg->State == eDATATerminateBody) {
769 * some mailservers take a nap before accepting the message
770 * content inspection and such.
772 Timeout += StrLength(pMsg->msgtext) / 1024;
783 case eTerminateConnection:
786 case eReadMore://// TODO
789 SetNextTimeout(&pMsg->IO, Timeout);
791 eNextState POP3_C_DispatchReadDone(AsyncIO *IO)
793 /* EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
794 pop3aggr *pMsg = IO->Data;
797 rc = POP3C_ReadHandlers[pMsg->State](pMsg);
800 POP3SetTimeout(rc, pMsg);
803 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO)
805 pop3aggr *pMsg = IO->Data;
808 /* EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
809 rc = POP3C_SendHandlers[pMsg->State](pMsg);
810 POP3SetTimeout(rc, pMsg);
815 /*****************************************************************************/
816 /* POP3 CLIENT ERROR CATCHERS */
817 /*****************************************************************************/
818 eNextState POP3_C_Terminate(AsyncIO *IO)
820 /// pop3aggr *pMsg = (pop3aggr *)IO->Data;
822 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
823 FinalizePOP3AggrRun(IO);
826 eNextState POP3_C_TerminateDB(AsyncIO *IO)
828 /// pop3aggr *pMsg = (pop3aggr *)IO->Data;
830 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
831 FinalizePOP3AggrRun(IO);
834 eNextState POP3_C_Timeout(AsyncIO *IO)
836 pop3aggr *pMsg = IO->Data;
838 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
839 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
840 return FailAggregationRun(IO);
842 eNextState POP3_C_ConnFail(AsyncIO *IO)
844 pop3aggr *pMsg = (pop3aggr *)IO->Data;
846 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
847 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
848 return FailAggregationRun(IO);
850 eNextState POP3_C_DNSFail(AsyncIO *IO)
852 pop3aggr *pMsg = (pop3aggr *)IO->Data;
854 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
855 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
856 return FailAggregationRun(IO);
858 eNextState POP3_C_Shutdown(AsyncIO *IO)
860 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
861 //// pop3aggr *pMsg = IO->Data;
863 ////pMsg->MyQEntry->Status = 3;
864 ///StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message retrieval."));
865 FinalizePOP3AggrRun(IO);
871 * @brief lineread Handler; understands when to read more POP3 lines,
872 * and when this is a one-lined reply.
874 eReadState POP3_C_ReadServerStatus(AsyncIO *IO)
876 eReadState Finished = eBufferNotEmpty;
878 switch (IO->NextState) {
883 case eTerminateConnection:
885 Finished = eReadFail;
892 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
896 Finished = CtdlReadMessageBodyAsync(IO);
902 /*****************************************************************************
903 * So we connect our Server IP here. *
904 *****************************************************************************/
905 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO)
907 pop3aggr *cpptr = IO->Data;
909 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
910 ////??? cpptr->State ++;
911 if (cpptr->Pos == NULL)
912 cpptr->Pos = GetNewHashPos(cpptr->MsgNumbers, 0);
914 POP3_C_DispatchWriteDone(IO);
915 ReAttachIO(IO, cpptr, 0);
916 IO->NextState = eReadMessage;
917 return IO->NextState;
920 eNextState pop3_connect_ip(AsyncIO *IO)
922 pop3aggr *cpptr = IO->Data;
924 if (cpptr->IOStart == 0.0) /* whith or without DNS? */
925 cpptr->IOStart = IO->Now;
927 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
929 return EvConnectSock(IO,
931 POP3_C_ReadTimeouts[0],
935 eNextState pop3_get_one_host_ip_done(AsyncIO *IO)
937 pop3aggr *cpptr = IO->Data;
938 struct hostent *hostent;
942 hostent = cpptr->HostLookup.VParsedDNSReply;
943 if ((cpptr->HostLookup.DNSStatus == ARES_SUCCESS) &&
944 (hostent != NULL) ) {
945 memset(&cpptr->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
946 if (cpptr->IO.ConnectMe->IPv6) {
947 memcpy(&cpptr->IO.ConnectMe->Addr.sin6_addr.s6_addr,
948 &hostent->h_addr_list[0],
949 sizeof(struct in6_addr));
951 cpptr->IO.ConnectMe->Addr.sin6_family =
953 cpptr->IO.ConnectMe->Addr.sin6_port =
954 htons(DefaultPOP3Port);
957 struct sockaddr_in *addr =
958 (struct sockaddr_in*)
959 &cpptr->IO.ConnectMe->Addr;
961 memcpy(&addr->sin_addr.s_addr,
962 hostent->h_addr_list[0],
965 addr->sin_family = hostent->h_addrtype;
966 addr->sin_port = htons(DefaultPOP3Port);
968 return pop3_connect_ip(IO);
974 eNextState pop3_get_one_host_ip(AsyncIO *IO)
976 pop3aggr *cpptr = IO->Data;
978 cpptr->IOStart = IO->Now;
980 EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
982 EVP3CCS_syslog(LOG_DEBUG,
983 "POP3 client[%ld]: looking up %s-Record %s : %d ...\n",
985 (cpptr->IO.ConnectMe->IPv6)? "aaaa": "a",
986 cpptr->IO.ConnectMe->Host,
987 cpptr->IO.ConnectMe->Port);
989 QueueQuery((cpptr->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a,
990 cpptr->IO.ConnectMe->Host,
993 pop3_get_one_host_ip_done);
994 IO->NextState = eReadDNSReply;
995 return IO->NextState;
1000 int pop3_do_fetching(pop3aggr *cpptr)
1002 AsyncIO *IO = &cpptr->IO;
1007 POP3_C_ReadServerStatus,
1009 POP3_C_DispatchWriteDone,
1010 POP3_C_DispatchReadDone,
1017 safestrncpy(((CitContext *)cpptr->IO.CitContext)->cs_host,
1019 sizeof(((CitContext *)cpptr->IO.CitContext)->cs_host));
1021 if (cpptr->IO.ConnectMe->IsIP) {
1022 QueueEventContext(&cpptr->IO,
1026 QueueEventContext(&cpptr->IO,
1027 pop3_get_one_host_ip);
1033 * Scan a room's netconfig to determine whether it requires POP3 aggregation
1035 void pop3client_scan_room(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCFG)
1037 const RoomNetCfgLine *pLine;
1040 pthread_mutex_lock(&POP3QueueMutex);
1041 if (GetHash(POP3QueueRooms, LKEY(qrbuf->QRnumber), &vptr))
1043 pthread_mutex_unlock(&POP3QueueMutex);
1044 EVP3CQ_syslog(LOG_DEBUG,
1045 "pop3client: [%ld] %s already in progress.",
1050 pthread_mutex_unlock(&POP3QueueMutex);
1052 if (server_shutting_down) return;
1054 pLine = OneRNCFG->NetConfigs[pop3client];
1056 while (pLine != NULL)
1060 cptr = (pop3aggr *) malloc(sizeof(pop3aggr));
1061 memset(cptr, 0, sizeof(pop3aggr));
1062 ///TODO do we need this? cptr->roomlist_parts=1;
1063 cptr->RoomName = NewStrBufPlain(qrbuf->QRname, -1);
1064 cptr->pop3user = NewStrBufDup(pLine->Value[1]);
1065 cptr->pop3pass = NewStrBufDup(pLine->Value[2]);
1066 cptr->Url = NewStrBuf();
1067 cptr->Host = NewStrBufDup(pLine->Value[0]);
1069 cptr->keep = atol(ChrPtr(pLine->Value[3]));
1070 cptr->interval = atol(ChrPtr(pLine->Value[4]));
1072 StrBufAppendBufPlain(cptr->Url, HKEY("pop3://"), 0);
1073 StrBufUrlescUPAppend(cptr->Url, cptr->pop3user, NULL);
1074 StrBufAppendBufPlain(cptr->Url, HKEY(":"), 0);
1075 StrBufUrlescUPAppend(cptr->Url, cptr->pop3pass, NULL);
1076 StrBufAppendBufPlain(cptr->Url, HKEY("@"), 0);
1077 StrBufAppendBuf(cptr->Url, cptr->Host, 0);
1078 StrBufAppendBufPlain(cptr->Url, HKEY("/"), 0);
1079 StrBufUrlescAppend(cptr->Url, cptr->RoomName, NULL);
1081 ParseURL(&cptr->IO.ConnectMe, cptr->Url, 110);
1085 /* todo: we need to reunite the url to be shure. */
1087 pthread_mutex_lock(&POP3ueueMutex);
1088 GetHash(POP3FetchUrls, SKEY(ptr->Url), &vptr);
1089 use_this_cptr = (pop3aggr *)vptr;
1091 if (use_this_rncptr != NULL)
1093 /* mustn't attach to an active session */
1094 if (use_this_cptr->RefCount > 0)
1096 DeletePOP3Cfg(cptr);
1102 StrBufAppendBufPlain(
1103 use_this_cptr->rooms,
1106 if (use_this_cptr->roomlist_parts == 1)
1108 use_this_cptr->OtherQRnumbers
1109 = NewHash(1, lFlathash);
1111 QRnumber = (long*)malloc(sizeof(long));
1112 *QRnumber = qrbuf->QRnumber;
1113 Put(use_this_cptr->OtherQRnumbers,
1114 LKEY(qrbuf->QRnumber),
1118 use_this_cptr->roomlist_parts++;
1120 pthread_mutex_unlock(&POP3QueueMutex);
1123 pthread_mutex_unlock(&RSSQueueMutex);
1125 cptr->n = Pop3ClientID++;
1126 pthread_mutex_lock(&POP3QueueMutex);
1130 DeletePOP3Aggregator);
1132 pthread_mutex_unlock(&POP3QueueMutex);
1133 pLine = pLine->next;
1138 static int doing_pop3client = 0;
1140 void pop3client_scan(void) {
1141 static time_t last_run = 0L;
1142 time_t fastest_scan;
1149 become_session(&pop3_client_CC);
1151 if (config.c_pop3_fastest < config.c_pop3_fetch)
1152 fastest_scan = config.c_pop3_fastest;
1154 fastest_scan = config.c_pop3_fetch;
1157 * Run POP3 aggregation no more frequently than once every n seconds
1159 if ( (time(NULL) - last_run) < fastest_scan ) {
1164 * This is a simple concurrency check to make sure only one pop3client
1165 * run is done at a time. We could do this with a mutex, but since we
1166 * don't really require extremely fine granularity here, we'll do it
1167 * with a static variable instead.
1169 if (doing_pop3client) return;
1170 doing_pop3client = 1;
1172 EVP3CQM_syslog(LOG_DEBUG, "pop3client started");
1173 CtdlForEachNetCfgRoom(pop3client_scan_room, NULL, pop3client);
1175 pthread_mutex_lock(&POP3QueueMutex);
1176 it = GetNewHashPos(POP3FetchUrls, 0);
1177 while (!server_shutting_down &&
1178 GetNextHashPos(POP3FetchUrls, it, &len, &Key, &vrptr) &&
1180 cptr = (pop3aggr *)vrptr;
1181 if (cptr->RefCount == 0)
1182 if (!pop3_do_fetching(cptr))
1183 DeletePOP3Aggregator(cptr);////TODO
1186 if ((palist->interval && time(NULL) > (last_run + palist->interval))
1187 || (time(NULL) > last_run + config.c_pop3_fetch))
1188 pop3_do_fetching(palist->roomname, palist->pop3host,
1189 palist->pop3user, palist->pop3pass, palist->keep);
1191 palist = palist->next;
1196 pthread_mutex_unlock(&POP3QueueMutex);
1198 EVP3CQM_syslog(LOG_DEBUG, "pop3client ended");
1199 last_run = time(NULL);
1200 doing_pop3client = 0;
1204 void pop3_cleanup(void)
1206 /* citthread_mutex_destroy(&POP3QueueMutex); TODO */
1207 while (doing_pop3client != 0) ;
1208 DeleteHash(&POP3FetchUrls);
1209 DeleteHash(&POP3QueueRooms);
1214 void LogDebugEnablePOP3Client(const int n)
1216 POP3ClientDebugEnabled = n;
1219 CTDL_MODULE_INIT(pop3client)
1223 CtdlFillSystemContext(&pop3_client_CC, "POP3aggr");
1224 CtdlREGISTERRoomCfgType(pop3client, ParseGeneric, 0, 5, SerializeGeneric, DeleteGenericCfgLine);
1225 pthread_mutex_init(&POP3QueueMutex, NULL);
1226 POP3QueueRooms = NewHash(1, lFlathash);
1227 POP3FetchUrls = NewHash(1, NULL);
1228 CtdlRegisterSessionHook(pop3client_scan, EVT_TIMER, PRIO_AGGR + 50);
1229 CtdlRegisterEVCleanupHook(pop3_cleanup);
1230 CtdlRegisterDebugFlagHook(HKEY("pop3client"), LogDebugEnablePOP3Client, &POP3ClientDebugEnabled);
1233 /* return our module id for the log */
1234 return "pop3client";