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