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