]> Pileus Git - ~andy/fetchmail/blob - pop3.c
7e40a7d78fd46af3a083bb0073eeded235314b8d
[~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 #include  <errno.h>
20
21 #include  "fetchmail.h"
22 #include  "socket.h"
23 #include  "i18n.h"
24
25 #ifdef OPIE_ENABLE
26 #include <opie.h>
27 #endif /* OPIE_ENABLE */
28
29 static int last;
30 #ifdef SDPS_ENABLE
31 char *sdps_envfrom;
32 char *sdps_envto;
33 #endif /* SDPS_ENABLE */
34
35 #ifdef OPIE_ENABLE
36 static char lastok[POPBUFSIZE+1];
37 #endif /* OPIE_ENABLE */
38
39 /* these variables are shared between the CAPA probe and the authenticator */
40 #if defined(GSSAPI)
41     flag has_gssapi = FALSE;
42 #endif /* defined(GSSAPI) */
43 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
44     flag has_kerberos = FALSE;
45 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
46     static flag has_cram = FALSE;
47 #ifdef OPIE_ENABLE
48     flag has_otp = FALSE;
49 #endif /* OPIE_ENABLE */
50 #ifdef SSL_ENABLE
51     static flag has_ssl = FALSE;
52 #endif /* SSL_ENABLE */
53
54 #ifdef NTLM_ENABLE
55 #include "ntlm.h"
56
57 static tSmbNtlmAuthRequest   request;              
58 static tSmbNtlmAuthChallenge challenge;
59 static tSmbNtlmAuthResponse  response;
60
61 /*
62  * NTLM support by Grant Edwards.
63  *
64  * Handle MS-Exchange NTLM authentication method.  This is the same
65  * as the NTLM auth used by Samba for SMB related services. We just
66  * encode the packets in base64 instead of sending them out via a
67  * network interface.
68  * 
69  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
70  */
71
72 static int do_pop3_ntlm(int sock, struct query *ctl)
73 {
74     char msgbuf[2048];
75     int result,len;
76   
77     gen_send(sock, "AUTH MSN");
78
79     if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
80         return result;
81   
82     if (msgbuf[0] != '+')
83         return PS_AUTHFAIL;
84   
85     buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
86
87     if (outlevel >= O_DEBUG)
88         dumpSmbNtlmAuthRequest(stdout, &request);
89
90     memset(msgbuf,0,sizeof msgbuf);
91     to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
92   
93     if (outlevel >= O_MONITOR)
94         report(stdout, "POP3> %s\n", msgbuf);
95   
96     strcat(msgbuf,"\r\n");
97     SockWrite (sock, msgbuf, strlen (msgbuf));
98
99     if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
100         return result;
101   
102     len = from64tobits ((unsigned char*)&challenge, msgbuf, sizeof(msgbuf));
103     
104     if (outlevel >= O_DEBUG)
105         dumpSmbNtlmAuthChallenge(stdout, &challenge);
106     
107     buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
108   
109     if (outlevel >= O_DEBUG)
110         dumpSmbNtlmAuthResponse(stdout, &response);
111   
112     memset(msgbuf,0,sizeof msgbuf);
113     to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
114
115     if (outlevel >= O_MONITOR)
116         report(stdout, "POP3> %s\n", msgbuf);
117       
118     strcat(msgbuf,"\r\n");
119     SockWrite (sock, msgbuf, strlen (msgbuf));
120   
121     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
122         return result;
123   
124     if (strstr (msgbuf, "OK"))
125         return PS_SUCCESS;
126     else
127         return PS_AUTHFAIL;
128 }
129 #endif /* NTLM */
130
131
132 #define DOTLINE(s)      (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
133
134 static int pop3_ok (int sock, char *argbuf)
135 /* parse command response */
136 {
137     int ok;
138     char buf [POPBUFSIZE+1];
139     char *bufp;
140
141     if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
142     {   bufp = buf;
143         if (*bufp == '+' || *bufp == '-')
144             bufp++;
145         else
146             return(PS_PROTOCOL);
147
148         while (isalpha((unsigned char)*bufp))
149             bufp++;
150
151         if (*bufp)
152           *(bufp++) = '\0';
153
154         if (strcmp(buf,"+OK") == 0)
155         {
156 #ifdef OPIE_ENABLE
157             strcpy(lastok, bufp);
158 #endif /* OPIE_ENABLE */
159             ok = 0;
160         }
161         else if (strncmp(buf,"-ERR", 4) == 0)
162         {
163             if (stage == STAGE_FETCH)
164                 ok = PS_TRANSIENT;
165             else if (stage > STAGE_GETAUTH)
166                 ok = PS_PROTOCOL;
167             /*
168              * We're checking for "lock busy", "unable to lock", 
169              * "already locked", "wait a few minutes" etc. here. 
170              * This indicates that we have to wait for the server to
171              * unwedge itself before we can poll again.
172              *
173              * PS_LOCKBUSY check empirically verified with two recent
174              * versions of the Berkeley popper; QPOP (version 2.2)  and
175              * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
176              * These are caught by the case-indifferent "lock" check.
177              * The "wait" catches "mail storage services unavailable,
178              * wait a few minutes and try again" on the InterMail server.
179              *
180              * If these aren't picked up on correctly, fetchmail will 
181              * think there is an authentication failure and wedge the
182              * connection in order to prevent futile polls.
183              *
184              * Gad, what a kluge.
185              */
186             else if (strstr(bufp,"lock")
187                      || strstr(bufp,"Lock")
188                      || strstr(bufp,"LOCK")
189                      || strstr(bufp,"wait")
190                      /* these are blessed by RFC 2449 */
191                      || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
192                 ok = PS_LOCKBUSY;
193             else if ((strstr(bufp,"Service")
194                      || strstr(bufp,"service"))
195                          && (strstr(bufp,"unavailable")))
196                 ok = PS_SERVBUSY;
197             else
198                 ok = PS_AUTHFAIL;
199             /*
200              * We always want to pass the user lock-busy messages, because
201              * they're red flags.  Other stuff (like AUTH failures on non-
202              * RFC1734 servers) only if we're debugging.
203              */
204             if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
205               report(stderr, "%s\n", bufp);
206         }
207         else
208             ok = PS_PROTOCOL;
209
210         if (argbuf != NULL)
211             strcpy(argbuf,bufp);
212     }
213
214     return(ok);
215 }
216
217
218
219 static int capa_probe(int sock)
220 /* probe the capabilities of the remote server */
221 {
222     int ok;
223
224 #if defined(GSSAPI)
225     has_gssapi = FALSE;
226 #endif /* defined(GSSAPI) */
227 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
228     has_kerberos = FALSE;
229 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
230     has_cram = FALSE;
231 #ifdef OPIE_ENABLE
232     has_otp = FALSE;
233 #endif /* OPIE_ENABLE */
234
235     ok = gen_transact(sock, "CAPA");
236     if (ok == PS_SUCCESS)
237     {
238         char buffer[64];
239
240         /* determine what authentication methods we have available */
241         while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
242         {
243             if (DOTLINE(buffer))
244                 break;
245 #ifdef SSL_ENABLE
246             if (strstr(buffer, "STLS"))
247                 has_ssl = TRUE;
248 #endif /* SSL_ENABLE */
249 #if defined(GSSAPI)
250             if (strstr(buffer, "GSSAPI"))
251                 has_gssapi = TRUE;
252 #endif /* defined(GSSAPI) */
253 #if defined(KERBEROS_V4)
254             if (strstr(buffer, "KERBEROS_V4"))
255                 has_kerberos = TRUE;
256 #endif /* defined(KERBEROS_V4)  */
257 #ifdef OPIE_ENABLE
258             if (strstr(buffer, "X-OTP"))
259                 has_otp = TRUE;
260 #endif /* OPIE_ENABLE */
261             if (strstr(buffer, "CRAM-MD5"))
262                 has_cram = TRUE;
263         }
264     }
265     return(ok);
266 }
267
268 static void set_peek_capable(struct query *ctl)
269 {
270     /* we're peek-capable means that the use of TOP is enabled,
271      * see pop3_fetch for details - short story, we can use TOP if
272      * we have a means of reliably tracking which mail we need to
273      * refetch should the connection abort in the middle.
274      * fetchall forces RETR, as does keep without UIDL */
275     peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
276 }
277
278 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
279 /* apply for connection authorization */
280 {
281     int ok;
282     char *start,*end;
283     char *msg;
284 #ifdef OPIE_ENABLE
285     char *challenge;
286 #endif /* OPIE_ENABLE */
287 #ifdef SSL_ENABLE
288     flag did_stls = FALSE;
289 #endif /* SSL_ENABLE */
290
291 #if defined(GSSAPI)
292     has_gssapi = FALSE;
293 #endif /* defined(GSSAPI) */
294 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
295     has_kerberos = FALSE;
296 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
297     has_cram = FALSE;
298 #ifdef OPIE_ENABLE
299     has_otp = FALSE;
300 #endif /* OPIE_ENABLE */
301 #ifdef SSL_ENABLE
302     has_ssl = FALSE;
303 #endif /* SSL_ENABLE */
304
305     if (ctl->server.authenticate == A_SSH) {
306         return PS_SUCCESS;
307     }
308
309 #ifdef SDPS_ENABLE
310     /*
311      * This needs to catch both demon.co.uk and demon.net.
312      * If we see either, and we're in multidrop mode, try to use
313      * the SDPS *ENV extension.
314      */
315     if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
316         ctl->server.sdps = TRUE;
317 #endif /* SDPS_ENABLE */
318 #ifdef NTLM_ENABLE
319         /* MSN servers require the use of NTLM (MSN) authentication */
320         if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
321             ctl->server.authenticate == A_NTLM)
322         {
323             if (!do_pop3_ntlm(sock, ctl))
324             {
325                 return(PS_SUCCESS);
326             }
327             else
328             {
329                 return(PS_AUTHFAIL);
330             }
331         }
332 #endif
333
334     switch (ctl->server.protocol) {
335     case P_POP3:
336 #ifdef RPA_ENABLE
337         /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
338         if (strstr(ctl->remotename, "@compuserve.com"))
339         {
340             /* AUTH command should return a list of available mechanisms */
341             if (gen_transact(sock, "AUTH") == 0)
342             {
343                 char buffer[10];
344                 flag has_rpa = FALSE;
345
346                 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
347                 {
348                     if (DOTLINE(buffer))
349                         break;
350                     if (strncasecmp(buffer, "rpa", 3) == 0)
351                         has_rpa = TRUE;
352                 }
353                 if (has_rpa && !POP3_auth_rpa(ctl->remotename, 
354                                               ctl->password, sock))
355                     return(PS_SUCCESS);
356             }
357
358             return(PS_AUTHFAIL);
359         }
360 #endif /* RPA_ENABLE */
361
362         /*
363          * CAPA command may return a list including available
364          * authentication mechanisms.  if it doesn't, no harm done, we
365          * just fall back to a plain login.  Note that this code 
366          * latches the server's authentication type, so that in daemon mode
367          * the CAPA check only needs to be done once at start of run.
368          *
369          * If CAPA fails, then force the authentication method to PASSORD
370          * and repoll immediately.
371          *
372          * These authentication methods are blessed by RFC1734,
373          * describing the POP3 AUTHentication command.
374          */
375         if ((ctl->server.authenticate == A_ANY) ||
376             (ctl->server.authenticate == A_GSSAPI) ||
377             (ctl->server.authenticate == A_KERBEROS_V4) ||
378             (ctl->server.authenticate == A_OTP) ||
379             (ctl->server.authenticate == A_CRAM_MD5))
380         {
381             if ((ok = capa_probe(sock)) != PS_SUCCESS)
382             /* we are in STAGE_GETAUTH! */
383                 if (ok == PS_AUTHFAIL ||
384                     /* Some servers directly close the socket. However, if we
385                      * have already authenticated before, then a previous CAPA
386                      * must have succeeded. In that case, treat this as a
387                      * genuine socket error and do not change the auth method.
388                      */
389                     (ok == PS_SOCKET && !ctl->wehaveauthed))
390                 {
391                     ctl->server.authenticate = A_PASSWORD;
392                     /* repoll immediately */
393                     ok = PS_REPOLL;
394                     break;
395                 }
396         }
397
398 #ifdef SSL_ENABLE
399         if (has_ssl
400             && !ctl->use_ssl
401             && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
402         {
403             char *realhost;
404
405            realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
406            ok = gen_transact(sock, "STLS");
407
408            /* We use "tls1" instead of ctl->sslproto, as we want STLS,
409             * not other SSL protocols
410             */
411            if (ok == PS_SUCCESS &&
412                SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
413            {
414                if (!ctl->sslproto && !ctl->wehaveauthed)
415                {
416                    ctl->sslproto = xstrdup("");
417                    /* repoll immediately */
418                    return(PS_REPOLL);
419                }
420                report(stderr,
421                        GT_("SSL connection failed.\n"));
422                 return(PS_AUTHFAIL);
423             }
424            did_stls = TRUE;
425
426            /*
427             * RFC 2595 says this:
428             *
429             * "Once TLS has been started, the client MUST discard cached
430             * information about server capabilities and SHOULD re-issue the
431             * CAPABILITY command.  This is necessary to protect against
432             * man-in-the-middle attacks which alter the capabilities list prior
433             * to STARTTLS.  The server MAY advertise different capabilities
434             * after STARTTLS."
435             */
436            capa_probe(sock);
437         }
438 #endif /* SSL_ENABLE */
439
440         /*
441          * OK, we have an authentication type now.
442          */
443 #if defined(KERBEROS_V4)
444         /* 
445          * Servers doing KPOP have to go through a dummy login sequence
446          * rather than doing SASL.
447          */
448         if (has_kerberos &&
449 #ifdef INET6_ENABLE
450             ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
451 #else /* INET6_ENABLE */
452             ctl->server.port != KPOP_PORT
453 #endif /* INET6_ENABLE */
454             && (ctl->server.authenticate == A_KERBEROS_V4
455              || ctl->server.authenticate == A_KERBEROS_V5
456              || ctl->server.authenticate == A_ANY))
457         {
458             ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
459             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
460                 break;
461         }
462 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
463
464 #if defined(GSSAPI)
465         if (has_gssapi &&
466             (ctl->server.authenticate == A_GSSAPI ||
467              ctl->server.authenticate == A_ANY))
468         {
469             ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
470             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
471                 break;
472         }
473 #endif /* defined(GSSAPI) */
474
475 #ifdef OPIE_ENABLE
476         if (has_otp &&
477             (ctl->server.authenticate == A_OTP ||
478              ctl->server.authenticate == A_ANY))
479         {
480             ok = do_otp(sock, "AUTH", ctl);
481             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
482                 break;
483         }
484 #endif /* OPIE_ENABLE */
485
486         if (ctl->server.authenticate == A_CRAM_MD5 || 
487             (has_cram && ctl->server.authenticate == A_ANY))
488         {
489             ok = do_cram_md5(sock, "AUTH", ctl, NULL);
490             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
491                 break;
492         }
493
494         /* ordinary validation, no one-time password or RPA */ 
495         if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
496             break;
497
498 #ifdef OPIE_ENABLE
499         /* see RFC1938: A One-Time Password System */
500         if ((challenge = strstr(lastok, "otp-"))) {
501           char response[OPIE_RESPONSE_MAX+1];
502           int i;
503
504           i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
505           if ((i == -2) && !run.poll_interval) {
506             char secret[OPIE_SECRET_MAX+1];
507             fprintf(stderr, GT_("Secret pass phrase: "));
508             if (opiereadpass(secret, sizeof(secret), 0))
509               i = opiegenerator(challenge,  secret, response);
510             memset(secret, 0, sizeof(secret));
511           };
512
513           if (i) {
514             ok = PS_ERROR;
515             break;
516           };
517
518           ok = gen_transact(sock, "PASS %s", response);
519           break;
520         }
521 #endif /* OPIE_ENABLE */
522
523         strcpy(shroud, ctl->password);
524         ok = gen_transact(sock, "PASS %s", ctl->password);
525         shroud[0] = '\0';
526 #ifdef SSL_ENABLE
527         /* this is for servers which claim to support TLS, but actually
528          * don't! */
529         if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
530         {
531             ctl->sslproto = xstrdup("");
532             /* repoll immediately */
533             ok = PS_REPOLL;
534         }
535 #endif
536         break;
537
538     case P_APOP:
539         /* build MD5 digest from greeting timestamp + password */
540         /* find start of timestamp */
541         for (start = greeting;  *start != 0 && *start != '<';  start++)
542             continue;
543         if (*start == 0) {
544             report(stderr,
545                    GT_("Required APOP timestamp not found in greeting\n"));
546             return(PS_AUTHFAIL);
547         }
548
549         /* find end of timestamp */
550         for (end = start;  *end != 0  && *end != '>';  end++)
551             continue;
552         if (*end == 0 || end == start + 1) {
553             report(stderr, 
554                    GT_("Timestamp syntax error in greeting\n"));
555             return(PS_AUTHFAIL);
556         }
557         else
558             *++end = '\0';
559
560         /* copy timestamp and password into digestion buffer */
561         xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
562         strcpy(msg,start);
563         strcat(msg,ctl->password);
564
565         strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
566
567         ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
568         break;
569
570     case P_RPOP:
571         if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
572             ok = gen_transact(sock, "RPOP %s", ctl->password);
573         break;
574
575     default:
576         report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
577         ok = PS_ERROR;
578     }
579
580     if (ok != 0)
581     {
582         /* maybe we detected a lock-busy condition? */
583         if (ok == PS_LOCKBUSY)
584             report(stderr, GT_("lock busy!  Is another session active?\n")); 
585
586         return(ok);
587     }
588
589 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
590  * accepted by Matthias Andree.
591  *
592  * Rationale: the server must have locked the spool before returning +OK;
593  * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
594 #ifdef WANT_BOGUS
595     /*
596      * Empirical experience shows some server/OS combinations
597      * may need a brief pause even after any lockfiles on the
598      * server are released, to give the server time to finish
599      * copying back very large mailfolders from the temp-file...
600      * this is only ever an issue with extremely large mailboxes.
601      */
602     sleep(3); /* to be _really_ safe, probably need sleep(5)! */
603 #endif
604
605     set_peek_capable(ctl);
606
607     /* we're approved */
608     return(PS_SUCCESS);
609 }
610
611 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
612 {
613     int ok;
614     int got_it;
615     char buf [POPBUFSIZE+1];
616     snprintf(buf, sizeof(buf), "TOP %d 1", num);
617     if ((ok = gen_transact(sock, buf )) != 0)
618        return ok;
619     got_it = 0;
620     while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0) 
621     {
622         if (DOTLINE(buf))
623             break;
624         if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
625             char *p = buf + 11;
626             p += strspn(p, POSIX_space);
627             p = strtok(p, POSIX_space);
628             strlcpy(id, p, idsize);
629         }
630     }
631     return 0;
632 }
633
634 /** Parse destructively the UID response (leading +OK must have been
635  * stripped off) in buf, store the number in gotnum, and store the ID
636  * into the caller-provided buffer "id" of size "idsize".
637  * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
638 static int parseuid(char *buf, unsigned long *gotnum, char *id, size_t idsize)
639 {
640     char *i, *j;
641
642     i = strtok(buf, POSIX_space);
643     errno = 0;
644     *gotnum = strtoul(i, &j, 10);
645     if (*j != '\0' || j == i || errno) {
646         report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
647         return PS_PROTOCOL;
648     }
649     i = strtok(NULL, POSIX_space);
650     strlcpy(id, i, idsize);
651     return PS_SUCCESS;
652 }
653
654 static int pop3_getuidl(int sock, int num , char *id, size_t idsize)
655 {
656     int ok;
657     char buf [POPBUFSIZE+1];
658     unsigned long gotnum;
659
660     gen_send(sock, "UIDL %d", num);
661     if ((ok = pop3_ok(sock, buf)) != 0)
662         return(ok);
663     if ((ok = parseuid(buf, &gotnum, id, idsize)))
664         return ok;
665     if (gotnum != num) {
666         report(stderr, GT_("Server responded with UID for wrong message.\n"));
667         return PS_PROTOCOL;
668     }
669     return(PS_SUCCESS);
670 }
671
672 static int pop3_fastuidl( int sock,  struct query *ctl, unsigned int count, int *newp)
673 {
674     int ok;
675     unsigned int first_nr, last_nr, try_nr;
676     char id [IDLEN+1];
677
678     first_nr = 0;
679     last_nr = count + 1;
680     while (first_nr < last_nr - 1)
681     {
682         struct idlist   *new;
683
684         try_nr = (first_nr + last_nr) / 2;
685         if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
686             return ok;
687         if ((new = str_in_list(&ctl->oldsaved, id, FALSE)))
688         {
689             flag mark = new->val.status.mark;
690             if (mark == UID_DELETED || mark == UID_EXPUNGED)
691             {
692                 if (outlevel >= O_VERBOSE)
693                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
694                 /* just mark it as seen now! */
695                 new->val.status.mark = mark = UID_SEEN;
696             }
697
698             /* narrow the search region! */
699             if (mark == UID_UNSEEN)
700             {
701                 if (outlevel >= O_DEBUG)
702                     report(stdout, GT_("%u is unseen\n"), try_nr);
703                 last_nr = try_nr;
704             }
705             else
706                 first_nr = try_nr;
707
708             /* save the number */
709             new->val.status.num = try_nr;
710         }
711         else
712         {
713             if (outlevel >= O_DEBUG)
714                 report(stdout, GT_("%u is unseen\n"), try_nr);
715             last_nr = try_nr;
716
717             /* save it */
718             new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
719             new->val.status.num = try_nr;
720         }
721     }
722     if (outlevel >= O_DEBUG && last_nr <= count)
723         report(stdout, GT_("%u is first unseen\n"), last_nr);
724
725     /* update last! */
726     *newp = count - first_nr;
727     last = first_nr;
728     return 0;
729 }
730
731 static int pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
732 {
733     /* This approach tries to get the message headers from the
734      * remote hosts and compares the message-id to the already known
735      * ones:
736      *  + if the first message containes a new id, all messages on
737      *    the server will be new
738      *  + if the first is known, try to estimate the last known message
739      *    on the server and check. If this works you know the total number
740      *    of messages to get.
741      *  + Otherwise run a binary search to determine the last known message
742      */
743     int ok, nolinear = 0;
744     int first_nr, list_len, try_id, try_nr, add_id;
745     int num;
746     char id [IDLEN+1];
747
748     if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
749         return ok;
750
751     if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
752         /* the first message is unknown -> all messages are new */
753         *newp = *countp;        
754         return 0;
755     }
756
757     /* check where we expect the latest known message */
758     list_len = count_list( &ctl->oldsaved );
759     try_id = list_len  - first_nr; /* -1 + 1 */
760     if( try_id > 1 ) {
761         if( try_id <= *countp ) {
762             if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
763                 return ok;
764     
765             try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
766         } else {
767             try_id = *countp+1;
768             try_nr = -1;
769         }
770         if( try_nr != list_len -1 ) {
771             /* some messages inbetween have been deleted... */
772             if( try_nr == -1 ) {
773                 nolinear = 1;
774
775                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
776                     ;
777                 for( ; add_id; add_id >>= 1 ) {
778                     if( try_nr == -1 ) {
779                         if( try_id - add_id <= 1 ) {
780                             continue;
781                         }
782                         try_id -= add_id;
783                     } else 
784                         try_id += add_id;
785                     
786                     if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
787                         return ok;
788                     try_nr = str_nr_in_list(&ctl->oldsaved, id);
789                 }
790                 if( try_nr == -1 ) {
791                     try_id--;
792                 }
793             } else {
794                 report(stderr, 
795                        GT_("Messages inserted into list on server. Cannot handle this.\n"));
796                 return -1;
797             }
798         } 
799     }
800     /* the first try_id messages are known -> copy them to the newsaved list */
801     for( num = first_nr; num < list_len; num++ )
802     {
803         struct idlist   *new = save_str(&ctl->newsaved, 
804                                 str_from_nr_list(&ctl->oldsaved, num),
805                                 UID_UNSEEN);
806         new->val.status.num = num - first_nr + 1;
807     }
808
809     if( nolinear ) {
810         free_str_list(&ctl->oldsaved);
811         ctl->oldsaved = 0;
812         last = try_id;
813     }
814
815     *newp = *countp - try_id;
816     return 0;
817 }
818
819 static int pop3_getrange(int sock, 
820                          struct query *ctl,
821                          const char *folder,
822                          int *countp, int *newp, int *bytes)
823 /* get range of messages to be fetched */
824 {
825     int ok;
826     char buf [POPBUFSIZE+1];
827
828     /* Ensure that the new list is properly empty */
829     ctl->newsaved = (struct idlist *)NULL;
830
831 #ifdef MBOX
832     /* Alain Knaff suggests this, but it's not RFC standard */
833     if (folder)
834         if ((ok = gen_transact(sock, "MBOX %s", folder)))
835             return ok;
836 #endif /* MBOX */
837
838     /* get the total message count */
839     gen_send(sock, "STAT");
840     ok = pop3_ok(sock, buf);
841     if (ok == 0)
842         sscanf(buf,"%d %d", countp, bytes);
843     else
844         return(ok);
845
846     /*
847      * Newer, RFC-1725-conformant POP servers may not have the LAST command.
848      * We work as hard as possible to hide this ugliness, but it makes
849      * counting new messages intrinsically quadratic in the worst case.
850      */
851     last = 0;
852     *newp = -1;
853     if (*countp > 0 && !ctl->fetchall)
854     {
855         int fastuidl;
856         char id [IDLEN+1];
857
858         /* should we do fast uidl this time? */
859         fastuidl = ctl->fastuidl;
860         if (*countp > 7 &&              /* linear search is better if there are few mails! */
861             !ctl->flush &&              /* with flush, it is safer to disable fastuidl */
862             NUM_NONZERO (fastuidl))
863         {
864             if (fastuidl == 1)
865                 dofastuidl = 1;
866             else
867                 dofastuidl = ctl->fastuidlcount != 0;
868         }
869         else
870             dofastuidl = 0;
871
872         if (!ctl->server.uidl) {
873             gen_send(sock, "LAST");
874             ok = pop3_ok(sock, buf);
875         } else
876             ok = 1;
877         if (ok == 0)
878         {
879             if (sscanf(buf, "%d", &last) == 0)
880             {
881                 report(stderr, GT_("protocol error\n"));
882                 return(PS_ERROR);
883             }
884             *newp = (*countp - last);
885         }
886         else
887         {
888             if (dofastuidl)
889                 return(pop3_fastuidl( sock, ctl, *countp, newp));
890             /* grab the mailbox's UID list */
891             if ((ok = gen_transact(sock, "UIDL")) != 0)
892             {
893                 /* don't worry, yet! do it the slow way */
894                 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
895                 {
896                     report(stderr, GT_("protocol error while fetching UIDLs\n"));
897                     return(PS_ERROR);
898                 }
899             }
900             else
901             {
902                 unsigned long unum;
903
904                 *newp = 0;
905                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
906                 {
907                     if (DOTLINE(buf))
908                         break;
909
910                     if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
911                     {
912                         struct idlist   *old, *new;
913
914                         new = save_str(&ctl->newsaved, id, UID_UNSEEN);
915                         new->val.status.num = unum;
916
917                         if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
918                         {
919                             flag mark = old->val.status.mark;
920                             if (mark == UID_DELETED || mark == UID_EXPUNGED)
921                             {
922                                 /* XXX FIXME: switch 3 occurrences from
923                                  * (int)unum or (unsigned int)unum to
924                                  * remove the cast and use %lu - not now
925                                  * though, time for new release */
926                                 if (outlevel >= O_VERBOSE)
927                                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
928                                 /* just mark it as seen now! */
929                                 old->val.status.mark = mark = UID_SEEN;
930                             }
931                             new->val.status.mark = mark;
932                             if (mark == UID_UNSEEN)
933                             {
934                                 (*newp)++;
935                                 if (outlevel >= O_DEBUG)
936                                     report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
937                             }
938                         }
939                         else
940                         {
941                             (*newp)++;
942                             if (outlevel >= O_DEBUG)
943                                 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
944                             /* add it to oldsaved also! In case, we do not
945                              * swap the lists (say, due to socket error),
946                              * the same mail will not be downloaded again.
947                              */
948                             old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
949                             old->val.status.num = unum;
950                         }
951                     }
952                 }
953             }
954         }
955     }
956
957     return(PS_SUCCESS);
958 }
959
960 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
961 /* capture the size of message #first */
962 {
963     int ok = 0, i;
964     char buf [POPBUFSIZE+1];
965     unsigned int num, size;
966
967     for (i = first; i <= last; i++) {
968         gen_send(sock, "LIST %d", i);
969         if ((ok = pop3_ok(sock, buf)) != 0)
970             return(ok);
971         if (sscanf(buf, "%u %u", &num, &size) == 2) {
972             if (num == i)
973                 sizes[i - first] = size;
974             else
975                 /* warn about possible attempt to induce buffer overrun
976                  *
977                  * we expect server reply message number and requested
978                  * message number to match */
979                 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
980         }
981     }
982     return(ok);
983 }
984
985 static int pop3_getsizes(int sock, int count, int *sizes)
986 /* capture the sizes of all messages */
987 {
988     int ok;
989
990     if ((ok = gen_transact(sock, "LIST")) != 0)
991         return(ok);
992     else
993     {
994         char buf [POPBUFSIZE+1];
995
996         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
997         {
998             unsigned int num, size;
999
1000             if (DOTLINE(buf))
1001                 break;
1002             else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1003                 if (num > 0 && num <= count)
1004                     sizes[num - 1] = size;
1005                 else
1006                     /* warn about possible attempt to induce buffer overrun */
1007                     report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1008             }
1009         }
1010
1011         return(ok);
1012     }
1013 }
1014
1015 static int pop3_is_old(int sock, struct query *ctl, int num)
1016 /* is the given message old? */
1017 {
1018     struct idlist *new;
1019     if (!ctl->oldsaved)
1020         return (num <= last);
1021     else if (dofastuidl)
1022     {
1023         char id [IDLEN+1];
1024
1025         if (num <= last)
1026             return(TRUE);
1027
1028         /* in fast uidl, we manipulate the old list only! */
1029
1030         if ((new = id_find(&ctl->oldsaved, num)))
1031         {
1032             /* we already have the id! */
1033             return(new->val.status.mark != UID_UNSEEN);
1034         }
1035
1036         /* get the uidl first! */
1037         if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1038             return(TRUE);
1039
1040         if ((new = str_in_list(&ctl->oldsaved, id, FALSE))) {
1041             /* we already have the id! */
1042             new->val.status.num = num;
1043             return(new->val.status.mark != UID_UNSEEN);
1044         }
1045
1046         /* save it */
1047         new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1048         new->val.status.num = num;
1049         return(FALSE);
1050     }
1051     else
1052         return ((new = id_find(&ctl->newsaved, num)) != NULL &&
1053             new->val.status.mark != UID_UNSEEN);
1054 }
1055
1056 #ifdef UNUSED
1057 /*
1058  * We could use this to fetch headers only as we do for IMAP.  The trouble 
1059  * is that there's no way to fetch the body only.  So the following RETR 
1060  * would have to re-fetch the header.  Enough messages have longer headers
1061  * than bodies to make this a net loss.
1062  */
1063 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1064 /* request headers of nth message */
1065 {
1066     int ok;
1067     char buf[POPBUFSIZE+1];
1068
1069     gen_send(sock, "TOP %d 0", number);
1070     if ((ok = pop3_ok(sock, buf)) != 0)
1071         return(ok);
1072
1073     *lenp = -1;         /* we got sizes from the LIST response */
1074
1075     return(PS_SUCCESS);
1076 }
1077 #endif /* UNUSED */
1078
1079 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1080 /* request nth message */
1081 {
1082     int ok;
1083     char buf[POPBUFSIZE+1];
1084
1085 #ifdef SDPS_ENABLE
1086     /*
1087      * See http://www.demon.net/services/mail/sdps-tech.html
1088      * for a description of what we're parsing here.
1089      */
1090     if (ctl->server.sdps)
1091     {
1092         int     linecount = 0;
1093
1094         sdps_envfrom = (char *)NULL;
1095         sdps_envto = (char *)NULL;
1096         gen_send(sock, "*ENV %d", number);
1097         do {
1098             if (gen_recv(sock, buf, sizeof(buf)))
1099             {
1100                 break;
1101             }
1102             linecount++;
1103             switch (linecount) {
1104             case 4:
1105                 /* No need to wrap envelope from address */
1106                 sdps_envfrom = xmalloc(strlen(buf)+1);
1107                 strcpy(sdps_envfrom,buf);
1108                 break;
1109             case 5:
1110                 /* Wrap address with To: <> so nxtaddr() likes it */
1111                 sdps_envto = xmalloc(strlen(buf)+7);
1112                 sprintf(sdps_envto,"To: <%s>",buf);
1113                 break;
1114             }
1115         } while
1116             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1117     }
1118 #endif /* SDPS_ENABLE */
1119
1120     /*
1121      * Though the POP RFCs don't document this fact, on almost every
1122      * POP3 server I know of messages are marked "seen" only at the
1123      * time the OK response to a RETR is issued.
1124      *
1125      * This means we can use TOP to fetch the message without setting its
1126      * seen flag.  This is good!  It means that if the protocol exchange
1127      * craps out during the message, it will still be marked `unseen' on
1128      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
1129      * reported to mark messages seen on a TOP fetch.)
1130      *
1131      * However...*don't* do this if we're using keep to suppress deletion!
1132      * In that case, marking the seen flag is the only way to prevent the
1133      * message from being re-fetched on subsequent runs.
1134      *
1135      * Also use RETR (that means no TOP, no peek) if fetchall is on.
1136      * This gives us a workaround for servers like usa.net's that bungle
1137      * TOP.  It's pretty harmless because fetchall guarantees that any
1138      * message dropped by an interrupted RETR will be picked up on the
1139      * next poll of the site.
1140      *
1141      * We take advantage here of the fact that, according to all the
1142      * POP RFCs, "if the number of lines requested by the POP3 client
1143      * is greater than than the number of lines in the body, then the
1144      * POP3 server sends the entire message.").
1145      *
1146      * The line count passed (99999999) is the maximum value CompuServe will
1147      * accept; it's much lower than the natural value 2147483646 (the maximum
1148      * twos-complement signed 32-bit integer minus 1) */
1149     if (!peek_capable)
1150         gen_send(sock, "RETR %d", number);
1151     else
1152         gen_send(sock, "TOP %d 99999999", number);
1153     if ((ok = pop3_ok(sock, buf)) != 0)
1154         return(ok);
1155
1156     *lenp = -1;         /* we got sizes from the LIST response */
1157
1158     return(PS_SUCCESS);
1159 }
1160
1161 static void mark_uid_seen(struct query *ctl, int number)
1162 /* Tell the UID code we've seen this. */
1163 {
1164     struct idlist       *sdp;
1165
1166     if ((sdp = id_find(&ctl->newsaved, number)))
1167         sdp->val.status.mark = UID_SEEN;
1168     /* mark it as seen in oldsaved also! In case, we do not swap the lists
1169      * (say, due to socket error), the same mail will not be downloaded
1170      * again.
1171      */
1172     if ((sdp = id_find(&ctl->oldsaved, number)))
1173         sdp->val.status.mark = UID_SEEN;
1174 }
1175
1176 static int pop3_delete(int sock, struct query *ctl, int number)
1177 /* delete a given message */
1178 {
1179     int ok;
1180     mark_uid_seen(ctl, number);
1181     /* actually, mark for deletion -- doesn't happen until QUIT time */
1182     ok = gen_transact(sock, "DELE %d", number);
1183     if (ok != PS_SUCCESS)
1184         return(ok);
1185     delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1186     return(PS_SUCCESS);
1187 }
1188
1189 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1190 /* mark a given message as seen */
1191 {
1192     mark_uid_seen(ctl, number);
1193     return(PS_SUCCESS);
1194 }
1195
1196 static int pop3_logout(int sock, struct query *ctl)
1197 /* send logout command */
1198 {
1199     int ok;
1200
1201 #ifdef __UNUSED__
1202     /*
1203      * We used to do this in case the server marks messages deleted when seen.
1204      * (Yes, this has been reported, in the MercuryP/NLM server.
1205      * It's even legal under RFC 1939 (section 8) as a site policy.)
1206      * It interacted badly with UIDL, though.  Thomas Zajic wrote:
1207      * "Running 'fetchmail -F -v' and checking the logs, I found out
1208      * that fetchmail did in fact flush my mailbox properly, but sent
1209      * a RSET just before sending QUIT to log off.  This caused the
1210      * POP3 server to undo/forget about the previous DELEs, resetting
1211      * my mailbox to its original (ie.  unflushed) state. The
1212      * ~/.fetchids file did get flushed though, so the next time
1213      * fetchmail was run it saw all the old messages as new ones ..."
1214      */
1215      if (ctl->keep)
1216         gen_transact(sock, "RSET");
1217 #endif /* __UNUSED__ */
1218
1219     ok = gen_transact(sock, "QUIT");
1220     if (!ok)
1221         expunge_uids(ctl);
1222
1223     return(ok);
1224 }
1225
1226 static const struct method pop3 =
1227 {
1228     "POP3",             /* Post Office Protocol v3 */
1229 #ifdef INET6_ENABLE
1230     "pop3",             /* standard POP3 port */
1231     "pop3s",            /* ssl POP3 port */
1232 #else /* INET6_ENABLE */
1233     110,                /* standard POP3 port */
1234     995,                /* ssl POP3 port */
1235 #endif /* INET6_ENABLE */
1236     FALSE,              /* this is not a tagged protocol */
1237     TRUE,               /* this uses a message delimiter */
1238     pop3_ok,            /* parse command response */
1239     pop3_getauth,       /* get authorization */
1240     pop3_getrange,      /* query range of messages */
1241     pop3_getsizes,      /* we can get a list of sizes */
1242     pop3_getpartialsizes,       /* we can get the size of 1 mail */
1243     pop3_is_old,        /* how do we tell a message is old? */
1244     pop3_fetch,         /* request given message */
1245     NULL,               /* no way to fetch body alone */
1246     NULL,               /* no message trailer */
1247     pop3_delete,        /* how to delete a message */
1248     pop3_mark_seen,     /* how to mark a message as seen */
1249     pop3_logout,        /* log out, we're done */
1250     FALSE,              /* no, we can't re-poll */
1251 };
1252
1253 int doPOP3 (struct query *ctl)
1254 /* retrieve messages using POP3 */
1255 {
1256 #ifndef MBOX
1257     if (ctl->mailboxes->id) {
1258         fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
1259         return(PS_SYNTAX);
1260     }
1261 #endif /* MBOX */
1262     set_peek_capable(ctl); /* XXX FIXME: is this needed or do we always
1263                               call this from pop3_getauth anyways? */
1264     return(do_protocol(ctl, &pop3));
1265 }
1266 #endif /* POP3_ENABLE */
1267
1268 /* pop3.c ends here */