]> Pileus Git - ~andy/fetchmail/blob - pop3.c
9eae1441888758c9a2fee28872af495834552e47
[~andy/fetchmail] / pop3.c
1 /*
2  * pop3.c -- POP3 protocol methods
3  *
4  * Copyright 1998 by Eric S. Raymond.
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #ifdef POP3_ENABLE
10 #include  <stdio.h>
11 #include  <string.h>
12 #include  <ctype.h>
13 #if defined(HAVE_UNISTD_H)
14 #include <unistd.h>
15 #endif
16 #if defined(STDC_HEADERS)
17 #include  <stdlib.h>
18 #endif
19  
20 #include  "fetchmail.h"
21 #include  "socket.h"
22 #include  "i18n.h"
23
24 #if OPIE_ENABLE
25 #include <opie.h>
26 #endif /* OPIE_ENABLE */
27
28 #ifndef strstr          /* glibc-2.1 declares this as a macro */
29 extern char *strstr();  /* needed on sysV68 R3V7.1. */
30 #endif /* strstr */
31
32 static int last;
33 #ifdef SDPS_ENABLE
34 char *sdps_envfrom;
35 char *sdps_envto;
36 #endif /* SDPS_ENABLE */
37
38 #if OPIE_ENABLE
39 static char lastok[POPBUFSIZE+1];
40 #endif /* OPIE_ENABLE */
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_ENABLE
66             strcpy(lastok, bufp);
67 #endif /* OPIE_ENABLE */
68             ok = 0;
69         }
70         else if (strncmp(buf,"-ERR", 4) == 0)
71         {
72             if (stage > STAGE_GETAUTH) 
73                 ok = PS_PROTOCOL;
74             /*
75              * We're checking for "lock busy", "unable to lock", 
76              * "already locked", "wait a few minutes" etc. here. 
77              * This indicates that we have to wait for the server to
78              * unwedge itself before we can poll again.
79              *
80              * PS_LOCKBUSY check empirically verified with two recent
81              * versions of the Berkeley popper; QPOP (version 2.2)  and
82              * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
83              * These are caught by the case-indifferent "lock" check.
84              * The "wait" catches "mail storage services unavailable,
85              * wait a few minutes and try again" on the InterMail server.
86              *
87              * If these aren't picked up on correctly, fetchmail will 
88              * think there is an authentication failure and wedge the
89              * connection in order to prevent futile polls.
90              *
91              * Gad, what a kluge.
92              */
93             else if (strstr(bufp,"lock")
94                      || strstr(bufp,"Lock")
95                      || strstr(bufp,"LOCK")
96                      || strstr(bufp,"wait")
97                      /* these are blessed by RFC 2449 */
98                      || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
99                 ok = PS_LOCKBUSY;
100             else
101                 ok = PS_AUTHFAIL;
102             if (*bufp)
103               report(stderr, "%s\n", bufp);
104         }
105         else
106             ok = PS_PROTOCOL;
107
108         if (argbuf != NULL)
109             strcpy(argbuf,bufp);
110     }
111
112     return(ok);
113 }
114
115 int pop3_getauth(int sock, struct query *ctl, char *greeting)
116 /* apply for connection authorization */
117 {
118     int ok;
119     char *start,*end;
120     char *msg;
121 #if OPIE_ENABLE
122     char *challenge;
123 #endif /* OPIE_ENABLE */
124
125 #ifdef SDPS_ENABLE
126     /*
127      * This needs to catch both demon.co.uk and demon.net.
128      * If we see either, and we're in multidrop mode, try to use
129      * the SDPS *ENV extension.
130      */
131     if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
132         ctl->server.sdps = TRUE;
133 #endif /* SDPS_ENABLE */
134
135     /* 
136      * In theory, we ought to probe with CAPA here (RFC 2449).
137      * But AFAIK this commpand is not widely implemented, and
138      * we have our own tests for optional commands, and it seems
139      * vanishingly unlikely that the RFC 2449 extended responses
140      * [IN-USE] and [LOGIN-DELAY] will ever be accidentally spoofed.
141      * So we'll not bother, and save ourselves the overhead.
142      */
143
144     switch (ctl->server.protocol) {
145     case P_POP3:
146 #ifdef RPA_ENABLE
147         /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
148         if (strstr(ctl->remotename, "@compuserve.com"))
149         {
150             /* AUTH command should return a list of available mechanisms */
151             if (gen_transact(sock, "AUTH") == 0)
152             {
153                 char buffer[10];
154                 flag has_rpa = FALSE;
155
156                 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
157                 {
158                     if (buffer[0] == '.')
159                         break;
160                     if (strncasecmp(buffer, "rpa", 3) == 0)
161                         has_rpa = TRUE;
162                 }
163                 if (has_rpa && !POP3_auth_rpa(ctl->remotename, 
164                                               ctl->password, sock))
165                     return(PS_SUCCESS);
166             }
167
168             return(PS_AUTHFAIL);
169         }
170         else /* not a CompuServe account */
171 #endif /* RPA_ENABLE */
172             ok = gen_transact(sock, "USER %s", ctl->remotename);
173
174 #if OPIE_ENABLE
175         /* see RFC1938: A One-Time Password System */
176         if (challenge = strstr(lastok, "otp-")) {
177           char response[OPIE_RESPONSE_MAX+1];
178           int i;
179
180           i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
181           if ((i == -2) && !run.poll_interval) {
182             char secret[OPIE_SECRET_MAX+1];
183             fprintf(stderr, _("Secret pass phrase: "));
184             if (opiereadpass(secret, sizeof(secret), 0))
185               i = opiegenerator(challenge,  secret, response);
186             memset(secret, 0, sizeof(secret));
187           };
188
189           if (i) {
190             ok = PS_ERROR;
191             break;
192           };
193
194           ok = gen_transact(sock, "PASS %s", response);
195           break;
196         }
197 #endif /* OPIE_ENABLE */
198
199         /* ordinary validation, no one-time password or RPA */ 
200         ok = gen_transact(sock, "PASS %s", ctl->password);
201         break;
202
203     case P_APOP:
204         /* build MD5 digest from greeting timestamp + password */
205         /* find start of timestamp */
206         for (start = greeting;  *start != 0 && *start != '<';  start++)
207             continue;
208         if (*start == 0) {
209             report(stderr,
210                    _("Required APOP timestamp not found in greeting\n"));
211             return(PS_AUTHFAIL);
212         }
213
214         /* find end of timestamp */
215         for (end = start;  *end != 0  && *end != '>';  end++)
216             continue;
217         if (*end == 0 || end == start + 1) {
218             report(stderr, 
219                    _("Timestamp syntax error in greeting\n"));
220             return(PS_AUTHFAIL);
221         }
222         else
223             *++end = '\0';
224
225         /* copy timestamp and password into digestion buffer */
226         xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
227         strcpy(msg,start);
228         strcat(msg,ctl->password);
229
230         strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
231
232         ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
233         break;
234
235     case P_RPOP:
236         if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
237             ok = gen_transact(sock, "RPOP %s", ctl->password);
238         break;
239
240     default:
241         report(stderr, _("Undefined protocol request in POP3_auth\n"));
242         ok = PS_ERROR;
243     }
244
245     if (ok != 0)
246     {
247         /* maybe we detected a lock-busy condition? */
248         if (ok == PS_LOCKBUSY)
249             report(stderr, _("lock busy!  Is another session active?\n")); 
250
251         return(ok);
252     }
253
254     /*
255      * Empirical experience shows some server/OS combinations
256      * may need a brief pause even after any lockfiles on the
257      * server are released, to give the server time to finish
258      * copying back very large mailfolders from the temp-file...
259      * this is only ever an issue with extremely large mailboxes.
260      */
261     sleep(3); /* to be _really_ safe, probably need sleep(5)! */
262
263     /* we're peek-capable if use of TOP is enabled */
264     peek_capable = !(ctl->fetchall || ctl->keep);
265
266     /* we're approved */
267     return(PS_SUCCESS);
268 }
269
270 static int
271 pop3_gettopid( int sock, int num , char *id)
272 {
273     int ok;
274     int got_it;
275     char buf [POPBUFSIZE+1];
276     sprintf( buf, "TOP %d 1", num );
277     if( (ok = gen_transact(sock, buf ) ) != 0 )
278        return ok; 
279     got_it = 0;
280     while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
281         if( buf[0] == '.' )
282             break;
283         if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
284             got_it = 1;
285             /* prevent stack overflows */
286             buf[IDLEN+12] = 0;
287             sscanf( buf+12, "%s", id);
288         }
289     }
290     return 0;
291 }
292
293 static int
294 pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
295 {
296     /* This approach tries to get the message headers from the
297      * remote hosts and compares the message-id to the already known
298      * ones:
299      *  + if the first message containes a new id, all messages on
300      *    the server will be new
301      *  + if the first is known, try to estimate the last known message
302      *    on the server and check. If this works you know the total number
303      *    of messages to get.
304      *  + Otherwise run a binary search to determine the last known message
305      */
306     int ok, nolinear = 0;
307     int first_nr, list_len, try_id, try_nr, add_id;
308     int num;
309     char id [IDLEN+1];
310     
311     if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
312         return ok;
313     
314     if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
315         /* the first message is unknown -> all messages are new */
316         *newp = *countp;        
317         return 0;
318     }
319
320     /* check where we expect the latest known message */
321     list_len = count_list( &ctl->oldsaved );
322     try_id = list_len  - first_nr; /* -1 + 1 */
323     if( try_id > 1 ) {
324         if( try_id <= *countp ) {
325             if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
326                 return ok;
327     
328             try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
329         } else {
330             try_id = *countp+1;
331             try_nr = -1;
332         }
333         if( try_nr != list_len -1 ) {
334             /* some messages inbetween have been deleted... */
335             if( try_nr == -1 ) {
336                 nolinear = 1;
337
338                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
339                     ;
340                 for( ; add_id; add_id >>= 1 ) {
341                     if( try_nr == -1 ) {
342                         if( try_id - add_id <= 1 ) {
343                             continue;
344                         }
345                         try_id -= add_id;
346                     } else 
347                         try_id += add_id;
348                     
349                     if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
350                         return ok;
351                     try_nr = str_nr_in_list(&ctl->oldsaved, id);
352                 }
353                 if( try_nr == -1 ) {
354                     try_id--;
355                 }
356             } else {
357                 report(stderr, 
358                        _("Messages inserted into list on server. Cannot handle this.\n"));
359                 return -1;
360             }
361         } 
362     }
363     /* the first try_id messages are known -> copy them to the newsaved list */
364     for( num = first_nr; num < list_len; num++ )
365     {
366         struct idlist   *new = save_str(&ctl->newsaved, 
367                                 str_from_nr_list(&ctl->oldsaved, num),
368                                 UID_UNSEEN);
369         new->val.status.num = num - first_nr + 1;
370     }
371
372     if( nolinear ) {
373         free_str_list(&ctl->oldsaved);
374         ctl->oldsaved = 0;
375         last = try_id;
376     }
377
378     *newp = *countp - try_id;
379     return 0;
380 }
381
382 static int pop3_getrange(int sock, 
383                          struct query *ctl,
384                          const char *folder,
385                          int *countp, int *newp, int *bytes)
386 /* get range of messages to be fetched */
387 {
388     int ok;
389     char buf [POPBUFSIZE+1];
390
391     /* Ensure that the new list is properly empty */
392     ctl->newsaved = (struct idlist *)NULL;
393
394 #ifdef MBOX
395     /* Alain Knaff suggests this, but it's not RFC standard */
396     if (folder)
397         if ((ok = gen_transact(sock, "MBOX %s", folder)))
398             return ok;
399 #endif /* MBOX */
400
401     /* get the total message count */
402     gen_send(sock, "STAT");
403     ok = pop3_ok(sock, buf);
404     if (ok == 0)
405         sscanf(buf,"%d %d", countp, bytes);
406     else
407         return(ok);
408
409     /*
410      * Newer, RFC-1725-conformant POP servers may not have the LAST command.
411      * We work as hard as possible to hide this ugliness, but it makes 
412      * counting new messages intrinsically quadratic in the worst case.
413      */
414     last = 0;
415     *newp = -1;
416     if (*countp > 0 && !ctl->fetchall)
417     {
418         char id [IDLEN+1];
419
420         if (!ctl->server.uidl) {
421             gen_send(sock, "LAST");
422             ok = pop3_ok(sock, buf);
423         } else
424             ok = 1;
425         if (ok == 0)
426         {
427             if (sscanf(buf, "%d", &last) == 0)
428             {
429                 report(stderr, _("protocol error\n"));
430                 return(PS_ERROR);
431             }
432             *newp = (*countp - last);
433         }
434         else
435         {
436             /* grab the mailbox's UID list */
437             if ((ok = gen_transact(sock, "UIDL")) != 0)
438             {
439                 /* don't worry, yet! do it the slow way */
440                 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
441                 {
442                     report(stderr, _("protocol error while fetching UIDLs\n"));
443                     return(PS_ERROR);
444                 }
445             }
446             else
447             {
448                 int     num;
449
450                 *newp = 0;
451                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
452                 {
453                     if (buf[0] == '.')
454                         break;
455                     else if (sscanf(buf, "%d %s", &num, id) == 2)
456                     {
457                         struct idlist   *new;
458
459                         new = save_str(&ctl->newsaved, id, UID_UNSEEN);
460                         new->val.status.num = num;
461
462                         if (str_in_list(&ctl->oldsaved, id, FALSE)) {
463                             new->val.status.mark = UID_SEEN;
464                             str_set_mark(&ctl->oldsaved, id, UID_SEEN);
465                         }
466                         else
467                             (*newp)++;
468                     }
469                 }
470             }
471         }
472     }
473
474     return(PS_SUCCESS);
475 }
476
477 static int pop3_getsizes(int sock, int count, int *sizes)
478 /* capture the sizes of all messages */
479 {
480     int ok;
481
482     if ((ok = gen_transact(sock, "LIST")) != 0)
483         return(ok);
484     else
485     {
486         char buf [POPBUFSIZE+1];
487
488         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
489         {
490             int num, size;
491
492             if (buf[0] == '.')
493                 break;
494             else if (sscanf(buf, "%d %d", &num, &size) == 2)
495                 sizes[num - 1] = size;
496         }
497
498         return(ok);
499     }
500 }
501
502 static int pop3_is_old(int sock, struct query *ctl, int num)
503 /* is the given message old? */
504 {
505     if (!ctl->oldsaved)
506         return (num <= last);
507     else
508         return (str_in_list(&ctl->oldsaved,
509                             str_find(&ctl->newsaved, num), FALSE));
510 }
511
512 #ifdef UNUSED
513 /*
514  * We could use this to fetch headers only as we do for IMAP.  The trouble 
515  * is that there's no way to fetch the body only.  So the following RETR 
516  * would have to re-fetch the header.  Enough messages have longer headers
517  * than bodies to make this a net loss.
518  */
519 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
520 /* request headers of nth message */
521 {
522     int ok;
523     char buf[POPBUFSIZE+1];
524
525     gen_send(sock, "TOP %d 0", number);
526     if ((ok = pop3_ok(sock, buf)) != 0)
527         return(ok);
528
529     *lenp = -1;         /* we got sizes from the LIST response */
530
531     return(PS_SUCCESS);
532 }
533 #endif /* UNUSED */
534
535 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
536 /* request nth message */
537 {
538     int ok;
539     char buf[POPBUFSIZE+1];
540
541 #ifdef SDPS_ENABLE
542     /*
543      * See http://www.demon.net/services/mail/sdps-tech.html
544      * for a description of what we're parsing here.
545      */
546     if (ctl->server.sdps)
547     {
548         int     linecount = 0;
549
550         sdps_envfrom = (char *)NULL;
551         sdps_envto = (char *)NULL;
552         gen_send(sock, "*ENV %d", number);
553         do {
554             if (gen_recv(sock, buf, sizeof(buf)))
555             {
556                 break;
557             }
558             linecount++;
559             switch (linecount) {
560             case 4:
561                 /* No need to wrap envelope from address */
562                 sdps_envfrom = xmalloc(strlen(buf)+1);
563                 strcpy(sdps_envfrom,buf);
564                 break;
565             case 5:
566                 /* Wrap address with To: <> so nxtaddr() likes it */
567                 sdps_envto = xmalloc(strlen(buf)+7);
568                 sprintf(sdps_envto,"To: <%s>",buf);
569                 break;
570             }
571         } while
572             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
573     }
574 #endif /* SDPS_ENABLE */
575
576     /*
577      * Though the POP RFCs don't document this fact, on almost every
578      * POP3 server I know of messages are marked "seen" only at the
579      * time the OK response to a RETR is issued.
580      *
581      * This means we can use TOP to fetch the message without setting its
582      * seen flag.  This is good!  It means that if the protocol exchange
583      * craps out during the message, it will still be marked `unseen' on
584      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
585      * reported to mark messages seen on a TOP fetch.)
586      *
587      * However...*don't* do this if we're using keep to suppress deletion!
588      * In that case, marking the seen flag is the only way to prevent the
589      * message from being re-fetched on subsequent runs.
590      *
591      * Also use RETR if fetchall is on.  This gives us a workaround
592      * for servers like usa.net's that bungle TOP.  It's pretty
593      * harmless because fetchall guarantees that any message dropped
594      * by an interrupted RETR will be picked up on the next poll of the
595      * site.
596      *
597      * We take advantage here of the fact that, according to all the
598      * POP RFCs, "if the number of lines requested by the POP3 client
599      * is greater than than the number of lines in the body, then the
600      * POP3 server sends the entire message.").
601      *
602      * The line count passed (99999999) is the maximum value CompuServe will
603      * accept; it's much lower than the natural value 2147483646 (the maximum
604      * twos-complement signed 32-bit integer minus 1) */
605     if (ctl->keep || ctl->fetchall)
606         gen_send(sock, "RETR %d", number);
607     else
608         gen_send(sock, "TOP %d 99999999", number);
609     if ((ok = pop3_ok(sock, buf)) != 0)
610         return(ok);
611
612     *lenp = -1;         /* we got sizes from the LIST response */
613
614     return(PS_SUCCESS);
615 }
616
617 static int pop3_delete(int sock, struct query *ctl, int number)
618 /* delete a given message */
619 {
620     /* actually, mark for deletion -- doesn't happen until QUIT time */
621     return(gen_transact(sock, "DELE %d", number));
622 }
623
624 static int pop3_logout(int sock, struct query *ctl)
625 /* send logout command */
626 {
627     int ok;
628
629     ok = gen_transact(sock, "QUIT");
630     if (!ok)
631         expunge_uids(ctl);
632
633     return(ok);
634 }
635
636 const static struct method pop3 =
637 {
638     "POP3",             /* Post Office Protocol v3 */
639 #if INET6_ENABLE
640     "pop3",             /* standard POP3 port */
641     "pop3s",            /* ssl POP3 port */
642 #else /* INET6_ENABLE */
643     110,                /* standard POP3 port */
644     995,                /* ssl POP3 port */
645 #endif /* INET6_ENABLE */
646     FALSE,              /* this is not a tagged protocol */
647     TRUE,               /* this uses a message delimiter */
648     pop3_ok,            /* parse command response */
649     NULL,               /* no password canonicalization */
650     pop3_getauth,       /* get authorization */
651     pop3_getrange,      /* query range of messages */
652     pop3_getsizes,      /* we can get a list of sizes */
653     pop3_is_old,        /* how do we tell a message is old? */
654     pop3_fetch,         /* request given message */
655     NULL,               /* no way to fetch body alone */
656     NULL,               /* no message trailer */
657     pop3_delete,        /* how to delete a message */
658     pop3_logout,        /* log out, we're done */
659     FALSE,              /* no, we can't re-poll */
660 };
661
662 int doPOP3 (struct query *ctl)
663 /* retrieve messages using POP3 */
664 {
665 #ifndef MBOX
666     if (ctl->mailboxes->id) {
667         fprintf(stderr,_("Option --remote is not supported with POP3\n"));
668         return(PS_SYNTAX);
669     }
670 #endif /* MBOX */
671     peek_capable = !ctl->fetchall;
672     return(do_protocol(ctl, &pop3));
673 }
674 #endif /* POP3_ENABLE */
675
676 /* pop3.c ends here */