]> Pileus Git - ~andy/fetchmail/blob - pop3.c
Re-enable OPIE build.
[~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_opts.poll_interval == -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 peek-capable if use of TOP is enabled */
238     peek_capable = !(ctl->fetchall || ctl->keep);
239
240     /* we're approved */
241     return(PS_SUCCESS);
242 }
243
244 static int
245 pop3_gettopid( int sock, int num , char *id)
246 {
247     int ok;
248     int got_it;
249     char buf [POPBUFSIZE+1];
250     sprintf( buf, "TOP %d 1", num );
251     if( (ok = gen_transact(sock, buf ) ) != 0 )
252        return ok; 
253     got_it = 0;
254     while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
255         if( buf[0] == '.' )
256             break;
257         if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
258             got_it = 1;
259             /* prevent stack overflows */
260             buf[IDLEN+12] = 0;
261             sscanf( buf+12, "%s", id);
262         }
263     }
264     return 0;
265 }
266
267 static int
268 pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
269 {
270     /* This approach tries to get the message headers from the
271      * remote hosts and compares the message-id to the already known
272      * ones:
273      *  + if the first message containes a new id, all messages on
274      *    the server will be new
275      *  + if the first is known, try to estimate the last known message
276      *    on the server and check. If this works you know the total number
277      *    of messages to get.
278      *  + Otherwise run a binary search to determine the last known message
279      */
280     int ok, nolinear = 0;
281     int first_nr, list_len, try_id, try_nr, add_id;
282     int num;
283     char id [IDLEN+1];
284     
285     if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
286         return ok;
287     
288     if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
289         /* the first message is unknown -> all messages are new */
290         *newp = *countp;        
291         return 0;
292     }
293
294     /* check where we expect the latest known message */
295     list_len = count_list( &ctl->oldsaved );
296     try_id = list_len  - first_nr; /* -1 + 1 */
297     if( try_id > 1 ) {
298         if( try_id <= *countp ) {
299             if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
300                 return ok;
301     
302             try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
303         } else {
304             try_id = *countp+1;
305             try_nr = -1;
306         }
307         if( try_nr != list_len -1 ) {
308             /* some messages inbetween have been deleted... */
309             if( try_nr == -1 ) {
310                 nolinear = 1;
311
312                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
313                     ;
314                 for( ; add_id; add_id >>= 1 ) {
315                     if( try_nr == -1 ) {
316                         if( try_id - add_id <= 1 ) {
317                             continue;
318                         }
319                         try_id -= add_id;
320                     } else 
321                         try_id += add_id;
322                     
323                     if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
324                         return ok;
325                     try_nr = str_nr_in_list(&ctl->oldsaved, id);
326                 }
327                 if( try_nr == -1 ) {
328                     try_id--;
329                 }
330             } else {
331                 error(0,0,"Messages inserted into list on server. "
332                       "Cannot handle this.");
333                 return -1;
334             }
335         } 
336     }
337     /* the first try_id messages are known -> copy them to the newsaved list */
338     for( num = first_nr; num < list_len; num++ )
339     {
340         struct idlist   *new = save_str(&ctl->newsaved, 
341                                 str_from_nr_list(&ctl->oldsaved, num),
342                                 UID_UNSEEN);
343         new->val.status.num = num - first_nr + 1;
344     }
345
346     if( nolinear ) {
347         free_str_list(&ctl->oldsaved);
348         ctl->oldsaved = 0;
349         last = try_id;
350     }
351
352     *newp = *countp - try_id;
353     return 0;
354 }
355
356 static int pop3_getrange(int sock, 
357                          struct query *ctl,
358                          const char *folder,
359                          int *countp, int *newp, int *bytes)
360 /* get range of messages to be fetched */
361 {
362     int ok;
363     char buf [POPBUFSIZE+1];
364
365     phase = PHASE_GETRANGE;
366
367     /* Ensure that the new list is properly empty */
368     ctl->newsaved = (struct idlist *)NULL;
369
370 #ifdef MBOX
371     /* Alain Knaff suggests this, but it's not RFC standard */
372     if (folder)
373         if ((ok = gen_transact(sock, "MBOX %s", folder)))
374             return ok;
375 #endif /* MBOX */
376
377     /* get the total message count */
378     gen_send(sock, "STAT");
379     ok = pop3_ok(sock, buf);
380     if (ok == 0)
381         sscanf(buf,"%d %d", countp, bytes);
382     else
383         return(ok);
384
385     /*
386      * Newer, RFC-1725-conformant POP servers may not have the LAST command.
387      * We work as hard as possible to hide this ugliness, but it makes 
388      * counting new messages intrinsically quadratic in the worst case.
389      */
390     last = 0;
391     *newp = -1;
392     if (*countp > 0 && !ctl->fetchall)
393     {
394         char id [IDLEN+1];
395
396         if (!ctl->server.uidl) {
397             gen_send(sock, "LAST");
398             ok = pop3_ok(sock, buf);
399         } else
400             ok = 1;
401         if (ok == 0)
402         {
403             if (sscanf(buf, "%d", &last) == 0)
404             {
405                 error(0, 0, "protocol error");
406                 return(PS_ERROR);
407             }
408             *newp = (*countp - last);
409         }
410         else
411         {
412             /* grab the mailbox's UID list */
413             if ((ok = gen_transact(sock, "UIDL")) != 0)
414             {
415                 /* don't worry, yet! do it the slow way */
416                 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
417                 {
418                     error(0, 0, "protocol error while fetching UIDLs");
419                     return(PS_ERROR);
420                 }
421             }
422             else
423             {
424                 int     num;
425
426                 *newp = 0;
427                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
428                 {
429                     if (buf[0] == '.')
430                         break;
431                     else if (sscanf(buf, "%d %s", &num, id) == 2)
432                     {
433                         struct idlist   *new;
434
435                         new = save_str(&ctl->newsaved, id, UID_UNSEEN);
436                         new->val.status.num = num;
437
438                         if (str_in_list(&ctl->oldsaved, id, FALSE)) {
439                             new->val.status.mark = UID_SEEN;
440                             str_set_mark(&ctl->oldsaved, id, UID_SEEN);
441                         }
442                         else
443                             (*newp)++;
444                     }
445                 }
446             }
447         }
448     }
449
450     return(PS_SUCCESS);
451 }
452
453 static int pop3_getsizes(int sock, int count, int *sizes)
454 /* capture the sizes of all messages */
455 {
456     int ok;
457
458     /* phase = PHASE_GETSIZES */
459
460     if ((ok = gen_transact(sock, "LIST")) != 0)
461         return(ok);
462     else
463     {
464         char buf [POPBUFSIZE+1];
465
466         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
467         {
468             int num, size;
469
470             if (buf[0] == '.')
471                 break;
472             else if (sscanf(buf, "%d %d", &num, &size) == 2)
473                 sizes[num - 1] = size;
474         }
475
476         return(ok);
477     }
478 }
479
480 static int pop3_is_old(int sock, struct query *ctl, int num)
481 /* is the given message old? */
482 {
483     if (!ctl->oldsaved)
484         return (num <= last);
485     else
486         return (str_in_list(&ctl->oldsaved,
487                             str_find(&ctl->newsaved, num), FALSE));
488 }
489
490 #ifdef UNUSED
491 /*
492  * We could use this to fetch headers only as we do for IMAP.  The trouble 
493  * is that there's no way to fetch the body only.  So the following RETR 
494  * would have to re-fetch the header.  Enough messages have longer headers
495  * than bodies to make this a net loss.
496  */
497 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
498 /* request headers of nth message */
499 {
500     int ok;
501     char buf[POPBUFSIZE+1];
502
503     /* phase = PHASE_FETCH */
504
505     gen_send(sock, "TOP %d 0", number);
506     if ((ok = pop3_ok(sock, buf)) != 0)
507         return(ok);
508
509     *lenp = -1;         /* we got sizes from the LIST response */
510
511     return(PS_SUCCESS);
512 }
513 #endif /* UNUSED */
514
515 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
516 /* request nth message */
517 {
518     int ok;
519     char buf[POPBUFSIZE+1];
520
521     /* phase = PHASE_FETCH */
522
523     /*
524      * Though the POP RFCs don't document this fact, on every POP3 server
525      * I know of messages are marked "seen" only at the time the OK
526      * response to a RETR is issued.
527      *
528      * This means we can use TOP to fetch the message without setting its
529      * seen flag.  This is good!  It means that if the protocol exchange
530      * craps out during the message, it will still be marked `unseen' on
531      * the server.
532      *
533      * However...*don't* do this if we're using keep to suppress deletion!
534      * In that case, marking the seen flag is the only way to prevent the
535      * message from being re-fetched on subsequent runs.
536      *
537      * Also use RETR if fetchall is on.  This gives us a workaround
538      * for servers like usa.net's that bungle TOP.  It's pretty
539      * harmless because fetchall guarantees that any message dropped
540      * by an interrupted RETR will be picked up on the next poll of the
541      * site.
542      *
543      * We take advantage here of the fact that, according to all the
544      * POP RFCs, "if the number of lines requested by the POP3 client
545      * is greater than than the number of lines in the body, then the
546      * POP3 server sends the entire message.").
547      *
548      * The line count passed (99999999) is the maximum value CompuServe will
549      * accept; it's much lower than the natural value 2147483646 (the maximum
550      * twos-complement signed 32-bit integer minus 1)
551      */
552     if (ctl->keep || ctl->fetchall)
553         gen_send(sock, "RETR %d", number);
554     else
555         gen_send(sock, "TOP %d 99999999", number);
556     if ((ok = pop3_ok(sock, buf)) != 0)
557         return(ok);
558
559     *lenp = -1;         /* we got sizes from the LIST response */
560
561     return(PS_SUCCESS);
562 }
563
564 static int pop3_delete(int sock, struct query *ctl, int number)
565 /* delete a given message */
566 {
567     /* actually, mark for deletion -- doesn't happen until QUIT time */
568     return(gen_transact(sock, "DELE %d", number));
569 }
570
571 static int pop3_logout(int sock, struct query *ctl)
572 /* send logout command */
573 {
574     int ok;
575
576     /* phase = PHASE_LOGOUT */
577
578     ok = gen_transact(sock, "QUIT");
579     if (!ok)
580         expunge_uids(ctl);
581
582     return(ok);
583 }
584
585 const static struct method pop3 =
586 {
587     "POP3",             /* Post Office Protocol v3 */
588 #if INET6
589     "pop3",             /* standard POP3 port */
590 #else /* INET6 */
591     110,                /* standard POP3 port */
592 #endif /* INET6 */
593     FALSE,              /* this is not a tagged protocol */
594     TRUE,               /* this uses a message delimiter */
595     pop3_ok,            /* parse command response */
596     NULL,               /* no password canonicalization */
597     pop3_getauth,       /* get authorization */
598     pop3_getrange,      /* query range of messages */
599     pop3_getsizes,      /* we can get a list of sizes */
600     pop3_is_old,        /* how do we tell a message is old? */
601     pop3_fetch,         /* request given message */
602     NULL,               /* no way to fetch body alone */
603     NULL,               /* no message trailer */
604     pop3_delete,        /* how to delete a message */
605     pop3_logout,        /* log out, we're done */
606     FALSE,              /* no, we can't re-poll */
607 };
608
609 int doPOP3 (struct query *ctl)
610 /* retrieve messages using POP3 */
611 {
612 #ifndef MBOX
613     if (ctl->mailboxes->id) {
614         fprintf(stderr,"Option --remote is not supported with POP3\n");
615         return(PS_SYNTAX);
616     }
617 #endif /* MBOX */
618     peek_capable = FALSE;
619     return(do_protocol(ctl, &pop3));
620 }
621 #endif /* POP3_ENABLE */
622
623 /* pop3.c ends here */