]> Pileus Git - ~andy/fetchmail/blob - pop3.c
df85e3e6a8d9be2838478cd22ea4f3144d25541c
[~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     /* comcast's Maillennium POP3/PROXY is full of bugs and truncates
615      * TOP replies after c. 80 kByte, so disable TOP. */
616     if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
617         report(stdout, GT_("Warning: Maillennium POP3/PROXY server found, using RETR command.\n"));
618         peek_capable = 0;
619     }
620
621     /* we're approved */
622     return(PS_SUCCESS);
623 }
624
625 /* cut off C string at first POSIX space */
626 static void trim(char *s) {
627     s += strcspn(s, POSIX_space);
628     s[0] = '\0';
629 }
630
631 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
632 {
633     int ok;
634     int got_it;
635     char buf [POPBUFSIZE+1];
636     snprintf(buf, sizeof(buf), "TOP %d 1", num);
637     if ((ok = gen_transact(sock, buf )) != 0)
638        return ok;
639     got_it = 0;
640     while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0) 
641     {
642         if (DOTLINE(buf))
643             break;
644         if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
645             char *p = buf + 11;
646             got_it = 1;
647             p += strspn(p, POSIX_space);
648             strlcpy(id, p, idsize);
649             trim(id);
650         }
651     }
652     return 0;
653 }
654
655 /** Parse the UID response (leading +OK must have been
656  * stripped off) in buf, store the number in gotnum, and store the ID
657  * into the caller-provided buffer "id" of size "idsize".
658  * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
659 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
660 {
661     const char *i;
662     char *j;
663
664     /* skip leading blanks ourselves */
665     i = buf;
666     i += strspn(i, POSIX_space);
667     errno = 0;
668     *gotnum = strtoul(i, &j, 10);
669     if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
670         report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
671         return PS_PROTOCOL;
672     }
673     j += strspn(j, POSIX_space);
674     strlcpy(id, j, idsize);
675     trim(id);
676     return PS_SUCCESS;
677 }
678
679 /** request UIDL for single message \a num and stuff the result into the
680  * buffer \a id which can hold \a idsize bytes */
681 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
682 {
683     int ok;
684     char buf [POPBUFSIZE+1];
685     unsigned long gotnum;
686
687     gen_send(sock, "UIDL %d", num);
688     if ((ok = pop3_ok(sock, buf)) != 0)
689         return(ok);
690     if ((ok = parseuid(buf, &gotnum, id, idsize)))
691         return ok;
692     if (gotnum != num) {
693         report(stderr, GT_("Server responded with UID for wrong message.\n"));
694         return PS_PROTOCOL;
695     }
696     return(PS_SUCCESS);
697 }
698
699 static int pop3_fastuidl( int sock,  struct query *ctl, unsigned int count, int *newp)
700 {
701     int ok;
702     unsigned int first_nr, last_nr, try_nr;
703     char id [IDLEN+1];
704
705     first_nr = 0;
706     last_nr = count + 1;
707     while (first_nr < last_nr - 1)
708     {
709         struct idlist   *new;
710
711         try_nr = (first_nr + last_nr) / 2;
712         if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
713             return ok;
714         if ((new = str_in_list(&ctl->oldsaved, id, FALSE)))
715         {
716             flag mark = new->val.status.mark;
717             if (mark == UID_DELETED || mark == UID_EXPUNGED)
718             {
719                 if (outlevel >= O_VERBOSE)
720                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
721                 /* just mark it as seen now! */
722                 new->val.status.mark = mark = UID_SEEN;
723             }
724
725             /* narrow the search region! */
726             if (mark == UID_UNSEEN)
727             {
728                 if (outlevel >= O_DEBUG)
729                     report(stdout, GT_("%u is unseen\n"), try_nr);
730                 last_nr = try_nr;
731             }
732             else
733                 first_nr = try_nr;
734
735             /* save the number */
736             new->val.status.num = try_nr;
737         }
738         else
739         {
740             if (outlevel >= O_DEBUG)
741                 report(stdout, GT_("%u is unseen\n"), try_nr);
742             last_nr = try_nr;
743
744             /* save it */
745             new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
746             new->val.status.num = try_nr;
747         }
748     }
749     if (outlevel >= O_DEBUG && last_nr <= count)
750         report(stdout, GT_("%u is first unseen\n"), last_nr);
751
752     /* update last! */
753     *newp = count - first_nr;
754     last = first_nr;
755     return 0;
756 }
757
758 static int pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
759 {
760     /* This approach tries to get the message headers from the
761      * remote hosts and compares the message-id to the already known
762      * ones:
763      *  + if the first message containes a new id, all messages on
764      *    the server will be new
765      *  + if the first is known, try to estimate the last known message
766      *    on the server and check. If this works you know the total number
767      *    of messages to get.
768      *  + Otherwise run a binary search to determine the last known message
769      */
770     int ok, nolinear = 0;
771     int first_nr, list_len, try_id, try_nr, add_id;
772     int num;
773     char id [IDLEN+1];
774
775     if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
776         return ok;
777
778     if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
779         /* the first message is unknown -> all messages are new */
780         *newp = *countp;        
781         return 0;
782     }
783
784     /* check where we expect the latest known message */
785     list_len = count_list( &ctl->oldsaved );
786     try_id = list_len  - first_nr; /* -1 + 1 */
787     if( try_id > 1 ) {
788         if( try_id <= *countp ) {
789             if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
790                 return ok;
791     
792             try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
793         } else {
794             try_id = *countp+1;
795             try_nr = -1;
796         }
797         if( try_nr != list_len -1 ) {
798             /* some messages inbetween have been deleted... */
799             if( try_nr == -1 ) {
800                 nolinear = 1;
801
802                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
803                     ;
804                 for( ; add_id; add_id >>= 1 ) {
805                     if( try_nr == -1 ) {
806                         if( try_id - add_id <= 1 ) {
807                             continue;
808                         }
809                         try_id -= add_id;
810                     } else 
811                         try_id += add_id;
812                     
813                     if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
814                         return ok;
815                     try_nr = str_nr_in_list(&ctl->oldsaved, id);
816                 }
817                 if( try_nr == -1 ) {
818                     try_id--;
819                 }
820             } else {
821                 report(stderr, 
822                        GT_("Messages inserted into list on server. Cannot handle this.\n"));
823                 return -1;
824             }
825         } 
826     }
827     /* the first try_id messages are known -> copy them to the newsaved list */
828     for( num = first_nr; num < list_len; num++ )
829     {
830         struct idlist   *new = save_str(&ctl->newsaved, 
831                                 str_from_nr_list(&ctl->oldsaved, num),
832                                 UID_UNSEEN);
833         new->val.status.num = num - first_nr + 1;
834     }
835
836     if( nolinear ) {
837         free_str_list(&ctl->oldsaved);
838         ctl->oldsaved = 0;
839         last = try_id;
840     }
841
842     *newp = *countp - try_id;
843     return 0;
844 }
845
846 static int pop3_getrange(int sock, 
847                          struct query *ctl,
848                          const char *folder,
849                          int *countp, int *newp, int *bytes)
850 /* get range of messages to be fetched */
851 {
852     int ok;
853     char buf [POPBUFSIZE+1];
854
855     /* Ensure that the new list is properly empty */
856     ctl->newsaved = (struct idlist *)NULL;
857
858 #ifdef MBOX
859     /* Alain Knaff suggests this, but it's not RFC standard */
860     if (folder)
861         if ((ok = gen_transact(sock, "MBOX %s", folder)))
862             return ok;
863 #endif /* MBOX */
864
865     /* get the total message count */
866     gen_send(sock, "STAT");
867     ok = pop3_ok(sock, buf);
868     if (ok == 0)
869         sscanf(buf,"%d %d", countp, bytes);
870     else
871         return(ok);
872
873     /*
874      * Newer, RFC-1725-conformant POP servers may not have the LAST command.
875      * We work as hard as possible to hide this ugliness, but it makes
876      * counting new messages intrinsically quadratic in the worst case.
877      */
878     last = 0;
879     *newp = -1;
880     if (*countp > 0 && !ctl->fetchall)
881     {
882         int fastuidl;
883         char id [IDLEN+1];
884
885         /* should we do fast uidl this time? */
886         fastuidl = ctl->fastuidl;
887         if (*countp > 7 &&              /* linear search is better if there are few mails! */
888             !ctl->flush &&              /* with flush, it is safer to disable fastuidl */
889             NUM_NONZERO (fastuidl))
890         {
891             if (fastuidl == 1)
892                 dofastuidl = 1;
893             else
894                 dofastuidl = ctl->fastuidlcount != 0;
895         }
896         else
897             dofastuidl = 0;
898
899         if (!ctl->server.uidl) {
900             gen_send(sock, "LAST");
901             ok = pop3_ok(sock, buf);
902         } else
903             ok = 1;
904         if (ok == 0)
905         {
906             if (sscanf(buf, "%d", &last) == 0)
907             {
908                 report(stderr, GT_("protocol error\n"));
909                 return(PS_ERROR);
910             }
911             *newp = (*countp - last);
912         }
913         else
914         {
915             if (dofastuidl)
916                 return(pop3_fastuidl( sock, ctl, *countp, newp));
917             /* grab the mailbox's UID list */
918             if ((ok = gen_transact(sock, "UIDL")) != 0)
919             {
920                 /* don't worry, yet! do it the slow way */
921                 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
922                 {
923                     report(stderr, GT_("protocol error while fetching UIDLs\n"));
924                     return(PS_ERROR);
925                 }
926             }
927             else
928             {
929                 unsigned long unum;
930
931                 *newp = 0;
932                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
933                 {
934                     if (DOTLINE(buf))
935                         break;
936
937                     if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
938                     {
939                         struct idlist   *old, *new;
940
941                         new = save_str(&ctl->newsaved, id, UID_UNSEEN);
942                         new->val.status.num = unum;
943
944                         if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
945                         {
946                             flag mark = old->val.status.mark;
947                             if (mark == UID_DELETED || mark == UID_EXPUNGED)
948                             {
949                                 /* XXX FIXME: switch 3 occurrences from
950                                  * (int)unum or (unsigned int)unum to
951                                  * remove the cast and use %lu - not now
952                                  * though, time for new release */
953                                 if (outlevel >= O_VERBOSE)
954                                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
955                                 /* just mark it as seen now! */
956                                 old->val.status.mark = mark = UID_SEEN;
957                             }
958                             new->val.status.mark = mark;
959                             if (mark == UID_UNSEEN)
960                             {
961                                 (*newp)++;
962                                 if (outlevel >= O_DEBUG)
963                                     report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
964                             }
965                         }
966                         else
967                         {
968                             (*newp)++;
969                             if (outlevel >= O_DEBUG)
970                                 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
971                             /* add it to oldsaved also! In case, we do not
972                              * swap the lists (say, due to socket error),
973                              * the same mail will not be downloaded again.
974                              */
975                             old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
976                             old->val.status.num = unum;
977                         }
978                     } else
979                         return PS_ERROR;
980                 }
981             }
982         }
983     }
984
985     return(PS_SUCCESS);
986 }
987
988 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
989 /* capture the size of message #first */
990 {
991     int ok = 0, i;
992     char buf [POPBUFSIZE+1];
993     unsigned int num, size;
994
995     for (i = first; i <= last; i++) {
996         gen_send(sock, "LIST %d", i);
997         if ((ok = pop3_ok(sock, buf)) != 0)
998             return(ok);
999         if (sscanf(buf, "%u %u", &num, &size) == 2) {
1000             if (num == i)
1001                 sizes[i - first] = size;
1002             else
1003                 /* warn about possible attempt to induce buffer overrun
1004                  *
1005                  * we expect server reply message number and requested
1006                  * message number to match */
1007                 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1008         }
1009     }
1010     return(ok);
1011 }
1012
1013 static int pop3_getsizes(int sock, int count, int *sizes)
1014 /* capture the sizes of all messages */
1015 {
1016     int ok;
1017
1018     if ((ok = gen_transact(sock, "LIST")) != 0)
1019         return(ok);
1020     else
1021     {
1022         char buf [POPBUFSIZE+1];
1023
1024         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1025         {
1026             unsigned int num, size;
1027
1028             if (DOTLINE(buf))
1029                 break;
1030             else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1031                 if (num > 0 && num <= count)
1032                     sizes[num - 1] = size;
1033                 else
1034                     /* warn about possible attempt to induce buffer overrun */
1035                     report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1036             }
1037         }
1038
1039         return(ok);
1040     }
1041 }
1042
1043 static int pop3_is_old(int sock, struct query *ctl, int num)
1044 /* is the given message old? */
1045 {
1046     struct idlist *new;
1047     if (!ctl->oldsaved)
1048         return (num <= last);
1049     else if (dofastuidl)
1050     {
1051         char id [IDLEN+1];
1052
1053         if (num <= last)
1054             return(TRUE);
1055
1056         /* in fast uidl, we manipulate the old list only! */
1057
1058         if ((new = id_find(&ctl->oldsaved, num)))
1059         {
1060             /* we already have the id! */
1061             return(new->val.status.mark != UID_UNSEEN);
1062         }
1063
1064         /* get the uidl first! */
1065         if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1066             return(TRUE);
1067
1068         if ((new = str_in_list(&ctl->oldsaved, id, FALSE))) {
1069             /* we already have the id! */
1070             new->val.status.num = num;
1071             return(new->val.status.mark != UID_UNSEEN);
1072         }
1073
1074         /* save it */
1075         new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1076         new->val.status.num = num;
1077         return(FALSE);
1078     }
1079     else
1080         return ((new = id_find(&ctl->newsaved, num)) != NULL &&
1081             new->val.status.mark != UID_UNSEEN);
1082 }
1083
1084 #ifdef UNUSED
1085 /*
1086  * We could use this to fetch headers only as we do for IMAP.  The trouble 
1087  * is that there's no way to fetch the body only.  So the following RETR 
1088  * would have to re-fetch the header.  Enough messages have longer headers
1089  * than bodies to make this a net loss.
1090  */
1091 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1092 /* request headers of nth message */
1093 {
1094     int ok;
1095     char buf[POPBUFSIZE+1];
1096
1097     gen_send(sock, "TOP %d 0", number);
1098     if ((ok = pop3_ok(sock, buf)) != 0)
1099         return(ok);
1100
1101     *lenp = -1;         /* we got sizes from the LIST response */
1102
1103     return(PS_SUCCESS);
1104 }
1105 #endif /* UNUSED */
1106
1107 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1108 /* request nth message */
1109 {
1110     int ok;
1111     char buf[POPBUFSIZE+1];
1112
1113 #ifdef SDPS_ENABLE
1114     /*
1115      * See http://www.demon.net/services/mail/sdps-tech.html
1116      * for a description of what we're parsing here.
1117      */
1118     if (ctl->server.sdps)
1119     {
1120         int     linecount = 0;
1121
1122         sdps_envfrom = (char *)NULL;
1123         sdps_envto = (char *)NULL;
1124         gen_send(sock, "*ENV %d", number);
1125         do {
1126             if (gen_recv(sock, buf, sizeof(buf)))
1127             {
1128                 break;
1129             }
1130             linecount++;
1131             switch (linecount) {
1132             case 4:
1133                 /* No need to wrap envelope from address */
1134                 sdps_envfrom = xmalloc(strlen(buf)+1);
1135                 strcpy(sdps_envfrom,buf);
1136                 break;
1137             case 5:
1138                 /* Wrap address with To: <> so nxtaddr() likes it */
1139                 sdps_envto = xmalloc(strlen(buf)+7);
1140                 sprintf(sdps_envto,"To: <%s>",buf);
1141                 break;
1142             }
1143         } while
1144             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1145     }
1146 #endif /* SDPS_ENABLE */
1147
1148     /*
1149      * Though the POP RFCs don't document this fact, on almost every
1150      * POP3 server I know of messages are marked "seen" only at the
1151      * time the OK response to a RETR is issued.
1152      *
1153      * This means we can use TOP to fetch the message without setting its
1154      * seen flag.  This is good!  It means that if the protocol exchange
1155      * craps out during the message, it will still be marked `unseen' on
1156      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
1157      * reported to mark messages seen on a TOP fetch.)
1158      *
1159      * However...*don't* do this if we're using keep to suppress deletion!
1160      * In that case, marking the seen flag is the only way to prevent the
1161      * message from being re-fetched on subsequent runs.
1162      *
1163      * Also use RETR (that means no TOP, no peek) if fetchall is on.
1164      * This gives us a workaround for servers like usa.net's that bungle
1165      * TOP.  It's pretty harmless because fetchall guarantees that any
1166      * message dropped by an interrupted RETR will be picked up on the
1167      * next poll of the site.
1168      *
1169      * We take advantage here of the fact that, according to all the
1170      * POP RFCs, "if the number of lines requested by the POP3 client
1171      * is greater than than the number of lines in the body, then the
1172      * POP3 server sends the entire message.").
1173      *
1174      * The line count passed (99999999) is the maximum value CompuServe will
1175      * accept; it's much lower than the natural value 2147483646 (the maximum
1176      * twos-complement signed 32-bit integer minus 1) */
1177     if (!peek_capable)
1178         gen_send(sock, "RETR %d", number);
1179     else
1180         gen_send(sock, "TOP %d 99999999", number);
1181     if ((ok = pop3_ok(sock, buf)) != 0)
1182         return(ok);
1183
1184     *lenp = -1;         /* we got sizes from the LIST response */
1185
1186     return(PS_SUCCESS);
1187 }
1188
1189 static void mark_uid_seen(struct query *ctl, int number)
1190 /* Tell the UID code we've seen this. */
1191 {
1192     struct idlist       *sdp;
1193
1194     if ((sdp = id_find(&ctl->newsaved, number)))
1195         sdp->val.status.mark = UID_SEEN;
1196     /* mark it as seen in oldsaved also! In case, we do not swap the lists
1197      * (say, due to socket error), the same mail will not be downloaded
1198      * again.
1199      */
1200     if ((sdp = id_find(&ctl->oldsaved, number)))
1201         sdp->val.status.mark = UID_SEEN;
1202 }
1203
1204 static int pop3_delete(int sock, struct query *ctl, int number)
1205 /* delete a given message */
1206 {
1207     int ok;
1208     mark_uid_seen(ctl, number);
1209     /* actually, mark for deletion -- doesn't happen until QUIT time */
1210     ok = gen_transact(sock, "DELE %d", number);
1211     if (ok != PS_SUCCESS)
1212         return(ok);
1213     delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1214     return(PS_SUCCESS);
1215 }
1216
1217 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1218 /* mark a given message as seen */
1219 {
1220     mark_uid_seen(ctl, number);
1221     return(PS_SUCCESS);
1222 }
1223
1224 static int pop3_logout(int sock, struct query *ctl)
1225 /* send logout command */
1226 {
1227     int ok;
1228
1229 #ifdef __UNUSED__
1230     /*
1231      * We used to do this in case the server marks messages deleted when seen.
1232      * (Yes, this has been reported, in the MercuryP/NLM server.
1233      * It's even legal under RFC 1939 (section 8) as a site policy.)
1234      * It interacted badly with UIDL, though.  Thomas Zajic wrote:
1235      * "Running 'fetchmail -F -v' and checking the logs, I found out
1236      * that fetchmail did in fact flush my mailbox properly, but sent
1237      * a RSET just before sending QUIT to log off.  This caused the
1238      * POP3 server to undo/forget about the previous DELEs, resetting
1239      * my mailbox to its original (ie.  unflushed) state. The
1240      * ~/.fetchids file did get flushed though, so the next time
1241      * fetchmail was run it saw all the old messages as new ones ..."
1242      */
1243      if (ctl->keep)
1244         gen_transact(sock, "RSET");
1245 #endif /* __UNUSED__ */
1246
1247     ok = gen_transact(sock, "QUIT");
1248     if (!ok)
1249         expunge_uids(ctl);
1250
1251     return(ok);
1252 }
1253
1254 static const struct method pop3 =
1255 {
1256     "POP3",             /* Post Office Protocol v3 */
1257     "pop3",             /* standard POP3 port */
1258     "pop3s",            /* ssl POP3 port */
1259     FALSE,              /* this is not a tagged protocol */
1260     TRUE,               /* this uses a message delimiter */
1261     pop3_ok,            /* parse command response */
1262     pop3_getauth,       /* get authorization */
1263     pop3_getrange,      /* query range of messages */
1264     pop3_getsizes,      /* we can get a list of sizes */
1265     pop3_getpartialsizes,       /* we can get the size of 1 mail */
1266     pop3_is_old,        /* how do we tell a message is old? */
1267     pop3_fetch,         /* request given message */
1268     NULL,               /* no way to fetch body alone */
1269     NULL,               /* no message trailer */
1270     pop3_delete,        /* how to delete a message */
1271     pop3_mark_seen,     /* how to mark a message as seen */
1272     NULL,               /* no action at end of mailbox */
1273     pop3_logout,        /* log out, we're done */
1274     FALSE,              /* no, we can't re-poll */
1275 };
1276
1277 int doPOP3 (struct query *ctl)
1278 /* retrieve messages using POP3 */
1279 {
1280 #ifndef MBOX
1281     if (ctl->mailboxes->id) {
1282         fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1283         return(PS_SYNTAX);
1284     }
1285 #endif /* MBOX */
1286     set_peek_capable(ctl); /* XXX FIXME: is this needed or do we always
1287                               call this from pop3_getauth anyways? */
1288     return(do_protocol(ctl, &pop3));
1289 }
1290 #endif /* POP3_ENABLE */
1291
1292 /* pop3.c ends here */