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