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