4250cc446ac67486dcf95ca75573538d646b901c
[citadel.git] / citadel / modules / pop3client / serv_pop3client.c
1 /*
2  * $Id$
3  *
4  * Consolidate mail from remote POP3 accounts.
5  *
6  * Copyright (c) 2007-2009 by the citadel.org team
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 3 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <stdio.h>
26
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
29 # include <time.h>
30 #else
31 # if HAVE_SYS_TIME_H
32 #  include <sys/time.h>
33 # else
34 #  include <time.h>
35 # endif
36 #endif
37
38 #include <ctype.h>
39 #include <string.h>
40 #include <errno.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <libcitadel.h>
44 #include "citadel.h"
45 #include "server.h"
46 #include "citserver.h"
47 #include "support.h"
48 #include "config.h"
49 #include "ctdl_module.h"
50 #include "clientsocket.h"
51 #include "msgbase.h"
52 #include "internet_addressing.h"
53 #include "database.h"
54 #include "citadel_dirs.h"
55
56 struct pop3aggr {
57         struct pop3aggr *next;
58         char roomname[ROOMNAMELEN];
59         char pop3host[128];
60         char pop3user[128];
61         char pop3pass[128];
62         int keep;
63         time_t interval;
64 };
65
66 struct pop3aggr *palist = NULL;
67
68
69 void pop3_do_fetching(char *roomname, char *pop3host, char *pop3user, char *pop3pass, int keep)
70 {
71         int sock;
72         char buf[SIZ];
73         int msg_to_fetch = 0;
74         int *msglist = NULL;
75         int num_msgs = 0;
76         int alloc_msgs = 0;
77         int i;
78         char *body = NULL;
79         struct CtdlMessage *msg = NULL;
80         long msgnum = 0;
81         char this_uidl[64];
82         char utmsgid[SIZ];
83         struct cdbdata *cdbut;
84         struct UseTable ut;
85         CitContext *CCC=CC;
86
87         CtdlLogPrintf(CTDL_DEBUG, "POP3: %s %s %s <password>\n", roomname, pop3host, pop3user);
88         CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s>\n", pop3host);
89         
90         if (CtdlThreadCheckStop())
91                 return;
92                 
93         sock = sock_connect(pop3host, "110");
94         if (sock < 0) {
95                 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
96                 return;
97         }
98         
99         if (CtdlThreadCheckStop())
100                 goto bail;
101
102         CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
103         CCC->sReadBuf = NewStrBuf();
104         CCC->sMigrateBuf = NewStrBuf();
105         CCC->sPos = NULL;
106
107         /* Read the server greeting */
108         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
109         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
110         if (strncasecmp(buf, "+OK", 3)) goto bail;
111
112         if (CtdlThreadCheckStop())
113                 goto bail;
114
115         /* Identify ourselves.  NOTE: we have to append a CR to each command.  The LF will
116          * automatically be appended by sock_puts().  Believe it or not, leaving out the CR
117          * will cause problems if the server happens to be Exchange, which is so b0rken it
118          * actually barfs on LF-terminated newlines.
119          */
120         snprintf(buf, sizeof buf, "USER %s\r", pop3user);
121         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
122         if (sock_puts(&sock, buf) <0) goto bail;
123         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
124         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
125         if (strncasecmp(buf, "+OK", 3)) goto bail;
126
127         if (CtdlThreadCheckStop())
128                 goto bail;
129
130         /* Password */
131         snprintf(buf, sizeof buf, "PASS %s\r", pop3pass);
132         CtdlLogPrintf(CTDL_DEBUG, "<PASS <password>\n");
133         if (sock_puts(&sock, buf) <0) goto bail;
134         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
135         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
136         if (strncasecmp(buf, "+OK", 3)) goto bail;
137
138         if (CtdlThreadCheckStop())
139                 goto bail;
140
141         /* Get the list of messages */
142         snprintf(buf, sizeof buf, "LIST\r");
143         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
144         if (sock_puts(&sock, buf) <0) goto bail;
145         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
146         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
147         if (strncasecmp(buf, "+OK", 3)) goto bail;
148
149         if (CtdlThreadCheckStop())
150                 goto bail;
151
152         do {
153                 if (CtdlThreadCheckStop())
154                         goto bail;
155
156                 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
157                 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
158                 msg_to_fetch = atoi(buf);
159                 if (msg_to_fetch > 0) {
160                         if (alloc_msgs == 0) {
161                                 alloc_msgs = 100;
162                                 msglist = malloc((alloc_msgs * (sizeof(int))));
163                         }
164                         else if (num_msgs >= alloc_msgs) {
165                                 alloc_msgs = alloc_msgs * 2;
166                                 msglist = realloc(msglist, (alloc_msgs * sizeof(int)));
167                         }
168                         if (msglist == NULL) goto bail;
169                         msglist[num_msgs++] = msg_to_fetch;
170                 }
171         } while (buf[0] != '.');
172
173         if (num_msgs) for (i=0; i<num_msgs; ++i) {
174
175                 /* Find out the UIDL of the message, to determine whether we've already downloaded it */
176                 snprintf(buf, sizeof buf, "UIDL %d\r", msglist[i]);
177                 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
178                 if (sock_puts(&sock, buf) <0) goto bail;
179                 if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
180                 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
181                 if (strncasecmp(buf, "+OK", 3)) goto bail;
182                 extract_token(this_uidl, buf, 2, ' ', sizeof this_uidl);
183
184                 snprintf(utmsgid, sizeof utmsgid, "pop3/%s/%s@%s", roomname, this_uidl, pop3host);
185
186                 if (CtdlThreadCheckStop())
187                         goto bail;
188
189                 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
190                 if (cdbut != NULL) {
191                         /* message has already been seen */
192                         CtdlLogPrintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
193                         cdb_free(cdbut);
194
195                         /* rewrite the record anyway, to update the timestamp */
196                         strcpy(ut.ut_msgid, utmsgid);
197                         ut.ut_timestamp = time(NULL);
198                         cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
199                 }
200                 else {
201                         /* Message has not been seen. Tell the server to fetch the message... */
202                         snprintf(buf, sizeof buf, "RETR %d\r", msglist[i]);
203                         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
204                         if (sock_puts(&sock, buf) <0) goto bail;
205                         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
206                         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
207                         if (strncasecmp(buf, "+OK", 3)) goto bail;
208         
209                         if (CtdlThreadCheckStop())
210                                 goto bail;
211
212                         /* If we get to this point, the message is on its way.  Read it. */
213                         body = CtdlReadMessageBody(HKEY("."), config.c_maxmsglen, NULL, 1, &sock);
214                         if (body == NULL) goto bail;
215         
216                         CtdlLogPrintf(CTDL_DEBUG, "Converting message...\n");
217                         msg = convert_internet_message(body);
218                         body = NULL;    /* yes, this should be dereferenced, NOT freed */
219         
220                         /* Do Something With It (tm) */
221                         msgnum = CtdlSubmitMsg(msg, NULL, roomname, 0);
222                         if (msgnum > 0L) {
223                                 /* Message has been committed to the store */
224         
225                                 if (!keep) {
226                                         snprintf(buf, sizeof buf, "DELE %d\r", msglist[i]);
227                                         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
228                                         if (sock_puts(&sock, buf) <0) goto bail;
229                                         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
230                                         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf); /* errors here are non-fatal */
231                                 }
232
233                                 /* write the uidl to the use table so we don't fetch this message again */
234                                 strcpy(ut.ut_msgid, utmsgid);
235                                 ut.ut_timestamp = time(NULL);
236                                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid),
237                                                 &ut, sizeof(struct UseTable) );
238                         }
239                         CtdlFreeMessage(msg);
240                 }
241         }
242
243         /* Log out */
244         snprintf(buf, sizeof buf, "QUIT\r");
245         CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
246         if (sock_puts(&sock, buf) <0) goto bail;
247         if (sock_getln(&sock, buf, sizeof buf) < 0) goto bail;
248         CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
249 bail:   
250         FreeStrBuf(&CCC->sReadBuf);
251         FreeStrBuf(&CCC->sMigrateBuf);
252
253         if (sock != -1)
254                 sock_close(sock);
255         if (msglist) free(msglist);
256 }
257
258
259 /*
260  * Scan a room's netconfig to determine whether it requires POP3 aggregation
261  */
262 void pop3client_scan_room(struct ctdlroom *qrbuf, void *data)
263 {
264         char filename[PATH_MAX];
265         char buf[1024];
266         char instr[32];
267         FILE *fp;
268         struct pop3aggr *pptr;
269
270         if (CtdlThreadCheckStop())
271                 return;
272
273         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
274
275         /* Only do net processing for rooms that have netconfigs */
276         fp = fopen(filename, "r");
277         if (fp == NULL) {
278                 return;
279         }
280
281         while (fgets(buf, sizeof buf, fp) != NULL) {
282                 buf[strlen(buf)-1] = 0;
283
284                 extract_token(instr, buf, 0, '|', sizeof instr);
285                 if (!strcasecmp(instr, "pop3client")) {
286                         pptr = (struct pop3aggr *) malloc(sizeof(struct pop3aggr));
287                         if (pptr != NULL) {
288                                 safestrncpy(pptr->roomname, qrbuf->QRname, sizeof pptr->roomname);
289                                 extract_token(pptr->pop3host, buf, 1, '|', sizeof pptr->pop3host);
290                                 extract_token(pptr->pop3user, buf, 2, '|', sizeof pptr->pop3user);
291                                 extract_token(pptr->pop3pass, buf, 3, '|', sizeof pptr->pop3pass);
292                                 pptr->keep = extract_int(buf, 4);
293                                 pptr->interval = extract_long(buf, 5);
294                                 pptr->next = palist;
295                                 palist = pptr;
296                         }
297                 }
298
299         }
300
301         fclose(fp);
302
303 }
304
305
306 void pop3client_scan(void) {
307         static time_t last_run = 0L;
308         static int doing_pop3client = 0;
309         struct pop3aggr *pptr;
310         time_t fastest_scan;
311         CitContext popclientCC;
312
313         /* Give this thread its own private CitContext */
314         CtdlFillSystemContext(&popclientCC, "popclient");
315         citthread_setspecific(MyConKey, (void *)&popclientCC );
316
317         if (config.c_pop3_fastest < config.c_pop3_fetch)
318                 fastest_scan = config.c_pop3_fastest;
319         else
320                 fastest_scan = config.c_pop3_fetch;
321
322         /*
323          * Run POP3 aggregation no more frequently than once every n seconds
324          */
325         if ( (time(NULL) - last_run) < fastest_scan ) {
326                 return;
327         }
328
329         /*
330          * This is a simple concurrency check to make sure only one pop3client run
331          * is done at a time.  We could do this with a mutex, but since we
332          * don't really require extremely fine granularity here, we'll do it
333          * with a static variable instead.
334          */
335         if (doing_pop3client) return;
336         doing_pop3client = 1;
337
338         CtdlLogPrintf(CTDL_DEBUG, "pop3client started\n");
339         CtdlForEachRoom(pop3client_scan_room, NULL);
340
341         while (palist != NULL && !CtdlThreadCheckStop()) {
342                 if ((palist->interval && time(NULL) > (last_run + palist->interval))
343                         || (time(NULL) > last_run + config.c_pop3_fetch))
344                                 pop3_do_fetching(palist->roomname, palist->pop3host,
345                                         palist->pop3user, palist->pop3pass, palist->keep);
346                 pptr = palist;
347                 palist = palist->next;
348                 free(pptr);
349         }
350
351         CtdlLogPrintf(CTDL_DEBUG, "pop3client ended\n");
352         last_run = time(NULL);
353         doing_pop3client = 0;
354         CtdlClearSystemContext();
355 }
356
357
358 CTDL_MODULE_INIT(pop3client)
359 {
360         if (!threading)
361         {
362                 CtdlRegisterSessionHook(pop3client_scan, EVT_TIMER);
363         }
364         
365         /* return our Subversion id for the Log */
366         return "$Id$";
367 }