2 * Consolidate mail from remote POP3 accounts.
4 * Copyright (c) 2007-2009 by the citadel.org team
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * 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 struct CitContext pop3_client_CC;
58 citthread_mutex_t POP3QueueMutex; /* locks the access to the following vars: */
59 HashList *POP3QueueRooms = NULL; /* rss_room_counter */
60 HashList *POP3FetchUrls = NULL; /* -> rss_aggregator; ->RefCount access to be locked too. */
62 typedef struct __pop3_room_counter {
67 typedef enum ePOP3_C_States {
74 ReadMessageBodyFollowing,
82 typedef struct _FetchItem {
88 struct CtdlMessage *Msg;
91 void HfreeFetchItem(void *vItem)
93 FetchItem *Item = (FetchItem*) vItem;
94 FreeStrBuf(&Item->MsgUIDL);
95 FreeStrBuf(&Item->MsgUID);
99 typedef struct __pop3aggr {
104 /// ParsedURL *Pop3Host;
105 DNSQueryParts HostLookup;
109 HashList *OtherQRnumbers;
112 /// StrBuf *pop3host; -> URL
115 StrBuf *RoomName; // TODO: fill me
118 ePOP3_C_States State;
119 HashList *MsgNumbers;
124 void DeletePOP3Aggregator(void *vptr)
126 pop3aggr *ptr = vptr;
127 DeleteHashPos(&ptr->Pos);
128 DeleteHash(&ptr->MsgNumbers);
129 // FreeStrBuf(&ptr->rooms);
130 FreeStrBuf(&ptr->pop3user);
131 FreeStrBuf(&ptr->pop3pass);
132 FreeStrBuf(&ptr->RoomName);
133 FreeURL(&ptr->IO.ConnectMe);
134 FreeStrBuf(&ptr->Url);
135 FreeStrBuf(&ptr->IO.IOBuf);
136 FreeStrBuf(&ptr->IO.SendBuf.Buf);
137 FreeStrBuf(&ptr->IO.RecvBuf.Buf);
138 DeleteAsyncMsg(&ptr->IO.ReadMsg);
143 typedef eNextState(*Pop3ClientHandler)(pop3aggr* RecvMsg);
145 eNextState POP3_C_Shutdown(AsyncIO *IO);
146 eNextState POP3_C_Timeout(AsyncIO *IO);
147 eNextState POP3_C_ConnFail(AsyncIO *IO);
148 eNextState POP3_C_DispatchReadDone(AsyncIO *IO);
149 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO);
150 eNextState POP3_C_Terminate(AsyncIO *IO);
151 eReadState POP3_C_ReadServerStatus(AsyncIO *IO);
152 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO);
154 eNextState FinalizePOP3AggrRun(AsyncIO *IO)
157 pop3aggr *cptr = (pop3aggr *)IO->Data;
159 syslog(LOG_DEBUG, "Terminating Aggregator; bye.\n");
161 It = GetNewHashPos(POP3FetchUrls, 0);
162 citthread_mutex_lock(&POP3QueueMutex);
164 GetHashPosFromKey(POP3FetchUrls, SKEY(cptr->Url), It);
165 DeleteEntryFromHash(POP3FetchUrls, It);
167 citthread_mutex_unlock(&POP3QueueMutex);
172 eNextState FailAggregationRun(AsyncIO *IO)
177 #define POP3C_DBG_SEND() syslog(LOG_DEBUG, "POP3 client[%ld]: > %s\n", RecvMsg->n, ChrPtr(RecvMsg->IO.SendBuf.Buf))
178 #define POP3C_DBG_READ() syslog(LOG_DEBUG, "POP3 client[%ld]: < %s\n", RecvMsg->n, ChrPtr(RecvMsg->IO.IOBuf))
179 #define POP3C_OK (strncasecmp(ChrPtr(RecvMsg->IO.IOBuf), "+OK", 3) == 0)
181 eNextState POP3C_ReadGreeting(pop3aggr *RecvMsg)
184 /* Read the server greeting */
185 if (!POP3C_OK) return eTerminateConnection;
186 else return eSendReply;
190 eNextState POP3C_SendUser(pop3aggr *RecvMsg)
192 /* Identify ourselves. NOTE: we have to append a CR to each command. The LF will
193 * automatically be appended by sock_puts(). Believe it or not, leaving out the CR
194 * will cause problems if the server happens to be Exchange, which is so b0rken it
195 * actually barfs on LF-terminated newlines.
197 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
198 "USER %s\r\n", ChrPtr(RecvMsg->pop3user));
203 eNextState POP3C_GetUserState(pop3aggr *RecvMsg)
206 if (!POP3C_OK) return eTerminateConnection;
207 else return eSendReply;
210 eNextState POP3C_SendPassword(pop3aggr *RecvMsg)
213 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
214 "PASS %s\r\n", ChrPtr(RecvMsg->pop3pass));
215 syslog(LOG_DEBUG, "<PASS <password>\n");
220 eNextState POP3C_GetPassState(pop3aggr *RecvMsg)
223 if (!POP3C_OK) return eTerminateConnection;
224 else return eSendReply;
227 eNextState POP3C_SendListCommand(pop3aggr *RecvMsg)
229 /* Get the list of messages */
230 StrBufPlain(RecvMsg->IO.SendBuf.Buf, HKEY("LIST\r\n"));
235 eNextState POP3C_GetListCommandState(pop3aggr *RecvMsg)
238 if (!POP3C_OK) return eTerminateConnection;
239 RecvMsg->MsgNumbers = NewHash(1, NULL);
245 eNextState POP3C_GetListOneLine(pop3aggr *RecvMsg)
251 FetchItem *OneMsg = NULL;
254 if ((StrLength(RecvMsg->IO.IOBuf) == 1) &&
255 (ChrPtr(RecvMsg->IO.IOBuf)[0] == '.'))
257 if (GetCount(RecvMsg->MsgNumbers) == 0)
259 //// RecvMsg->Sate = ReadQuitState;
263 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
268 OneMsg = (FetchItem*) malloc(sizeof(FetchItem));
269 memset(OneMsg, 0, sizeof(FetchItem));
270 OneMsg->MSGID = atol(ChrPtr(RecvMsg->IO.IOBuf));
272 pch = strchr(ChrPtr(RecvMsg->IO.IOBuf), ' ');
275 OneMsg->MSGSize = atol(pch + 1);
278 rc = TestValidateHash(RecvMsg->MsgNumbers);
280 syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
283 Put(RecvMsg->MsgNumbers, LKEY(OneMsg->MSGID), OneMsg, HfreeFetchItem);
285 rc = TestValidateHash(RecvMsg->MsgNumbers);
287 syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
289 //RecvMsg->State --; /* read next Line */
293 eNextState POP3_FetchNetworkUsetableEntry(AsyncIO *IO)
298 struct cdbdata *cdbut;
299 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
301 if(GetNextHashPos(RecvMsg->MsgNumbers, RecvMsg->Pos, &HKLen, &HKey, &vData))
305 RecvMsg->CurrMsg = (FetchItem*) vData;
306 syslog(LOG_DEBUG, "CHECKING: whether %s has already been seen: ", ChrPtr(RecvMsg->CurrMsg->MsgUID));
307 /* Find out if we've already seen this item */
308 safestrncpy(ut.ut_msgid,
309 ChrPtr(RecvMsg->CurrMsg->MsgUID),
310 sizeof(ut.ut_msgid));
311 ut.ut_timestamp = time(NULL);/// TODO: libev timestamp!
313 cdbut = cdb_fetch(CDB_USETABLE, SKEY(RecvMsg->CurrMsg->MsgUID));
315 /* Item has already been seen */
316 syslog(LOG_DEBUG, "YES\n");
319 /* rewrite the record anyway, to update the timestamp */
320 cdb_store(CDB_USETABLE,
321 SKEY(RecvMsg->CurrMsg->MsgUID),
322 &ut, sizeof(struct UseTable) );
323 RecvMsg->CurrMsg->NeedFetch = 1; ////TODO0;
327 syslog(LOG_DEBUG, "NO\n");
328 RecvMsg->CurrMsg->NeedFetch = 1;
330 return NextDBOperation(&RecvMsg->IO, POP3_FetchNetworkUsetableEntry);
334 /* ok, now we know them all, continue with reading the actual messages. */
335 DeleteHashPos(&RecvMsg->Pos);
337 return QueueEventContext(IO, POP3_C_ReAttachToFetchMessages);
341 eNextState POP3C_GetOneMessagID(pop3aggr *RecvMsg)
349 rc = TestValidateHash(RecvMsg->MsgNumbers);
351 syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
353 if(GetNextHashPos(RecvMsg->MsgNumbers, RecvMsg->Pos, &HKLen, &HKey, &vData))
355 RecvMsg->CurrMsg = (FetchItem*) vData;
356 /* Find out the UIDL of the message, to determine whether we've already downloaded it */
357 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
358 "UIDL %ld\r\n", RecvMsg->CurrMsg->MSGID);
364 DeleteHashPos(&RecvMsg->Pos);
365 /// done receiving uidls.. start looking them up now.
366 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
367 return QueueDBOperation(&RecvMsg->IO, POP3_FetchNetworkUsetableEntry);
369 return eReadMore; /* TODO */
372 eNextState POP3C_GetOneMessageIDState(pop3aggr *RecvMsg)
376 rc = TestValidateHash(RecvMsg->MsgNumbers);
378 syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
382 if (!POP3C_OK) return eTerminateConnection;
383 RecvMsg->CurrMsg->MsgUIDL = NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf));
384 RecvMsg->CurrMsg->MsgUID = NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf) * 2);
386 StrBufExtract_token(RecvMsg->CurrMsg->MsgUIDL, RecvMsg->IO.IOBuf, 2, ' ');
387 StrBufPrintf(RecvMsg->CurrMsg->MsgUID,
389 ChrPtr(RecvMsg->RoomName),
390 ChrPtr(RecvMsg->CurrMsg->MsgUIDL),
391 RecvMsg->IO.ConnectMe->User,
392 RecvMsg->IO.ConnectMe->Host);
398 eNextState POP3C_SendGetOneMsg(pop3aggr *RecvMsg)
404 RecvMsg->CurrMsg = NULL;
405 while (GetNextHashPos(RecvMsg->MsgNumbers, RecvMsg->Pos, &HKLen, &HKey, &vData) &&
406 (RecvMsg->CurrMsg = (FetchItem*) vData, RecvMsg->CurrMsg->NeedFetch == 0))
409 if ((RecvMsg->CurrMsg != NULL ) && (RecvMsg->CurrMsg->NeedFetch == 1))
411 /* Message has not been seen. Tell the server to fetch the message... */
412 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
413 "RETR %ld\r\n", RecvMsg->CurrMsg->MSGID);
418 RecvMsg->State = ReadQuitState;
419 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
424 eNextState POP3C_ReadMessageBodyFollowing(pop3aggr *RecvMsg)
427 if (!POP3C_OK) return eTerminateConnection;
428 RecvMsg->IO.ReadMsg = NewAsyncMsg(HKEY("."),
429 RecvMsg->CurrMsg->MSGSize,
438 eNextState POP3C_StoreMsgRead(AsyncIO *IO)
440 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
443 syslog(LOG_DEBUG, "MARKING: %s as seen: ", ChrPtr(RecvMsg->CurrMsg->MsgUID));
445 safestrncpy(ut.ut_msgid,
446 ChrPtr(RecvMsg->CurrMsg->MsgUID),
447 sizeof(ut.ut_msgid));
448 ut.ut_timestamp = time(NULL); /* TODO: use libev time */
449 cdb_store(CDB_USETABLE,
450 ChrPtr(RecvMsg->CurrMsg->MsgUID),
451 StrLength(RecvMsg->CurrMsg->MsgUID),
453 sizeof(struct UseTable) );
455 return QueueEventContext(&RecvMsg->IO, POP3_C_ReAttachToFetchMessages);
457 eNextState POP3C_SaveMsg(AsyncIO *IO)
460 pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
462 /* Do Something With It (tm) */
463 msgnum = CtdlSubmitMsg(RecvMsg->CurrMsg->Msg,
465 ChrPtr(RecvMsg->RoomName),
468 /* Message has been committed to the store */
469 /* write the uidl to the use table so we don't fetch this message again */
471 CtdlFreeMessage(RecvMsg->CurrMsg->Msg);
473 return NextDBOperation(&RecvMsg->IO, POP3C_StoreMsgRead);
476 eNextState POP3C_ReadMessageBody(pop3aggr *RecvMsg)
478 syslog(LOG_DEBUG, "Converting message...\n");
479 RecvMsg->CurrMsg->Msg = convert_internet_message_buf(&RecvMsg->IO.ReadMsg->MsgBuf);
481 return QueueDBOperation(&RecvMsg->IO, POP3C_SaveMsg);
484 eNextState POP3C_SendDelete(pop3aggr *RecvMsg)
486 if (!RecvMsg->keep) {
487 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
488 "DELE %ld\r\n", RecvMsg->CurrMsg->MSGID);
493 RecvMsg->State = ReadMessageBodyFollowing;
494 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
497 eNextState POP3C_ReadDeleteState(pop3aggr *RecvMsg)
500 RecvMsg->State = GetOneMessageIDState;
504 eNextState POP3C_SendQuit(pop3aggr *RecvMsg)
507 StrBufPlain(RecvMsg->IO.SendBuf.Buf,
514 eNextState POP3C_ReadQuitState(pop3aggr *RecvMsg)
517 return eTerminateConnection;
520 const long POP3_C_ConnTimeout = 1000;
521 const long DefaultPOP3Port = 110;
523 Pop3ClientHandler POP3C_ReadHandlers[] = {
527 POP3C_GetListCommandState,
528 POP3C_GetListOneLine,
529 POP3C_GetOneMessageIDState,
530 POP3C_ReadMessageBodyFollowing,
531 POP3C_ReadMessageBody,
532 POP3C_ReadDeleteState,
536 const long POP3_C_SendTimeouts[POP3C_MaxRead] = {
546 const ConstStr POP3C_ReadErrors[POP3C_MaxRead] = {
547 {HKEY("Connection broken during ")},
548 {HKEY("Connection broken during ")},
549 {HKEY("Connection broken during ")},
550 {HKEY("Connection broken during ")},
551 {HKEY("Connection broken during ")},
552 {HKEY("Connection broken during ")},
553 {HKEY("Connection broken during ")},
554 {HKEY("Connection broken during ")}
557 Pop3ClientHandler POP3C_SendHandlers[] = {
558 NULL, /* we don't send a greeting */
561 POP3C_SendListCommand,
563 POP3C_GetOneMessagID,
570 const long POP3_C_ReadTimeouts[] = {
582 /*****************************************************************************/
583 /* POP3 CLIENT DISPATCHER */
584 /*****************************************************************************/
586 void POP3SetTimeout(eNextState NextTCPState, pop3aggr *pMsg)
588 double Timeout = 0.0;
590 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
592 switch (NextTCPState) {
595 Timeout = POP3_C_SendTimeouts[pMsg->State];
597 if (pMsg->State == eDATABody) {
598 / * if we're sending a huge message, we need more time. * /
599 Timeout += StrLength(pMsg->msgtext) / 1024;
604 Timeout = POP3_C_ReadTimeouts[pMsg->State];
606 if (pMsg->State == eDATATerminateBody) {
608 * some mailservers take a nap before accepting the message
609 * content inspection and such.
611 Timeout += StrLength(pMsg->msgtext) / 1024;
622 case eTerminateConnection:
625 case eReadMore://// TODO
628 SetNextTimeout(&pMsg->IO, Timeout);
630 eNextState POP3_C_DispatchReadDone(AsyncIO *IO)
632 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
633 pop3aggr *pMsg = IO->Data;
636 rc = POP3C_ReadHandlers[pMsg->State](pMsg);
639 POP3SetTimeout(rc, pMsg);
642 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO)
644 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
645 pop3aggr *pMsg = IO->Data;
648 rc = POP3C_SendHandlers[pMsg->State](pMsg);
649 POP3SetTimeout(rc, pMsg);
654 /*****************************************************************************/
655 /* POP3 CLIENT ERROR CATCHERS */
656 /*****************************************************************************/
657 eNextState POP3_C_Terminate(AsyncIO *IO)
659 /// pop3aggr *pMsg = (pop3aggr *)IO->Data;
661 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
662 FinalizePOP3AggrRun(IO);
665 eNextState POP3_C_Timeout(AsyncIO *IO)
667 pop3aggr *pMsg = IO->Data;
669 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
670 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
671 return FailAggregationRun(IO);
673 eNextState POP3_C_ConnFail(AsyncIO *IO)
675 pop3aggr *pMsg = (pop3aggr *)IO->Data;
677 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
678 StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
679 return FailAggregationRun(IO);
681 eNextState POP3_C_Shutdown(AsyncIO *IO)
683 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
684 //// pop3aggr *pMsg = IO->Data;
686 ////pMsg->MyQEntry->Status = 3;
687 ///StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message retrieval."));
688 FinalizePOP3AggrRun(IO);
694 * @brief lineread Handler; understands when to read more POP3 lines, and when this is a one-lined reply.
696 eReadState POP3_C_ReadServerStatus(AsyncIO *IO)
698 eReadState Finished = eBufferNotEmpty;
700 switch (IO->NextState) {
705 case eTerminateConnection:
707 Finished = eReadFail;
713 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
716 Finished = CtdlReadMessageBodyAsync(IO);
722 /*****************************************************************************
723 * So we connect our Server IP here. *
724 *****************************************************************************/
725 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO)
727 pop3aggr *cpptr = IO->Data;
729 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
730 ////??? cpptr->State ++;
731 if (cpptr->Pos == NULL)
732 cpptr->Pos = GetNewHashPos(cpptr->MsgNumbers, 0);
734 POP3_C_DispatchWriteDone(IO);
735 ReAttachIO(IO, cpptr, 0);
736 IO->NextState = eReadMessage;
737 return IO->NextState;
740 eNextState connect_ip(AsyncIO *IO)
742 pop3aggr *cpptr = IO->Data;
744 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
746 //// IO->ConnectMe = &cpptr->Pop3Host;
747 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
749 /////// SetConnectStatus(IO);
751 return InitEventIO(IO, cpptr,
753 POP3_C_ReadTimeouts[0],
757 eNextState get_one_host_ip_done(AsyncIO *IO)
759 pop3aggr *cpptr = IO->Data;
760 struct hostent *hostent;
764 hostent = cpptr->HostLookup.VParsedDNSReply;
765 if ((cpptr->HostLookup.DNSStatus == ARES_SUCCESS) &&
766 (hostent != NULL) ) {
767 memset(&cpptr->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
768 if (cpptr->IO.ConnectMe->IPv6) {
769 memcpy(&cpptr->IO.ConnectMe->Addr.sin6_addr.s6_addr,
770 &hostent->h_addr_list[0],
771 sizeof(struct in6_addr));
773 cpptr->IO.ConnectMe->Addr.sin6_family = hostent->h_addrtype;
774 cpptr->IO.ConnectMe->Addr.sin6_port = htons(DefaultPOP3Port);
777 struct sockaddr_in *addr = (struct sockaddr_in*) &cpptr->IO.ConnectMe->Addr;
778 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
779 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
780 memcpy(&addr->sin_addr.s_addr,
781 hostent->h_addr_list[0],
784 addr->sin_family = hostent->h_addrtype;
785 addr->sin_port = htons(DefaultPOP3Port);
788 return connect_ip(IO);
794 eNextState get_one_host_ip(AsyncIO *IO)
796 pop3aggr *cpptr = IO->Data;
798 * here we start with the lookup of one host. it might be...
799 * - the relay host *sigh*
800 * - the direct hostname if there was no mx record
806 syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
809 "POP3 client[%ld]: looking up %s-Record %s : %d ...\n",
811 (cpptr->IO.ConnectMe->IPv6)? "aaaa": "a",
812 cpptr->IO.ConnectMe->Host,
813 cpptr->IO.ConnectMe->Port);
815 QueueQuery((cpptr->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a,
816 cpptr->IO.ConnectMe->Host,
819 get_one_host_ip_done);
820 IO->NextState = eReadDNSReply;
821 return IO->NextState;
826 int pop3_do_fetching(pop3aggr *cpptr)
830 cpptr->IO.Data = cpptr;
832 cpptr->IO.SendDone = POP3_C_DispatchWriteDone;
833 cpptr->IO.ReadDone = POP3_C_DispatchReadDone;
834 cpptr->IO.Terminate = POP3_C_Terminate;
835 cpptr->IO.LineReader = POP3_C_ReadServerStatus;
836 cpptr->IO.ConnFail = POP3_C_ConnFail;
837 cpptr->IO.Timeout = POP3_C_Timeout;
838 cpptr->IO.ShutdownAbort = POP3_C_Shutdown;
840 cpptr->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
841 cpptr->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
842 cpptr->IO.IOBuf = NewStrBuf();
844 cpptr->IO.NextState = eReadMessage;
846 syslog(LOG_DEBUG, "POP3: %s %s %s <password>\n", roomname, pop3host, pop3user);
847 syslog(LOG_DEBUG, "Connecting to <%s>\n", pop3host);
850 SubC = CloneContext (&pop3_client_CC);
851 SubC->session_specific_data = (char*) cpptr;
852 cpptr->IO.CitContext = SubC;
854 if (cpptr->IO.ConnectMe->IsIP) {
855 QueueEventContext(&cpptr->IO,
858 else { /* uneducated admin has chosen to add DNS to the equation... */
859 QueueEventContext(&cpptr->IO,
866 * Scan a room's netconfig to determine whether it requires POP3 aggregation
868 void pop3client_scan_room(struct ctdlroom *qrbuf, void *data)
875 char filename[PATH_MAX];
879 const char *CfgPtr, *lPtr;
882 // pop3_room_counter *Count = NULL;
885 citthread_mutex_lock(&POP3QueueMutex);
886 if (GetHash(POP3QueueRooms, LKEY(qrbuf->QRnumber), &vptr))
889 "pop3client: [%ld] %s already in progress.\n",
892 citthread_mutex_unlock(&POP3QueueMutex);
895 citthread_mutex_unlock(&POP3QueueMutex);
897 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
899 if (CtdlThreadCheckStop())
902 /* Only do net processing for rooms that have netconfigs */
903 fd = open(filename, 0);
905 //syslog(LOG_DEBUG, "rssclient: %s no config.\n", qrbuf->QRname);
908 if (CtdlThreadCheckStop())
910 if (fstat(fd, &statbuf) == -1) {
911 syslog(LOG_DEBUG, "ERROR: could not stat configfile '%s' - %s\n",
912 filename, strerror(errno));
915 if (CtdlThreadCheckStop())
917 CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
918 if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
920 FreeStrBuf(&CfgData);
921 syslog(LOG_DEBUG, "ERROR: reading config '%s' - %s<br>\n",
922 filename, strerror(errno));
926 if (CtdlThreadCheckStop())
930 CfgType = NewStrBuf();
931 Line = NewStrBufPlain(NULL, StrLength(CfgData));
936 Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
937 if (StrLength(Line) > 0)
940 StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
941 if (!strcasecmp("pop3client", ChrPtr(CfgType)))
948 Count = malloc(sizeof(pop3_room_counter));
953 cptr = (pop3aggr *) malloc(sizeof(pop3aggr));
954 memset(cptr, 0, sizeof(pop3aggr));
955 /// TODO do we need this? cptr->roomlist_parts = 1;
956 cptr->RoomName = NewStrBufPlain(qrbuf->QRname, -1);
957 cptr->pop3user = NewStrBufPlain(NULL, StrLength(Line));
958 cptr->pop3pass = NewStrBufPlain(NULL, StrLength(Line));
959 cptr->Url = NewStrBuf();
962 StrBufExtract_NextToken(Tmp, Line, &lPtr, '|');
963 StrBufExtract_NextToken(cptr->pop3user, Line, &lPtr, '|');
964 StrBufExtract_NextToken(cptr->pop3pass, Line, &lPtr, '|');
965 cptr->keep = StrBufExtractNext_long(Line, &lPtr, '|');
966 cptr->interval = StrBufExtractNext_long(Line, &lPtr, '|');
968 StrBufPrintf(cptr->Url, "pop3://%s:%s@%s/%s",
969 ChrPtr(cptr->pop3user),
970 ChrPtr(cptr->pop3pass),
972 ChrPtr(cptr->RoomName));
974 ParseURL(&cptr->IO.ConnectMe, cptr->Url, 110);
978 /* todo: we need to reunite the url to be shure. */
980 citthread_mutex_lock(&POP3ueueMutex);
981 GetHash(POP3FetchUrls, SKEY(ptr->Url), &vptr);
982 use_this_cptr = (pop3aggr *)vptr;
984 if (use_this_rncptr != NULL)
986 /* mustn't attach to an active session */
987 if (use_this_cptr->RefCount > 0)
995 StrBufAppendBufPlain(use_this_cptr->rooms,
998 if (use_this_cptr->roomlist_parts == 1)
1000 use_this_cptr->OtherQRnumbers = NewHash(1, lFlathash);
1002 QRnumber = (long*)malloc(sizeof(long));
1003 *QRnumber = qrbuf->QRnumber;
1004 Put(use_this_cptr->OtherQRnumbers, LKEY(qrbuf->QRnumber), QRnumber, NULL);
1005 use_this_cptr->roomlist_parts++;
1007 citthread_mutex_unlock(&POP3QueueMutex);
1010 citthread_mutex_unlock(&RSSQueueMutex);
1013 citthread_mutex_lock(&POP3QueueMutex);
1014 Put(POP3FetchUrls, SKEY(cptr->Url), cptr, DeletePOP3Aggregator);
1015 citthread_mutex_unlock(&POP3QueueMutex);
1025 FreeStrBuf(&CfgType);
1026 FreeStrBuf(&CfgData);
1030 void pop3client_scan(void) {
1031 static time_t last_run = 0L;
1032 static int doing_pop3client = 0;
1033 /// struct pop3aggr *pptr;
1034 time_t fastest_scan;
1041 if (config.c_pop3_fastest < config.c_pop3_fetch)
1042 fastest_scan = config.c_pop3_fastest;
1044 fastest_scan = config.c_pop3_fetch;
1047 * Run POP3 aggregation no more frequently than once every n seconds
1049 if ( (time(NULL) - last_run) < fastest_scan ) {
1054 * This is a simple concurrency check to make sure only one pop3client run
1055 * is done at a time. We could do this with a mutex, but since we
1056 * don't really require extremely fine granularity here, we'll do it
1057 * with a static variable instead.
1059 if (doing_pop3client) return;
1060 doing_pop3client = 1;
1062 syslog(LOG_DEBUG, "pop3client started\n");
1063 CtdlForEachRoom(pop3client_scan_room, NULL);
1066 citthread_mutex_lock(&POP3QueueMutex);
1067 it = GetNewHashPos(POP3FetchUrls, 0);
1068 while (GetNextHashPos(POP3FetchUrls, it, &len, &Key, &vrptr) &&
1070 cptr = (pop3aggr *)vrptr;
1071 if (cptr->RefCount == 0)
1072 if (!pop3_do_fetching(cptr))
1073 DeletePOP3Aggregator(cptr);////TODO
1076 citthread_mutex_unlock(&POP3QueueMutex);
1078 syslog(LOG_DEBUG, "pop3client ended\n");
1079 last_run = time(NULL);
1080 doing_pop3client = 0;
1084 void pop3_cleanup(void)
1086 citthread_mutex_destroy(&POP3QueueMutex);
1087 DeleteHash(&POP3FetchUrls);
1088 DeleteHash(&POP3QueueRooms);
1091 CTDL_MODULE_INIT(pop3client)
1095 CtdlFillSystemContext(&pop3_client_CC, "POP3aggr");
1096 citthread_mutex_init(&POP3QueueMutex, NULL);
1097 POP3QueueRooms = NewHash(1, lFlathash);
1098 POP3FetchUrls = NewHash(1, NULL);
1099 CtdlRegisterSessionHook(pop3client_scan, EVT_TIMER);
1100 CtdlRegisterCleanupHook(pop3_cleanup);
1102 /* return our Subversion id for the Log */
1103 return "pop3client";