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