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