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