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