]> Pileus Git - ~andy/fetchmail/blob - pop3.c
More robust message size queries
[~andy/fetchmail] / pop3.c
1 /*
2  * pop3.c -- POP3 protocol methods
3  *
4  * For license terms, see the file COPYING in this directory.
5  */
6
7 #include  "config.h"
8
9 #include  <stdio.h>
10 #include  <string.h>
11 #include  <ctype.h>
12 #if defined(HAVE_UNISTD_H)
13 #include <unistd.h>
14 #endif
15 #if defined(STDC_HEADERS)
16 #include  <stdlib.h>
17 #endif
18  
19 #include  "fetchmail.h"
20 #include  "socket.h"
21
22 #if HAVE_LIBOPIE
23 #include  <opie.h>
24 #endif /* HAVE_LIBOPIE */
25
26 extern char *strstr();  /* needed on sysV68 R3V7.1. */
27
28 static int last;
29
30 #if HAVE_LIBOPIE
31 static char lastok[POPBUFSIZE+1];
32 #endif /* HAVE_LIBOPIE */
33
34 int pop3_ok (int sock, char *argbuf)
35 /* parse command response */
36 {
37     int ok;
38     char buf [POPBUFSIZE+1];
39     char *bufp;
40
41     if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
42     {
43         bufp = buf;
44         if (*bufp == '+' || *bufp == '-')
45             bufp++;
46         else
47             return(PS_PROTOCOL);
48
49         while (isalpha(*bufp))
50             bufp++;
51
52         if (*bufp)
53           *(bufp++) = '\0';
54
55         if (strcmp(buf,"+OK") == 0)
56         {
57 #if HAVE_LIBOPIE
58             strcpy(lastok, bufp);
59 #endif /* HAVE_LIBOPIE */
60             ok = 0;
61         }
62         else if (strcmp(buf,"-ERR") == 0)
63         {
64             /*
65              * We're checking for "lock busy", "unable to lock", 
66              * "already locked" etc. here.  This indicates that we
67              * have to wait for the server to clean up before we
68              * can poll again.
69              *
70              * PS_LOCKBUSY check empirically verified with two recent
71              * versions the Berkeley popper;    QPOP (version 2.2)  and
72              * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
73              */
74             if (strstr(bufp,"lock")||strstr(bufp,"Lock")||strstr(bufp,"LOCK"))
75                 ok = PS_LOCKBUSY;
76             else
77                 ok = PS_AUTHFAIL;
78             if (*bufp)
79               error(0,0,bufp);
80         }
81         else
82             ok = PS_PROTOCOL;
83
84         if (argbuf != NULL)
85             strcpy(argbuf,bufp);
86     }
87
88     return(ok);
89 }
90
91 int pop3_getauth(int sock, struct query *ctl, char *greeting)
92 /* apply for connection authorization */
93 {
94     int ok;
95     char *start,*end;
96     char *msg;
97 #if HAVE_LIBOPIE
98     char *challenge;
99 #endif /* HAVE_LIBOPIE */
100
101     switch (ctl->server.protocol) {
102     case P_POP3:
103         if ((ok = gen_transact(sock, "USER %s", ctl->remotename)) != 0)
104             break;
105
106 #if defined(HAVE_LIBOPIE) && defined(OPIE_ENABLE)
107         /* see RFC1938: A One-Time Password System */
108         if (challenge = strstr(greeting, "otp-"))
109         {
110             char response[OPIE_RESPONSE_MAX+1];
111
112             if (opiegenerator(challenge, ctl->password, response))
113             {
114                 ok = PS_ERROR;
115                 break;
116             }
117
118             ok = gen_transact(sock, "PASS %s", response);
119             break;
120         }
121 #endif /* defined(HAVE_LIBOPIE) && defined(OPIE_ENABLE) */
122
123 #ifdef ENABLE_RPA
124         /* if we're talking to CompuServe, try RPA */
125         if (strstr(greeting, "csi.com"))
126         {
127             /* AUTH command should return a list of available mechanisms */
128             if (gen_transact(sock, "AUTH") == 0)
129             {
130                 char buffer[10];
131                 flag authenticated = FALSE;
132
133                 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
134                 {
135                     if (buffer[0] == '.')
136                         break;
137                     if (strncasecmp(buffer, "rpa", 3) == 0)
138                     {
139                         if (POP3_auth_rpa(ctl->remotename,
140                                           ctl->password, sock) == PS_SUCCEED)
141                         {
142                             authenticated = TRUE;
143                             break;
144                         }
145                     }
146                 }
147
148                 if (authenticated)
149                     break;
150             }
151         }
152 #endif /* ENABLE_RPA */
153
154         /* ordinary validation, no one-time password or RPA */ 
155         ok = gen_transact(sock, "PASS %s", ctl->password);
156         break;
157
158     case P_APOP:
159         /* build MD5 digest from greeting timestamp + password */
160         /* find start of timestamp */
161         for (start = greeting;  *start != 0 && *start != '<';  start++)
162             continue;
163         if (*start == 0) {
164             error(0, -1, "Required APOP timestamp not found in greeting");
165             return(PS_AUTHFAIL);
166         }
167
168         /* find end of timestamp */
169         for (end = start;  *end != 0  && *end != '>';  end++)
170             continue;
171         if (*end == 0 || end == start + 1) {
172             error(0, -1, "Timestamp syntax error in greeting");
173             return(PS_AUTHFAIL);
174         }
175         else
176             *++end = '\0';
177
178         /* copy timestamp and password into digestion buffer */
179         msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
180         strcpy(msg,start);
181         strcat(msg,ctl->password);
182
183         strcpy(ctl->digest, MD5Digest(msg));
184         free(msg);
185
186         ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
187         break;
188
189     case P_RPOP:
190         if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
191             ok = gen_transact(sock, "RPOP %s", ctl->password);
192         break;
193
194     default:
195         error(0, 0, "Undefined protocol request in POP3_auth");
196         ok = PS_ERROR;
197     }
198
199     /* maybe we detected a lock-busy condition? */
200     if (ok != 0)
201     {
202         if (ok == PS_LOCKBUSY)
203         {
204             error(0, 0, "lock busy!  Is another session active?"); 
205             return(PS_LOCKBUSY);
206         }
207     }
208
209     /*
210      * Empirical experience shows some server/OS combinations
211      * may need a brief pause even after any lockfiles on the
212      * server are released, to give the server time to finish
213      * copying back very large mailfolders from the temp-file...
214      * this is only ever an issue with extremely large mailboxes.
215      */
216     sleep(3); /* to be _really_ safe, probably need sleep(5)! */
217
218     /* we're approved */
219     return(0);
220 }
221
222 static int
223 pop3_gettopid( int sock, int num , char *id)
224 {
225     int ok;
226     int got_it;
227     char buf [POPBUFSIZE+1];
228     sprintf( buf, "TOP %d 1", num );
229     if( (ok = gen_transact(sock, buf ) ) != 0 )
230        return ok; 
231     got_it = 0;
232     while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
233         if( buf[0] == '.' )
234             break;
235         if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
236             got_it = 1;
237             sscanf( buf+12, "%s", id);
238         }
239     }
240     return 0;
241 }
242
243 static int
244 pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
245 {
246     /* This approach tries to get the message headers from the
247      * remote hosts and compares the message-id to the already known
248      * ones:
249      *  + if the first message containes a new id, all messages on
250      *    the server will be new
251      *  + if the first is known, try to estimate the last known message
252      *    on the server and check. If this works you know the total number
253      *    of messages to get.
254      *  + Otherwise run a binary search to determine the last known message
255      */
256     int ok, nolinear = 0;
257     int first_nr, list_len, try_id, try_nr, hop_id, add_id;
258     int num;
259     char id [IDLEN+1];
260     
261     if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
262         return ok;
263     
264     if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
265         /* the first message is unknown -> all messages are new */
266         *newp = *countp;        
267         return 0;
268     }
269
270     /* check where we expect the latest known message */
271     list_len = count_list( &ctl->oldsaved );
272     try_id = list_len  - first_nr; /* -1 + 1 */
273     if( try_id > 1 ) {
274         if( try_id <= *countp ) {
275             if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
276                 return ok;
277     
278             try_nr = str_nr_in_list(&ctl->oldsaved, id);
279         } else {
280             try_id = *countp+1;
281             try_nr = -1;
282         }
283         if( try_nr != list_len -1 ) {
284             /* some messages inbetween have been deleted... */
285             if( try_nr == -1 ) {
286                 nolinear = 1;
287
288                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
289                     ;
290                 for( ; add_id; add_id >>= 1 ) {
291                     if( try_nr == -1 ) {
292                         if( try_id - add_id <= 1 ) {
293                             continue;
294                         }
295                         try_id -= add_id;
296                     } else 
297                         try_id += add_id;
298                     
299                     if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
300                         return ok;
301                     try_nr = str_nr_in_list(&ctl->oldsaved, id);
302                 }
303                 if( try_nr == -1 ) {
304                     try_id--;
305                 }
306             } else {
307                 error(0,0,"Messages inserted into list on server. "
308                       "Cannot handle this.");
309                 return -1;
310             }
311         } 
312     }
313     /* The first try_id messages are known -> copy them to
314        the newsaved list */
315     for( num = first_nr; num < list_len; num++ )
316         save_str(&ctl->newsaved, num-first_nr + 1,
317                  str_from_nr_list( &ctl->oldsaved, num ));
318
319     if( nolinear ) {
320         free_str_list(&ctl->oldsaved);
321         ctl->oldsaved = 0;
322         last = try_id;
323     }
324
325     *newp = *countp - try_id;
326     return 0;
327 }
328
329 static int pop3_getrange(int sock, 
330                          struct query *ctl,
331                          const char *folder,
332                          int *countp, int *newp)
333 /* get range of messages to be fetched */
334 {
335     int ok;
336     char buf [POPBUFSIZE+1];
337
338     /* Ensure that the new list is properly empty */
339     ctl->newsaved = (struct idlist *)NULL;
340
341 #ifdef MBOX
342     /* Alain Knaff suggests this, but it's not RFC standard */
343     if (folder)
344         if ((ok = gen_transact(sock, "MBOX %s", folder)))
345             return ok;
346 #endif /* MBOX */
347
348     /* get the total message count */
349     gen_send(sock, "STAT");
350     ok = pop3_ok(sock, buf);
351     if (ok == 0)
352         sscanf(buf,"%d %*d", countp);
353     else
354         return(ok);
355
356     /*
357      * Newer, RFC-1725-conformant POP servers may not have the LAST command.
358      * We work as hard as possible to hide this ugliness, but it makes 
359      * counting new messages intrinsically quadratic in the worst case.
360      */
361     last = 0;
362     *newp = -1;
363     if (*countp > 0 && !ctl->fetchall)
364     {
365         char id [IDLEN+1];
366
367         if (!ctl->server.uidl) {
368             gen_send(sock, "LAST");
369             ok = pop3_ok(sock, buf);
370         } else
371             ok = 1;
372         if (ok == 0)
373         {
374             if (sscanf(buf, "%d", &last) == 0)
375             {
376                 error(0, 0, "protocol error");
377                 return(PS_ERROR);
378             }
379             *newp = (*countp - last);
380         }
381         else
382         {
383             /* grab the mailbox's UID list */
384             if ((ok = gen_transact(sock, "UIDL")) != 0)
385             {
386                 /* don't worry, yet! do it the slow way */
387                 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
388                 {
389                     error(0, 0, "protocol error while fetching UIDLs");
390                     return(PS_ERROR);
391                 }
392             }
393             else
394             {
395                 int     num;
396
397                 *newp = 0;
398                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
399                 {
400                     if (buf[0] == '.')
401                         break;
402                     else if (sscanf(buf, "%d %s", &num, id) == 2)
403                     {
404                         save_str(&ctl->newsaved, num, id);
405
406                         /* note: ID comparison is caseblind */
407                         if (!str_in_list(&ctl->oldsaved, id))
408                             (*newp)++;
409                     }
410                 }
411             }
412         }
413     }
414
415     return(0);
416 }
417
418 static int pop3_getsizes(int sock, int count, int *sizes)
419 /* capture the sizes of all messages */
420 {
421     int ok;
422
423     if ((ok = gen_transact(sock, "LIST")) != 0)
424         return(ok);
425     else
426     {
427         char buf [POPBUFSIZE+1];
428
429         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
430         {
431             int num, size;
432
433             if (buf[0] == '.')
434                 break;
435             else if (sscanf(buf, "%d %d", &num, &size) == 2)
436                 sizes[num - 1] = size;
437         }
438
439         return(ok);
440     }
441 }
442
443 static int pop3_is_old(int sock, struct query *ctl, int num)
444 /* is the given message old? */
445 {
446     if (!ctl->oldsaved)
447         return (num <= last);
448     else
449         /* note: ID comparison is caseblind */
450         return (str_in_list(&ctl->oldsaved,
451                             str_find (&ctl->newsaved, num)));
452 }
453
454 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
455 /* request nth message */
456 {
457     int ok;
458     char buf [POPBUFSIZE+1], *cp;
459
460     gen_send(sock, "RETR %d", number);
461     if ((ok = pop3_ok(sock, buf)) != 0)
462         return(ok);
463
464     *lenp = -1;         /* we got sizes from the LIST response */
465
466     return(0);
467 }
468
469 static int pop3_delete(int sock, struct query *ctl, int number)
470 /* delete a given message */
471 {
472     /* actually, mark for deletion -- doesn't happen until QUIT time */
473     return(gen_transact(sock, "DELE %d", number));
474 }
475
476 static int pop3_logout(int sock, struct query *ctl)
477 /* send logout command */
478 {
479     return(gen_transact(sock, "QUIT"));
480 }
481
482 const static struct method pop3 =
483 {
484     "POP3",             /* Post Office Protocol v3 */
485     110,                /* standard POP3 port */
486     FALSE,              /* this is not a tagged protocol */
487     TRUE,               /* this uses a message delimiter */
488     pop3_ok,            /* parse command response */
489     pop3_getauth,       /* get authorization */
490     pop3_getrange,      /* query range of messages */
491     pop3_getsizes,      /* we can get a list of sizes */
492     pop3_is_old,        /* how do we tell a message is old? */
493     pop3_fetch,         /* request given message */
494     NULL,               /* no way to fetch body alone */
495     NULL,               /* no message trailer */
496     pop3_delete,        /* how to delete a message */
497     pop3_logout,        /* log out, we're done */
498     FALSE,              /* no, we can't re-poll */
499 };
500
501 int doPOP3 (struct query *ctl)
502 /* retrieve messages using POP3 */
503 {
504 #ifndef MBOX
505     if (ctl->mailboxes->id) {
506         fprintf(stderr,"Option --remote is not supported with POP3\n");
507         return(PS_SYNTAX);
508     }
509 #endif /* MBOX */
510     peek_capable = FALSE;
511     return(do_protocol(ctl, &pop3));
512 }
513
514 /* pop3.c ends here */