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