c14e5da730f15ef0f10a3ab6cc1fd71099bec9c4
[citadel.git] / citadel / modules / pop3client / serv_pop3client.c
1 /*
2  * Consolidate mail from remote POP3 accounts.
3  *
4  * Copyright (c) 2007-2011 by the citadel.org team
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
27 # include <time.h>
28 #else
29 # if HAVE_SYS_TIME_H
30 #  include <sys/time.h>
31 # else
32 #  include <time.h>
33 # endif
34 #endif
35
36 #include <ctype.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <libcitadel.h>
42 #include "citadel.h"
43 #include "server.h"
44 #include "citserver.h"
45 #include "support.h"
46 #include "config.h"
47 #include "ctdl_module.h"
48 #include "clientsocket.h"
49 #include "msgbase.h"
50 #include "internet_addressing.h"
51 #include "database.h"
52 #include "citadel_dirs.h"
53 #include "event_client.h"
54
55
56 #define POP3C_OK (strncasecmp(ChrPtr(RecvMsg->IO.IOBuf), "+OK", 3) == 0)
57 int Pop3ClientID = 0;
58 int POP3ClientDebugEnabled = 0;
59
60 #define N ((pop3aggr*)IO->Data)->n
61
62 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (POP3ClientDebugEnabled != 0))
63
64 #define EVP3C_syslog(LEVEL, FORMAT, ...)                                \
65         DBGLOG(LEVEL) syslog(LEVEL,                                     \
66                              "IO[%ld]CC[%d][%ld]" FORMAT,               \
67                              IO->ID, CCID, N, __VA_ARGS__)
68
69 #define EVP3CM_syslog(LEVEL, FORMAT)                                    \
70         DBGLOG(LEVEL) syslog(LEVEL,                                     \
71                              "IO[%ld]CC[%d][%ld]" FORMAT,               \
72                              IO->ID, CCID, N)
73
74 #define EVP3CQ_syslog(LEVEL, FORMAT, ...)                               \
75         DBGLOG(LEVEL) syslog(LEVEL,                                     \
76                              "P3Q:" FORMAT,                             \
77                              __VA_ARGS__)
78
79 #define EVP3CQM_syslog(LEVEL, FORMAT)                                   \
80         DBGLOG(LEVEL) syslog(LEVEL,                                     \
81                              "P3Q" FORMAT                               \
82                 )
83
84 #define EVP3CCS_syslog(LEVEL, FORMAT, ...)                              \
85         DBGLOG(LEVEL) syslog(LEVEL, "IO[%ld][%ld]" FORMAT,              \
86                              IO->ID, N, __VA_ARGS__)
87
88 #define EVP3CCSM_syslog(LEVEL, FORMAT)                          \
89         DBGLOG(LEVEL) syslog(LEVEL, "IO[%ld][%ld]" FORMAT,      \
90                              IO->ID, N)
91
92 #define POP3C_DBG_SEND()                                                \
93         EVP3C_syslog(LOG_DEBUG,                                         \
94                      "POP3: > %s\n",                                    \
95                      ChrPtr(RecvMsg->IO.SendBuf.Buf))
96
97 #define POP3C_DBG_READ()                                \
98         EVP3C_syslog(LOG_DEBUG,                         \
99                      "POP3: < %s\n",                    \
100                      ChrPtr(RecvMsg->IO.IOBuf))
101
102
103 struct CitContext pop3_client_CC;
104
105 pthread_mutex_t POP3QueueMutex; /* locks the access to the following vars: */
106 HashList *POP3QueueRooms = NULL;
107 HashList *POP3FetchUrls = NULL;
108
109 typedef struct pop3aggr pop3aggr;
110 typedef eNextState(*Pop3ClientHandler)(pop3aggr* RecvMsg);
111
112 eNextState POP3_C_Shutdown(AsyncIO *IO);
113 eNextState POP3_C_Timeout(AsyncIO *IO);
114 eNextState POP3_C_ConnFail(AsyncIO *IO);
115 eNextState POP3_C_DNSFail(AsyncIO *IO);
116 eNextState POP3_C_DispatchReadDone(AsyncIO *IO);
117 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO);
118 eNextState POP3_C_Terminate(AsyncIO *IO);
119 eReadState POP3_C_ReadServerStatus(AsyncIO *IO);
120 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO);
121
122 typedef struct __pop3_room_counter {
123         int count;
124         long QRnumber;
125 }pop3_room_counter;
126
127 typedef enum ePOP3_C_States {
128         ReadGreeting,
129         GetUserState,
130         GetPassState,
131         GetListCommandState,
132         GetListOneLine,
133         GetOneMessageIDState,
134         ReadMessageBodyFollowing,
135         ReadMessageBody,
136         GetDeleteState,
137         ReadQuitState,
138         POP3C_MaxRead
139 }ePOP3_C_States;
140
141
142 typedef struct _FetchItem {
143         long MSGID;
144         long MSGSize;
145         StrBuf *MsgUIDL;
146         StrBuf *MsgUID;
147         int NeedFetch;
148         struct CtdlMessage *Msg;
149 } FetchItem;
150
151 void HfreeFetchItem(void *vItem)
152 {
153         FetchItem *Item = (FetchItem*) vItem;
154         FreeStrBuf(&Item->MsgUIDL);
155         FreeStrBuf(&Item->MsgUID);
156         free(Item);
157 }
158
159 struct pop3aggr {
160         AsyncIO  IO;
161
162         long n;
163         double IOStart;
164         long count;
165         long RefCount;
166         DNSQueryParts HostLookup;
167
168         long             QRnumber;
169         HashList        *OtherQRnumbers;
170
171         StrBuf          *Url;
172         StrBuf *pop3user;
173         StrBuf *pop3pass;
174         StrBuf *RoomName; // TODO: fill me
175         int keep;
176         time_t interval;
177         ePOP3_C_States State;
178         HashList *MsgNumbers;
179         HashPos *Pos;
180         FetchItem *CurrMsg;
181 };
182
183 void DeletePOP3Aggregator(void *vptr)
184 {
185         pop3aggr *ptr = vptr;
186         DeleteHashPos(&ptr->Pos);
187         DeleteHash(&ptr->MsgNumbers);
188 //      FreeStrBuf(&ptr->rooms);
189         FreeStrBuf(&ptr->pop3user);
190         FreeStrBuf(&ptr->pop3pass);
191         FreeStrBuf(&ptr->RoomName);
192         FreeURL(&ptr->IO.ConnectMe);
193         FreeStrBuf(&ptr->Url);
194         FreeStrBuf(&ptr->IO.IOBuf);
195         FreeStrBuf(&ptr->IO.SendBuf.Buf);
196         FreeStrBuf(&ptr->IO.RecvBuf.Buf);
197         DeleteAsyncMsg(&ptr->IO.ReadMsg);
198         ((struct CitContext*)ptr->IO.CitContext)->state = CON_IDLE;
199         ((struct CitContext*)ptr->IO.CitContext)->kill_me = 1;
200         FreeAsyncIOContents(&ptr->IO);
201         free(ptr);
202 }
203
204 eNextState FinalizePOP3AggrRun(AsyncIO *IO)
205 {
206         HashPos  *It;
207         pop3aggr *cpptr = (pop3aggr *)IO->Data;
208
209         EVP3C_syslog(LOG_INFO,
210                      "%s@%s: fetched %ld new of %d messages in %fs. bye.",
211                      ChrPtr(cpptr->pop3user),
212                      ChrPtr(cpptr->pop3pass),
213                      cpptr->count,
214                      GetCount(cpptr->MsgNumbers), 
215                      IO->Now - cpptr->IOStart 
216                 );
217
218         It = GetNewHashPos(POP3FetchUrls, 0);
219         pthread_mutex_lock(&POP3QueueMutex);
220         {
221                 if (GetHashPosFromKey(POP3FetchUrls, SKEY(cpptr->Url), It))
222                         DeleteEntryFromHash(POP3FetchUrls, It);
223         }
224         pthread_mutex_unlock(&POP3QueueMutex);
225         DeleteHashPos(&It);
226         return eAbort;
227 }
228
229 eNextState FailAggregationRun(AsyncIO *IO)
230 {
231         return eAbort;
232 }
233
234 eNextState POP3C_ReadGreeting(pop3aggr *RecvMsg)
235 {
236         AsyncIO *IO = &RecvMsg->IO;
237         POP3C_DBG_READ();
238         /* Read the server greeting */
239         if (!POP3C_OK) return eTerminateConnection;
240         else return eSendReply;
241 }
242
243 eNextState POP3C_SendUser(pop3aggr *RecvMsg)
244 {
245         AsyncIO *IO = &RecvMsg->IO;
246         /* Identify ourselves.  NOTE: we have to append a CR to each command.
247          *  The LF will automatically be appended by sock_puts().  Believe it
248          * or not, leaving out the CR will cause problems if the server happens
249          * to be Exchange, which is so b0rken it actually barfs on
250          * LF-terminated newlines.
251          */
252         StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
253                      "USER %s\r\n", ChrPtr(RecvMsg->pop3user));
254         POP3C_DBG_SEND();
255         return eReadMessage;
256 }
257
258 eNextState POP3C_GetUserState(pop3aggr *RecvMsg)
259 {
260         AsyncIO *IO = &RecvMsg->IO;
261         POP3C_DBG_READ();
262         if (!POP3C_OK) return eTerminateConnection;
263         else return eSendReply;
264 }
265
266 eNextState POP3C_SendPassword(pop3aggr *RecvMsg)
267 {
268         AsyncIO *IO = &RecvMsg->IO;
269         /* Password */
270         StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
271                      "PASS %s\r\n", ChrPtr(RecvMsg->pop3pass));
272         EVP3CM_syslog(LOG_DEBUG, "<PASS <password>\n");
273 //      POP3C_DBG_SEND(); No, we won't write the passvoid to syslog...
274         return eReadMessage;
275 }
276
277 eNextState POP3C_GetPassState(pop3aggr *RecvMsg)
278 {
279         AsyncIO *IO = &RecvMsg->IO;
280         POP3C_DBG_READ();
281         if (!POP3C_OK) return eTerminateConnection;
282         else return eSendReply;
283 }
284
285 eNextState POP3C_SendListCommand(pop3aggr *RecvMsg)
286 {
287         AsyncIO *IO = &RecvMsg->IO;
288         /* Get the list of messages */
289         StrBufPlain(RecvMsg->IO.SendBuf.Buf, HKEY("LIST\r\n"));
290         POP3C_DBG_SEND();
291         return eReadMessage;
292 }
293
294 eNextState POP3C_GetListCommandState(pop3aggr *RecvMsg)
295 {
296         AsyncIO *IO = &RecvMsg->IO;
297         POP3C_DBG_READ();
298         if (!POP3C_OK) return eTerminateConnection;
299         RecvMsg->MsgNumbers = NewHash(1, NULL);
300         RecvMsg->State++;
301         return eReadMore;
302 }
303
304
305 eNextState POP3C_GetListOneLine(pop3aggr *RecvMsg)
306 {
307         AsyncIO *IO = &RecvMsg->IO;
308 #if 0
309         int rc;
310 #endif
311         const char *pch;
312         FetchItem *OneMsg = NULL;
313         POP3C_DBG_READ();
314
315         if ((StrLength(RecvMsg->IO.IOBuf) == 1) &&
316             (ChrPtr(RecvMsg->IO.IOBuf)[0] == '.'))
317         {
318                 if (GetCount(RecvMsg->MsgNumbers) == 0)
319                 {
320                         ////    RecvMsg->Sate = ReadQuitState;
321                 }
322                 else
323                 {
324                         RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
325                 }
326                 return eSendReply;
327
328         }
329         OneMsg = (FetchItem*) malloc(sizeof(FetchItem));
330         memset(OneMsg, 0, sizeof(FetchItem));
331         OneMsg->MSGID = atol(ChrPtr(RecvMsg->IO.IOBuf));
332
333         pch = strchr(ChrPtr(RecvMsg->IO.IOBuf), ' ');
334         if (pch != NULL)
335         {
336                 OneMsg->MSGSize = atol(pch + 1);
337         }
338 #if 0
339         rc = TestValidateHash(RecvMsg->MsgNumbers);
340         if (rc != 0)
341                 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
342 #endif
343
344         Put(RecvMsg->MsgNumbers, LKEY(OneMsg->MSGID), OneMsg, HfreeFetchItem);
345 #if 0
346         rc = TestValidateHash(RecvMsg->MsgNumbers);
347         if (rc != 0)
348                 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
349 #endif
350         //RecvMsg->State --; /* read next Line */
351         return eReadMore;
352 }
353
354 eNextState POP3_FetchNetworkUsetableEntry(AsyncIO *IO)
355 {
356         long HKLen;
357         const char *HKey;
358         void *vData;
359         struct cdbdata *cdbut;
360         pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
361
362         if(GetNextHashPos(RecvMsg->MsgNumbers,
363                           RecvMsg->Pos,
364                           &HKLen,
365                           &HKey,
366                           &vData))
367         {
368                 struct UseTable ut;
369                 if (server_shutting_down)
370                         return eAbort;
371
372                 RecvMsg->CurrMsg = (FetchItem*) vData;
373                 EVP3CCS_syslog(LOG_DEBUG,
374                                "CHECKING: whether %s has already been seen: ",
375                                ChrPtr(RecvMsg->CurrMsg->MsgUID));
376
377                 /* Find out if we've already seen this item */
378                 safestrncpy(ut.ut_msgid,
379                             ChrPtr(RecvMsg->CurrMsg->MsgUID),
380                             sizeof(ut.ut_msgid));
381                 ut.ut_timestamp = time(NULL);/// TODO: libev timestamp!
382
383                 cdbut = cdb_fetch(CDB_USETABLE, SKEY(RecvMsg->CurrMsg->MsgUID));
384                 if (cdbut != NULL) {
385                         /* Item has already been seen */
386                         EVP3CCSM_syslog(LOG_DEBUG, "YES\n");
387                         cdb_free(cdbut);
388
389                         /* rewrite the record anyway, to update the timestamp */
390                         cdb_store(CDB_USETABLE,
391                                   SKEY(RecvMsg->CurrMsg->MsgUID),
392                                   &ut, sizeof(struct UseTable) );
393                         RecvMsg->CurrMsg->NeedFetch = 0; ////TODO0;
394                 }
395                 else
396                 {
397                         EVP3CCSM_syslog(LOG_DEBUG, "NO\n");
398                         RecvMsg->CurrMsg->NeedFetch = 1;
399                 }
400                 return NextDBOperation(&RecvMsg->IO,
401                                        POP3_FetchNetworkUsetableEntry);
402         }
403         else
404         {
405                 /* ok, now we know them all,
406                  * continue with reading the actual messages. */
407                 DeleteHashPos(&RecvMsg->Pos);
408                 StopDBWatchers(IO);
409                 return QueueEventContext(IO, POP3_C_ReAttachToFetchMessages);
410         }
411 }
412
413 eNextState POP3C_GetOneMessagID(pop3aggr *RecvMsg)
414 {
415         AsyncIO *IO = &RecvMsg->IO;
416         long HKLen;
417         const char *HKey;
418         void *vData;
419
420 #if 0
421         int rc;
422         rc = TestValidateHash(RecvMsg->MsgNumbers);
423         if (rc != 0)
424                 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
425 #endif
426         if(GetNextHashPos(RecvMsg->MsgNumbers,
427                           RecvMsg->Pos,
428                           &HKLen, &HKey,
429                           &vData))
430         {
431                 RecvMsg->CurrMsg = (FetchItem*) vData;
432                 /* Find out the UIDL of the message,
433                  * to determine whether we've already downloaded it */
434                 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
435                              "UIDL %ld\r\n", RecvMsg->CurrMsg->MSGID);
436                 POP3C_DBG_SEND();
437         }
438         else
439         {
440             RecvMsg->State++;
441                 DeleteHashPos(&RecvMsg->Pos);
442                 /// done receiving uidls.. start looking them up now.
443                 RecvMsg->Pos = GetNewHashPos(RecvMsg->MsgNumbers, 0);
444                 return QueueDBOperation(&RecvMsg->IO,
445                                         POP3_FetchNetworkUsetableEntry);
446         }
447         return eReadMore; /* TODO */
448 }
449
450 eNextState POP3C_GetOneMessageIDState(pop3aggr *RecvMsg)
451 {
452         AsyncIO *IO = &RecvMsg->IO;
453 #if 0
454         int rc;
455         rc = TestValidateHash(RecvMsg->MsgNumbers);
456         if (rc != 0)
457                 EVP3CCS_syslog(LOG_DEBUG, "Hash Invalid: %d\n", rc);
458 #endif
459
460         POP3C_DBG_READ();
461         if (!POP3C_OK) return eTerminateConnection;
462         RecvMsg->CurrMsg->MsgUIDL =
463                 NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf));
464         RecvMsg->CurrMsg->MsgUID =
465                 NewStrBufPlain(NULL, StrLength(RecvMsg->IO.IOBuf) * 2);
466
467         StrBufExtract_token(RecvMsg->CurrMsg->MsgUIDL,
468                             RecvMsg->IO.IOBuf, 2, ' ');
469
470         StrBufPrintf(RecvMsg->CurrMsg->MsgUID,
471                      "pop3/%s/%s:%s@%s",
472                      ChrPtr(RecvMsg->RoomName),
473                      ChrPtr(RecvMsg->CurrMsg->MsgUIDL),
474                      RecvMsg->IO.ConnectMe->User,
475                      RecvMsg->IO.ConnectMe->Host);
476         RecvMsg->State --;
477         return eSendReply;
478 }
479
480
481 eNextState POP3C_SendGetOneMsg(pop3aggr *RecvMsg)
482 {
483         AsyncIO *IO = &RecvMsg->IO;
484         long HKLen;
485         const char *HKey;
486         void *vData;
487
488         RecvMsg->CurrMsg = NULL;
489         while (GetNextHashPos(RecvMsg->MsgNumbers,
490                               RecvMsg->Pos,
491                               &HKLen, &HKey,
492                               &vData) &&
493                (RecvMsg->CurrMsg = (FetchItem*) vData,
494                 RecvMsg->CurrMsg->NeedFetch == 0))
495         {}
496
497         if ((RecvMsg->CurrMsg != NULL ) && (RecvMsg->CurrMsg->NeedFetch == 1))
498         {
499                 /* Message has not been seen.
500                  * Tell the server to fetch the message... */
501                 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
502                              "RETR %ld\r\n", RecvMsg->CurrMsg->MSGID);
503                 POP3C_DBG_SEND();
504                 return eReadMessage;
505         }
506         else {
507                 RecvMsg->State = ReadQuitState;
508                 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
509         }
510 }
511
512
513 eNextState POP3C_ReadMessageBodyFollowing(pop3aggr *RecvMsg)
514 {
515         AsyncIO *IO = &RecvMsg->IO;
516         POP3C_DBG_READ();
517         if (!POP3C_OK) return eTerminateConnection;
518         RecvMsg->IO.ReadMsg = NewAsyncMsg(HKEY("."),
519                                           RecvMsg->CurrMsg->MSGSize,
520                                           config.c_maxmsglen,
521                                           NULL, -1,
522                                           1);
523
524         return eReadPayload;
525 }
526
527
528 eNextState POP3C_StoreMsgRead(AsyncIO *IO)
529 {
530         pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
531         struct UseTable ut;
532
533         EVP3CCS_syslog(LOG_DEBUG,
534                        "MARKING: %s as seen: ",
535                        ChrPtr(RecvMsg->CurrMsg->MsgUID));
536
537         safestrncpy(ut.ut_msgid,
538                     ChrPtr(RecvMsg->CurrMsg->MsgUID),
539                     sizeof(ut.ut_msgid));
540         ut.ut_timestamp = time(NULL); /* TODO: use libev time */
541         cdb_store(CDB_USETABLE,
542                   ChrPtr(RecvMsg->CurrMsg->MsgUID),
543                   StrLength(RecvMsg->CurrMsg->MsgUID),
544                   &ut,
545                   sizeof(struct UseTable) );
546         StopDBWatchers(IO);
547         return QueueEventContext(&RecvMsg->IO, POP3_C_ReAttachToFetchMessages);
548 }
549 eNextState POP3C_SaveMsg(AsyncIO *IO)
550 {
551         long msgnum;
552         pop3aggr *RecvMsg = (pop3aggr *) IO->Data;
553
554         /* Do Something With It (tm) */
555         msgnum = CtdlSubmitMsg(RecvMsg->CurrMsg->Msg,
556                                NULL,
557                                ChrPtr(RecvMsg->RoomName),
558                                0);
559         if (msgnum > 0L)
560         {
561                 /* Message has been committed to the store
562                  * write the uidl to the use table
563                  * so we don't fetch this message again
564                  */
565         }
566         CtdlFreeMessage(RecvMsg->CurrMsg->Msg);
567
568         RecvMsg->count ++;
569         return NextDBOperation(&RecvMsg->IO, POP3C_StoreMsgRead);
570 }
571
572 eNextState POP3C_ReadMessageBody(pop3aggr *RecvMsg)
573 {
574         AsyncIO *IO = &RecvMsg->IO;
575         EVP3CM_syslog(LOG_DEBUG, "Converting message...");
576         RecvMsg->CurrMsg->Msg =
577                 convert_internet_message_buf(&RecvMsg->IO.ReadMsg->MsgBuf);
578         StopClientWatchers(IO, 0);
579         return QueueDBOperation(&RecvMsg->IO, POP3C_SaveMsg);
580 }
581
582 eNextState POP3C_SendDelete(pop3aggr *RecvMsg)
583 {
584         AsyncIO *IO = &RecvMsg->IO;
585         if (!RecvMsg->keep) {
586                 StrBufPrintf(RecvMsg->IO.SendBuf.Buf,
587                              "DELE %ld\r\n", RecvMsg->CurrMsg->MSGID);
588                 POP3C_DBG_SEND();
589                 return eReadMessage;
590         }
591         else {
592                 RecvMsg->State = ReadMessageBodyFollowing;
593                 return POP3_C_DispatchWriteDone(&RecvMsg->IO);
594         }
595 }
596 eNextState POP3C_ReadDeleteState(pop3aggr *RecvMsg)
597 {
598         AsyncIO *IO = &RecvMsg->IO;
599         POP3C_DBG_READ();
600         RecvMsg->State = GetOneMessageIDState;
601         return eReadMessage;
602 }
603
604 eNextState POP3C_SendQuit(pop3aggr *RecvMsg)
605 {
606         AsyncIO *IO = &RecvMsg->IO;
607         /* Log out */
608         StrBufPlain(RecvMsg->IO.SendBuf.Buf,
609                     HKEY("QUIT\r\n3)"));
610         POP3C_DBG_SEND();
611         return eReadMessage;
612 }
613
614
615 eNextState POP3C_ReadQuitState(pop3aggr *RecvMsg)
616 {
617         AsyncIO *IO = &RecvMsg->IO;
618         POP3C_DBG_READ();
619         return eTerminateConnection;
620 }
621
622 const long POP3_C_ConnTimeout = 1000;
623 const long DefaultPOP3Port = 110;
624
625 Pop3ClientHandler POP3C_ReadHandlers[] = {
626         POP3C_ReadGreeting,
627         POP3C_GetUserState,
628         POP3C_GetPassState,
629         POP3C_GetListCommandState,
630         POP3C_GetListOneLine,
631         POP3C_GetOneMessageIDState,
632         POP3C_ReadMessageBodyFollowing,
633         POP3C_ReadMessageBody,
634         POP3C_ReadDeleteState,
635         POP3C_ReadQuitState,
636 };
637
638 const long POP3_C_SendTimeouts[POP3C_MaxRead] = {
639         100,
640         100,
641         100,
642         100,
643         100,
644         100,
645         100,
646         100
647 };
648 const ConstStr POP3C_ReadErrors[POP3C_MaxRead] = {
649         {HKEY("Connection broken during ")},
650         {HKEY("Connection broken during ")},
651         {HKEY("Connection broken during ")},
652         {HKEY("Connection broken during ")},
653         {HKEY("Connection broken during ")},
654         {HKEY("Connection broken during ")},
655         {HKEY("Connection broken during ")},
656         {HKEY("Connection broken during ")}
657 };
658
659 Pop3ClientHandler POP3C_SendHandlers[] = {
660         NULL, /* we don't send a greeting */
661         POP3C_SendUser,
662         POP3C_SendPassword,
663         POP3C_SendListCommand,
664         NULL,
665         POP3C_GetOneMessagID,
666         POP3C_SendGetOneMsg,
667         NULL,
668         POP3C_SendDelete,
669         POP3C_SendQuit
670 };
671
672 const long POP3_C_ReadTimeouts[] = {
673         100,
674         100,
675         100,
676         100,
677         100,
678         100,
679         100,
680         100,
681         100,
682         100
683 };
684 /*****************************************************************************/
685 /*                     POP3 CLIENT DISPATCHER                                */
686 /*****************************************************************************/
687
688 void POP3SetTimeout(eNextState NextTCPState, pop3aggr *pMsg)
689 {
690         AsyncIO *IO = &pMsg->IO;
691         double Timeout = 0.0;
692
693         EVP3C_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
694
695         switch (NextTCPState) {
696         case eSendFile:
697         case eSendReply:
698         case eSendMore:
699                 Timeout = POP3_C_SendTimeouts[pMsg->State];
700 /*
701   if (pMsg->State == eDATABody) {
702   / * if we're sending a huge message, we need more time. * /
703   Timeout += StrLength(pMsg->msgtext) / 1024;
704   }
705 */
706                 break;
707         case eReadFile:
708         case eReadMessage:
709                 Timeout = POP3_C_ReadTimeouts[pMsg->State];
710 /*
711   if (pMsg->State == eDATATerminateBody) {
712   / *
713   * some mailservers take a nap before accepting the message
714   * content inspection and such.
715   * /
716   Timeout += StrLength(pMsg->msgtext) / 1024;
717   }
718 */
719                 break;
720         case eReadPayload:
721                 Timeout = 100000;
722                 /* TODO!!! */
723                 break;
724         case eSendDNSQuery:
725         case eReadDNSReply:
726         case eConnect:
727         case eTerminateConnection:
728         case eDBQuery:
729         case eAbort:
730         case eReadMore://// TODO
731                 return;
732         }
733         SetNextTimeout(&pMsg->IO, Timeout);
734 }
735 eNextState POP3_C_DispatchReadDone(AsyncIO *IO)
736 {
737 /*      EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
738         pop3aggr *pMsg = IO->Data;
739         eNextState rc;
740
741         rc = POP3C_ReadHandlers[pMsg->State](pMsg);
742         if (rc != eReadMore)
743             pMsg->State++;
744         POP3SetTimeout(rc, pMsg);
745         return rc;
746 }
747 eNextState POP3_C_DispatchWriteDone(AsyncIO *IO)
748 {
749         pop3aggr *pMsg = IO->Data;
750         eNextState rc;
751
752 /*      EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__); to noisy anyways. */
753         rc = POP3C_SendHandlers[pMsg->State](pMsg);
754         POP3SetTimeout(rc, pMsg);
755         return rc;
756 }
757
758
759 /*****************************************************************************/
760 /*                     POP3 CLIENT ERROR CATCHERS                            */
761 /*****************************************************************************/
762 eNextState POP3_C_Terminate(AsyncIO *IO)
763 {
764 ///     pop3aggr *pMsg = (pop3aggr *)IO->Data;
765
766         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
767         FinalizePOP3AggrRun(IO);
768         return eAbort;
769 }
770 eNextState POP3_C_TerminateDB(AsyncIO *IO)
771 {
772 ///     pop3aggr *pMsg = (pop3aggr *)IO->Data;
773
774         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
775         FinalizePOP3AggrRun(IO);
776         return eAbort;
777 }
778 eNextState POP3_C_Timeout(AsyncIO *IO)
779 {
780         pop3aggr *pMsg = IO->Data;
781
782         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
783         StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
784         return FailAggregationRun(IO);
785 }
786 eNextState POP3_C_ConnFail(AsyncIO *IO)
787 {
788         pop3aggr *pMsg = (pop3aggr *)IO->Data;
789
790         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
791         StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
792         return FailAggregationRun(IO);
793 }
794 eNextState POP3_C_DNSFail(AsyncIO *IO)
795 {
796         pop3aggr *pMsg = (pop3aggr *)IO->Data;
797
798         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
799         StrBufPlain(IO->ErrMsg, CKEY(POP3C_ReadErrors[pMsg->State]));
800         return FailAggregationRun(IO);
801 }
802 eNextState POP3_C_Shutdown(AsyncIO *IO)
803 {
804         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
805 ////    pop3aggr *pMsg = IO->Data;
806
807 ////pMsg->MyQEntry->Status = 3;
808 ///StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message retrieval."));
809         FinalizePOP3AggrRun(IO);
810         return eAbort;
811 }
812
813
814 /**
815  * @brief lineread Handler; understands when to read more POP3 lines,
816  *   and when this is a one-lined reply.
817  */
818 eReadState POP3_C_ReadServerStatus(AsyncIO *IO)
819 {
820         eReadState Finished = eBufferNotEmpty;
821
822         switch (IO->NextState) {
823         case eSendDNSQuery:
824         case eReadDNSReply:
825         case eDBQuery:
826         case eConnect:
827         case eTerminateConnection:
828         case eAbort:
829                 Finished = eReadFail;
830                 break;
831         case eSendFile:
832         case eSendReply:
833         case eSendMore:
834         case eReadMore:
835         case eReadMessage:
836                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
837                 break;
838         case eReadFile:
839         case eReadPayload:
840                 Finished = CtdlReadMessageBodyAsync(IO);
841                 break;
842         }
843         return Finished;
844 }
845
846 /*****************************************************************************
847  * So we connect our Server IP here.                                         *
848  *****************************************************************************/
849 eNextState POP3_C_ReAttachToFetchMessages(AsyncIO *IO)
850 {
851         pop3aggr *cpptr = IO->Data;
852
853         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
854 ////??? cpptr->State ++;
855         if (cpptr->Pos == NULL)
856                 cpptr->Pos = GetNewHashPos(cpptr->MsgNumbers, 0);
857
858         POP3_C_DispatchWriteDone(IO);
859         ReAttachIO(IO, cpptr, 0);
860         IO->NextState = eReadMessage;
861         return IO->NextState;
862 }
863
864 eNextState pop3_connect_ip(AsyncIO *IO)
865 {
866         pop3aggr *cpptr = IO->Data;
867
868         if (cpptr->IOStart == 0.0) /* whith or without DNS? */
869                 cpptr->IOStart = IO->Now;
870
871         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
872
873         return EvConnectSock(IO,
874                              POP3_C_ConnTimeout,
875                              POP3_C_ReadTimeouts[0],
876                              1);
877 }
878
879 eNextState pop3_get_one_host_ip_done(AsyncIO *IO)
880 {
881         pop3aggr *cpptr = IO->Data;
882         struct hostent *hostent;
883
884         QueryCbDone(IO);
885
886         hostent = cpptr->HostLookup.VParsedDNSReply;
887         if ((cpptr->HostLookup.DNSStatus == ARES_SUCCESS) && 
888             (hostent != NULL) ) {
889                 memset(&cpptr->IO.ConnectMe->Addr, 0, sizeof(struct in6_addr));
890                 if (cpptr->IO.ConnectMe->IPv6) {
891                         memcpy(&cpptr->IO.ConnectMe->Addr.sin6_addr.s6_addr, 
892                                &hostent->h_addr_list[0],
893                                sizeof(struct in6_addr));
894
895                         cpptr->IO.ConnectMe->Addr.sin6_family =
896                                 hostent->h_addrtype;
897                         cpptr->IO.ConnectMe->Addr.sin6_port   =
898                                 htons(DefaultPOP3Port);
899                 }
900                 else {
901                         struct sockaddr_in *addr =
902                                 (struct sockaddr_in*)
903                                 &cpptr->IO.ConnectMe->Addr;
904
905                         memcpy(&addr->sin_addr.s_addr,
906                                hostent->h_addr_list[0],
907                                sizeof(uint32_t));
908
909                         addr->sin_family = hostent->h_addrtype;
910                         addr->sin_port   = htons(DefaultPOP3Port);
911                 }
912                 return pop3_connect_ip(IO);
913         }
914         else
915                 return eAbort;
916 }
917
918 eNextState pop3_get_one_host_ip(AsyncIO *IO)
919 {
920         pop3aggr *cpptr = IO->Data;
921
922         cpptr->IOStart = IO->Now;
923
924         EVP3CCS_syslog(LOG_DEBUG, "POP3: %s\n", __FUNCTION__);
925
926         EVP3CCS_syslog(LOG_DEBUG, 
927                        "POP3 client[%ld]: looking up %s-Record %s : %d ...\n",
928                        cpptr->n,
929                        (cpptr->IO.ConnectMe->IPv6)? "aaaa": "a",
930                        cpptr->IO.ConnectMe->Host,
931                        cpptr->IO.ConnectMe->Port);
932
933         QueueQuery((cpptr->IO.ConnectMe->IPv6)? ns_t_aaaa : ns_t_a,
934                    cpptr->IO.ConnectMe->Host,
935                    &cpptr->IO,
936                    &cpptr->HostLookup,
937                    pop3_get_one_host_ip_done);
938         IO->NextState = eReadDNSReply;
939         return IO->NextState;
940 }
941
942
943
944 int pop3_do_fetching(pop3aggr *cpptr)
945 {
946         AsyncIO *IO = &cpptr->IO;
947
948         InitIOStruct(IO,
949                      cpptr,
950                      eReadMessage,
951                      POP3_C_ReadServerStatus,
952                      POP3_C_DNSFail,
953                      POP3_C_DispatchWriteDone,
954                      POP3_C_DispatchReadDone,
955                      POP3_C_Terminate,
956                      POP3_C_TerminateDB,
957                      POP3_C_ConnFail,
958                      POP3_C_Timeout,
959                      POP3_C_Shutdown);
960
961         safestrncpy(((CitContext *)cpptr->IO.CitContext)->cs_host,
962                     ChrPtr(cpptr->Url),
963                     sizeof(((CitContext *)cpptr->IO.CitContext)->cs_host));
964
965         if (cpptr->IO.ConnectMe->IsIP) {
966                 QueueEventContext(&cpptr->IO,
967                                   pop3_connect_ip);
968         }
969         else {
970                 QueueEventContext(&cpptr->IO,
971                                   pop3_get_one_host_ip);
972         }
973         return 1;
974 }
975
976 /*
977  * Scan a room's netconfig to determine whether it requires POP3 aggregation
978  */
979 void pop3client_scan_room(struct ctdlroom *qrbuf, void *data)
980 {
981         StrBuf *CfgData;
982         StrBuf *CfgType;
983         StrBuf *Line;
984
985         struct stat statbuf;
986         char filename[PATH_MAX];
987         int  fd;
988         int Done;
989         void *vptr;
990         const char *CfgPtr, *lPtr;
991         const char *Err;
992
993 //      pop3_room_counter *Count = NULL;
994 //      pop3aggr *cpptr;
995
996         pthread_mutex_lock(&POP3QueueMutex);
997         if (GetHash(POP3QueueRooms, LKEY(qrbuf->QRnumber), &vptr))
998         {
999                 pthread_mutex_unlock(&POP3QueueMutex);
1000                 EVP3CQ_syslog(LOG_DEBUG,
1001                               "pop3client: [%ld] %s already in progress.",
1002                               qrbuf->QRnumber,
1003                               qrbuf->QRname);
1004                 return;
1005         }
1006         pthread_mutex_unlock(&POP3QueueMutex);
1007
1008         if (server_shutting_down) return;
1009
1010         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
1011
1012         if (server_shutting_down)
1013                 return;
1014
1015         /* Only do net processing for rooms that have netconfigs */
1016         fd = open(filename, 0);
1017         if (fd <= 0) {
1018                 return;
1019         }
1020         if (server_shutting_down)
1021                 return;
1022         if (fstat(fd, &statbuf) == -1) {
1023                 EVP3CQ_syslog(LOG_INFO,
1024                               "ERROR: could not stat configfile '%s' - %s",
1025                               filename,
1026                               strerror(errno));
1027                 return;
1028         }
1029         if (server_shutting_down)
1030                 return;
1031         CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
1032         if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
1033                 close(fd);
1034                 FreeStrBuf(&CfgData);
1035                 EVP3CQ_syslog(LOG_INFO,
1036                               "ERROR: reading config '%s' - %s",
1037                               filename, strerror(errno));
1038                 return;
1039         }
1040         close(fd);
1041         if (server_shutting_down)
1042                 return;
1043
1044         CfgPtr = NULL;
1045         CfgType = NewStrBuf();
1046         Line = NewStrBufPlain(NULL, StrLength(CfgData));
1047         Done = 0;
1048
1049         while (!Done)
1050         {
1051                 Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
1052                 if (StrLength(Line) > 0)
1053                 {
1054                         lPtr = NULL;
1055                         StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
1056                         if (!strcasecmp("pop3client", ChrPtr(CfgType)))
1057                         {
1058                                 pop3aggr *cptr;
1059                                 StrBuf *Tmp;
1060 /*
1061                                 if (Count == NULL)
1062                                 {
1063                                 Count = malloc(sizeof(pop3_room_counter));
1064                                         Count->count = 0;
1065                                 }
1066                                 Count->count ++;
1067 */
1068                                 cptr = (pop3aggr *) malloc(sizeof(pop3aggr));
1069                                 memset(cptr, 0, sizeof(pop3aggr));
1070                                 ///TODO do we need this? cptr->roomlist_parts=1;
1071                                 cptr->RoomName =
1072                                         NewStrBufPlain(qrbuf->QRname, -1);
1073                                 cptr->pop3user =
1074                                         NewStrBufPlain(NULL, StrLength(Line));
1075                                 cptr->pop3pass =
1076                                         NewStrBufPlain(NULL, StrLength(Line));
1077                                 cptr->Url = NewStrBuf();
1078                                 Tmp = NewStrBuf();
1079
1080                                 StrBufExtract_NextToken(Tmp, Line, &lPtr, '|');
1081                                 StrBufExtract_NextToken(cptr->pop3user,
1082                                                         Line,
1083                                                         &lPtr,
1084                                                         '|');
1085
1086                                 StrBufExtract_NextToken(cptr->pop3pass,
1087                                                         Line,
1088                                                         &lPtr,
1089                                                         '|');
1090
1091                                 cptr->keep = StrBufExtractNext_long(Line,
1092                                                                     &lPtr,
1093                                                                     '|');
1094
1095                                 cptr->interval = StrBufExtractNext_long(Line,
1096                                                                         &lPtr,
1097                                                                         '|');
1098
1099                                 StrBufAppendBufPlain(cptr->Url, HKEY("pop3://"), 0);
1100                                 StrBufUrlescUPAppend(cptr->Url, cptr->pop3user, NULL);
1101                                 StrBufAppendBufPlain(cptr->Url, HKEY(":"), 0);
1102                                 StrBufUrlescUPAppend(cptr->Url, cptr->pop3pass, NULL);
1103                                 StrBufAppendBufPlain(cptr->Url, HKEY("@"), 0);
1104                                 StrBufAppendBuf(cptr->Url, Tmp, 0);
1105                                 StrBufAppendBufPlain(cptr->Url, HKEY("/"), 0);
1106                                 StrBufUrlescAppend(cptr->Url, cptr->RoomName, NULL);
1107
1108                                 FreeStrBuf(&Tmp);
1109                                 ParseURL(&cptr->IO.ConnectMe, cptr->Url, 110);
1110
1111
1112 #if 0
1113 /* todo: we need to reunite the url to be shure. */
1114
1115                                 pthread_mutex_lock(&POP3ueueMutex);
1116                                 GetHash(POP3FetchUrls, SKEY(ptr->Url), &vptr);
1117                                 use_this_cptr = (pop3aggr *)vptr;
1118
1119                                 if (use_this_rncptr != NULL)
1120                                 {
1121                                         /* mustn't attach to an active session */
1122                                         if (use_this_cptr->RefCount > 0)
1123                                         {
1124                                                 DeletePOP3Cfg(cptr);
1125 ///                                             Count->count--;
1126                                         }
1127                                         else
1128                                         {
1129                                                 long *QRnumber;
1130                                                 StrBufAppendBufPlain(
1131                                                         use_this_cptr->rooms,
1132                                                         qrbuf->QRname,
1133                                                         -1, 0);
1134                                                 if (use_this_cptr->roomlist_parts == 1)
1135                                                 {
1136                                                         use_this_cptr->OtherQRnumbers
1137                                                                 = NewHash(1, lFlathash);
1138                                                 }
1139                                                 QRnumber = (long*)malloc(sizeof(long));
1140                                                 *QRnumber = qrbuf->QRnumber;
1141                                                 Put(use_this_cptr->OtherQRnumbers,
1142                                                     LKEY(qrbuf->QRnumber),
1143                                                     QRnumber,
1144                                                     NULL);
1145
1146                                                 use_this_cptr->roomlist_parts++;
1147                                         }
1148                                         pthread_mutex_unlock(&POP3QueueMutex);
1149                                         continue;
1150                                 }
1151                                 pthread_mutex_unlock(&RSSQueueMutex);
1152 #endif
1153                                 cptr->n = Pop3ClientID++;
1154                                 pthread_mutex_lock(&POP3QueueMutex);
1155                                 Put(POP3FetchUrls,
1156                                     SKEY(cptr->Url),
1157                                     cptr,
1158                                     DeletePOP3Aggregator);
1159
1160                                 pthread_mutex_unlock(&POP3QueueMutex);
1161
1162                         }
1163
1164                 }
1165
1166                 ///fclose(fp);
1167
1168         }
1169         FreeStrBuf(&Line);
1170         FreeStrBuf(&CfgType);
1171         FreeStrBuf(&CfgData);
1172 }
1173
1174 static int doing_pop3client = 0;
1175
1176 void pop3client_scan(void) {
1177         static time_t last_run = 0L;
1178         time_t fastest_scan;
1179         HashPos *it;
1180         long len;
1181         const char *Key;
1182         void *vrptr;
1183         pop3aggr *cptr;
1184
1185         become_session(&pop3_client_CC);
1186
1187         if (config.c_pop3_fastest < config.c_pop3_fetch)
1188                 fastest_scan = config.c_pop3_fastest;
1189         else
1190                 fastest_scan = config.c_pop3_fetch;
1191
1192         /*
1193          * Run POP3 aggregation no more frequently than once every n seconds
1194          */
1195         if ( (time(NULL) - last_run) < fastest_scan ) {
1196                 return;
1197         }
1198
1199         /*
1200          * This is a simple concurrency check to make sure only one pop3client
1201          * run is done at a time.  We could do this with a mutex, but since we
1202          * don't really require extremely fine granularity here, we'll do it
1203          * with a static variable instead.
1204          */
1205         if (doing_pop3client) return;
1206         doing_pop3client = 1;
1207
1208         EVP3CQM_syslog(LOG_DEBUG, "pop3client started");
1209         CtdlForEachRoom(pop3client_scan_room, NULL);
1210
1211         pthread_mutex_lock(&POP3QueueMutex);
1212         it = GetNewHashPos(POP3FetchUrls, 0);
1213         while (!server_shutting_down &&
1214                GetNextHashPos(POP3FetchUrls, it, &len, &Key, &vrptr) &&
1215                (vrptr != NULL)) {
1216                 cptr = (pop3aggr *)vrptr;
1217                 if (cptr->RefCount == 0)
1218                         if (!pop3_do_fetching(cptr))
1219                                 DeletePOP3Aggregator(cptr);////TODO
1220
1221 /*
1222         if ((palist->interval && time(NULL) > (last_run + palist->interval))
1223                         || (time(NULL) > last_run + config.c_pop3_fetch))
1224                         pop3_do_fetching(palist->roomname, palist->pop3host,
1225                         palist->pop3user, palist->pop3pass, palist->keep);
1226                 pptr = palist;
1227                 palist = palist->next;
1228                 free(pptr);
1229 */
1230         }
1231         DeleteHashPos(&it);
1232         pthread_mutex_unlock(&POP3QueueMutex);
1233
1234         EVP3CQM_syslog(LOG_DEBUG, "pop3client ended");
1235         last_run = time(NULL);
1236         doing_pop3client = 0;
1237 }
1238
1239
1240 void pop3_cleanup(void)
1241 {
1242         /* citthread_mutex_destroy(&POP3QueueMutex); TODO */
1243         while (doing_pop3client != 0) ;
1244         DeleteHash(&POP3FetchUrls);
1245         DeleteHash(&POP3QueueRooms);
1246 }
1247
1248
1249
1250 void LogDebugEnablePOP3Client(const int n)
1251 {
1252         POP3ClientDebugEnabled = n;
1253 }
1254
1255 CTDL_MODULE_INIT(pop3client)
1256 {
1257         if (!threading)
1258         {
1259                 CtdlFillSystemContext(&pop3_client_CC, "POP3aggr");
1260                 pthread_mutex_init(&POP3QueueMutex, NULL);
1261                 POP3QueueRooms = NewHash(1, lFlathash);
1262                 POP3FetchUrls = NewHash(1, NULL);
1263                 CtdlRegisterSessionHook(pop3client_scan, EVT_TIMER, PRIO_AGGR + 50);
1264                 CtdlRegisterEVCleanupHook(pop3_cleanup);
1265                 CtdlRegisterDebugFlagHook(HKEY("pop3client"), LogDebugEnablePOP3Client, &POP3ClientDebugEnabled);
1266         }
1267
1268         /* return our module id for the log */
1269         return "pop3client";
1270 }