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