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