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