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