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