]> Pileus Git - ~andy/fetchmail/blob - pop3.c
Fix IMAP password shrouding.
[~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 1997.
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 the newsaved list */
335     for( num = first_nr; num < list_len; num++ )
336     {
337         struct idlist   *new = save_str(&ctl->newsaved, 
338                                 str_from_nr_list(&ctl->oldsaved, num),
339                                 UID_UNSEEN);
340         new->val.status.num = num - first_nr + 1;
341     }
342
343     if( nolinear ) {
344         free_str_list(&ctl->oldsaved);
345         ctl->oldsaved = 0;
346         last = try_id;
347     }
348
349     *newp = *countp - try_id;
350     return 0;
351 }
352
353 static int pop3_getrange(int sock, 
354                          struct query *ctl,
355                          const char *folder,
356                          int *countp, int *newp)
357 /* get range of messages to be fetched */
358 {
359     int ok;
360     char buf [POPBUFSIZE+1];
361
362     phase = PHASE_GETRANGE;
363
364     /* Ensure that the new list is properly empty */
365     ctl->newsaved = (struct idlist *)NULL;
366
367 #ifdef MBOX
368     /* Alain Knaff suggests this, but it's not RFC standard */
369     if (folder)
370         if ((ok = gen_transact(sock, "MBOX %s", folder)))
371             return ok;
372 #endif /* MBOX */
373
374     /* get the total message count */
375     gen_send(sock, "STAT");
376     ok = pop3_ok(sock, buf);
377     if (ok == 0)
378         sscanf(buf,"%d %*d", countp);
379     else
380         return(ok);
381
382     /*
383      * Newer, RFC-1725-conformant POP servers may not have the LAST command.
384      * We work as hard as possible to hide this ugliness, but it makes 
385      * counting new messages intrinsically quadratic in the worst case.
386      */
387     last = 0;
388     *newp = -1;
389     if (*countp > 0 && !ctl->fetchall)
390     {
391         char id [IDLEN+1];
392
393         if (!ctl->server.uidl) {
394             gen_send(sock, "LAST");
395             ok = pop3_ok(sock, buf);
396         } else
397             ok = 1;
398         if (ok == 0)
399         {
400             if (sscanf(buf, "%d", &last) == 0)
401             {
402                 error(0, 0, "protocol error");
403                 return(PS_ERROR);
404             }
405             *newp = (*countp - last);
406         }
407         else
408         {
409             /* grab the mailbox's UID list */
410             if ((ok = gen_transact(sock, "UIDL")) != 0)
411             {
412                 /* don't worry, yet! do it the slow way */
413                 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
414                 {
415                     error(0, 0, "protocol error while fetching UIDLs");
416                     return(PS_ERROR);
417                 }
418             }
419             else
420             {
421                 int     num;
422
423                 *newp = 0;
424                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
425                 {
426                     if (buf[0] == '.')
427                         break;
428                     else if (sscanf(buf, "%d %s", &num, id) == 2)
429                     {
430                         struct idlist   *new;
431
432                         new = save_str(&ctl->newsaved, id, UID_UNSEEN);
433                         new->val.status.num = num;
434
435                         /* note: ID comparison is caseblind */
436                         if (str_in_list(&ctl->oldsaved, id)) {
437                             new->val.status.mark = UID_SEEN;
438                             str_set_mark(&ctl->oldsaved, id, UID_SEEN);
439                         }
440                         else
441                             (*newp)++;
442                     }
443                 }
444             }
445         }
446     }
447
448     return(0);
449 }
450
451 static int pop3_getsizes(int sock, int count, int *sizes)
452 /* capture the sizes of all messages */
453 {
454     int ok;
455
456     /* phase = PHASE_GETSIZES */
457
458     if ((ok = gen_transact(sock, "LIST")) != 0)
459         return(ok);
460     else
461     {
462         char buf [POPBUFSIZE+1];
463
464         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
465         {
466             int num, size;
467
468             if (buf[0] == '.')
469                 break;
470             else if (sscanf(buf, "%d %d", &num, &size) == 2)
471                 sizes[num - 1] = size;
472         }
473
474         return(ok);
475     }
476 }
477
478 static int pop3_is_old(int sock, struct query *ctl, int num)
479 /* is the given message old? */
480 {
481     if (!ctl->oldsaved)
482         return (num <= last);
483     else
484         /* note: ID comparison is caseblind */
485         return (str_in_list(&ctl->oldsaved,
486                             str_find (&ctl->newsaved, num)));
487 }
488
489 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
490 /* request nth message */
491 {
492     int ok;
493     char buf [POPBUFSIZE+1];
494
495     /* phase = PHASE_FETCH */
496
497     gen_send(sock, "RETR %d", number);
498     if ((ok = pop3_ok(sock, buf)) != 0)
499         return(ok);
500
501     *lenp = -1;         /* we got sizes from the LIST response */
502
503     return(0);
504 }
505
506 static int pop3_delete(int sock, struct query *ctl, int number)
507 /* delete a given message */
508 {
509     /* actually, mark for deletion -- doesn't happen until QUIT time */
510     return(gen_transact(sock, "DELE %d", number));
511 }
512
513 static int pop3_logout(int sock, struct query *ctl)
514 /* send logout command */
515 {
516     int ok;
517
518     /* phase = PHASE_LOGOUT */
519
520     ok = gen_transact(sock, "QUIT");
521     if (!ok)
522         expunge_uids(ctl);
523
524     return(ok);
525 }
526
527 const static struct method pop3 =
528 {
529     "POP3",             /* Post Office Protocol v3 */
530 #if INET6
531     "pop3",             /* standard POP3 port */
532 #else /* INET6 */
533     110,                /* standard POP3 port */
534 #endif /* INET6 */
535     FALSE,              /* this is not a tagged protocol */
536     TRUE,               /* this uses a message delimiter */
537     pop3_ok,            /* parse command response */
538     NULL,               /* no password canonicalization */
539     pop3_getauth,       /* get authorization */
540     pop3_getrange,      /* query range of messages */
541     pop3_getsizes,      /* we can get a list of sizes */
542     pop3_is_old,        /* how do we tell a message is old? */
543     pop3_fetch,         /* request given message */
544     NULL,               /* no way to fetch body alone */
545     NULL,               /* no message trailer */
546     pop3_delete,        /* how to delete a message */
547     pop3_logout,        /* log out, we're done */
548     FALSE,              /* no, we can't re-poll */
549 };
550
551 int doPOP3 (struct query *ctl)
552 /* retrieve messages using POP3 */
553 {
554 #ifndef MBOX
555     if (ctl->mailboxes->id) {
556         fprintf(stderr,"Option --remote is not supported with POP3\n");
557         return(PS_SYNTAX);
558     }
559 #endif /* MBOX */
560     peek_capable = FALSE;
561     return(do_protocol(ctl, &pop3));
562 }
563 #endif /* POP3_ENABLE */
564
565 /* pop3.c ends here */