]> Pileus Git - ~andy/fetchmail/blob - pop3.c
Clarify Maillennium workaround warning even more (...instead of TOP).
[~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     /* Set this up before authentication quits early. */
317     set_peek_capable(ctl);
318     /*
319      * The "Maillennium POP3/PROXY server" deliberately truncates
320      * TOP replies after c. 64 or 80 kByte (we have varying reports), so
321      * disable TOP. Comcast once spewed marketing babble to the extent
322      * of protecting Outlook -- pretty overzealous to break a protocol
323      * for that that Microsoft could have read, too. Comcast aren't
324      * alone in using this software though.
325      * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
326      * (Thanks to Ed Wilts for reminding me of that.)
327      *
328      * The warning is printed once per server, until fetchmail exits.
329      * It will be suppressed when --fetchall or other circumstances make
330      * us use RETR anyhow.
331      *
332      * Matthias Andree
333      */
334     if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
335         if ((ctl->server.workarounds & WKA_TOP) == 0) {
336             report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
337             ctl->server.workarounds |= WKA_TOP;
338         }
339         peek_capable = 0;
340     }
341     if (ctl->server.authenticate == A_SSH) {
342         return PS_SUCCESS;
343     }
344
345 #ifdef SDPS_ENABLE
346     /*
347      * This needs to catch both demon.co.uk and demon.net.
348      * If we see either, and we're in multidrop mode, try to use
349      * the SDPS *ENV extension.
350      */
351     if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
352         ctl->server.sdps = TRUE;
353 #endif /* SDPS_ENABLE */
354
355 #ifdef NTLM_ENABLE
356     /* MSN servers require the use of NTLM (MSN) authentication */
357     if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
358             ctl->server.authenticate == A_MSN)
359         return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
360     if (ctl->server.authenticate == A_NTLM)
361         return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
362 #else
363     if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
364     {
365         report(stderr,
366            GT_("Required NTLM capability not compiled into fetchmail\n"));
367     }
368 #endif
369
370     switch (ctl->server.protocol) {
371     case P_POP3:
372 #ifdef RPA_ENABLE
373         /* XXX FIXME: AUTH probing (RFC1734) should become global */
374         /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
375         if (strstr(ctl->remotename, "@compuserve.com"))
376         {
377             /* AUTH command should return a list of available mechanisms */
378             if (gen_transact(sock, "AUTH") == 0)
379             {
380                 char buffer[10];
381                 flag has_rpa = FALSE;
382
383                 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
384                 {
385                     if (DOTLINE(buffer))
386                         break;
387                     if (strncasecmp(buffer, "rpa", 3) == 0)
388                         has_rpa = TRUE;
389                 }
390                 if (has_rpa && !POP3_auth_rpa(ctl->remotename, 
391                                               ctl->password, sock))
392                     return(PS_SUCCESS);
393             }
394
395             return(PS_AUTHFAIL);
396         }
397 #endif /* RPA_ENABLE */
398
399         /*
400          * CAPA command may return a list including available
401          * authentication mechanisms.  if it doesn't, no harm done, we
402          * just fall back to a plain login.  Note that this code 
403          * latches the server's authentication type, so that in daemon mode
404          * the CAPA check only needs to be done once at start of run.
405          *
406          * If CAPA fails, then force the authentication method to PASSORD
407          * and repoll immediately.
408          *
409          * These authentication methods are blessed by RFC1734,
410          * describing the POP3 AUTHentication command.
411          */
412         if ((ctl->server.authenticate == A_ANY) ||
413             (ctl->server.authenticate == A_GSSAPI) ||
414             (ctl->server.authenticate == A_KERBEROS_V4) ||
415             (ctl->server.authenticate == A_OTP) ||
416             (ctl->server.authenticate == A_CRAM_MD5))
417         {
418             if ((ok = capa_probe(sock)) != PS_SUCCESS)
419             /* we are in STAGE_GETAUTH! */
420                 if (ok == PS_AUTHFAIL ||
421                     /* Some servers directly close the socket. However, if we
422                      * have already authenticated before, then a previous CAPA
423                      * must have succeeded. In that case, treat this as a
424                      * genuine socket error and do not change the auth method.
425                      */
426                     (ok == PS_SOCKET && !ctl->wehaveauthed))
427                 {
428                     ctl->server.authenticate = A_PASSWORD;
429                     /* repoll immediately */
430                     ok = PS_REPOLL;
431                     break;
432                 }
433         }
434
435 #ifdef SSL_ENABLE
436         if (has_ssl
437             && !ctl->use_ssl
438             && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
439         {
440             char *realhost;
441
442            realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
443            ok = gen_transact(sock, "STLS");
444
445            /* We use "tls1" instead of ctl->sslproto, as we want STLS,
446             * not other SSL protocols
447             */
448            if (ok == PS_SUCCESS &&
449                SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
450            {
451                if (!ctl->sslproto && !ctl->wehaveauthed)
452                {
453                    ctl->sslproto = xstrdup("");
454                    /* repoll immediately */
455                    return(PS_REPOLL);
456                }
457                report(stderr,
458                        GT_("SSL connection failed.\n"));
459                 return PS_SOCKET;
460             }
461            did_stls = TRUE;
462
463            /*
464             * RFC 2595 says this:
465             *
466             * "Once TLS has been started, the client MUST discard cached
467             * information about server capabilities and SHOULD re-issue the
468             * CAPABILITY command.  This is necessary to protect against
469             * man-in-the-middle attacks which alter the capabilities list prior
470             * to STARTTLS.  The server MAY advertise different capabilities
471             * after STARTTLS."
472             */
473            capa_probe(sock);
474         }
475 #endif /* SSL_ENABLE */
476
477         /*
478          * OK, we have an authentication type now.
479          */
480 #if defined(KERBEROS_V4)
481         /* 
482          * Servers doing KPOP have to go through a dummy login sequence
483          * rather than doing SASL.
484          */
485         if (has_kerberos &&
486             ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
487             && (ctl->server.authenticate == A_KERBEROS_V4
488              || ctl->server.authenticate == A_KERBEROS_V5
489              || ctl->server.authenticate == A_ANY))
490         {
491             ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
492             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
493                 break;
494         }
495 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
496
497 #if defined(GSSAPI)
498         if (has_gssapi &&
499             (ctl->server.authenticate == A_GSSAPI ||
500              ctl->server.authenticate == A_ANY))
501         {
502             ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
503             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
504                 break;
505         }
506 #endif /* defined(GSSAPI) */
507
508 #ifdef OPIE_ENABLE
509         if (has_otp &&
510             (ctl->server.authenticate == A_OTP ||
511              ctl->server.authenticate == A_ANY))
512         {
513             ok = do_otp(sock, "AUTH", ctl);
514             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
515                 break;
516         }
517 #endif /* OPIE_ENABLE */
518
519         if (ctl->server.authenticate == A_CRAM_MD5 || 
520             (has_cram && ctl->server.authenticate == A_ANY))
521         {
522             ok = do_cram_md5(sock, "AUTH", ctl, NULL);
523             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
524                 break;
525         }
526
527         /* ordinary validation, no one-time password or RPA */ 
528         if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
529             break;
530
531 #ifdef OPIE_ENABLE
532         /* see RFC1938: A One-Time Password System */
533         if ((challenge = strstr(lastok, "otp-"))) {
534           char response[OPIE_RESPONSE_MAX+1];
535           int i;
536
537           i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
538           if ((i == -2) && !run.poll_interval) {
539             char secret[OPIE_SECRET_MAX+1];
540             fprintf(stderr, GT_("Secret pass phrase: "));
541             if (opiereadpass(secret, sizeof(secret), 0))
542               i = opiegenerator(challenge,  secret, response);
543             memset(secret, 0, sizeof(secret));
544           };
545
546           if (i) {
547             ok = PS_ERROR;
548             break;
549           };
550
551           ok = gen_transact(sock, "PASS %s", response);
552           break;
553         }
554 #endif /* OPIE_ENABLE */
555
556         strlcpy(shroud, ctl->password, sizeof(shroud));
557         ok = gen_transact(sock, "PASS %s", ctl->password);
558         shroud[0] = '\0';
559 #ifdef SSL_ENABLE
560         /* this is for servers which claim to support TLS, but actually
561          * don't! */
562         if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
563         {
564             ctl->sslproto = xstrdup("");
565             /* repoll immediately */
566             ok = PS_REPOLL;
567         }
568 #endif
569         break;
570
571     case P_APOP:
572         /* build MD5 digest from greeting timestamp + password */
573         /* find start of timestamp */
574         for (start = greeting;  *start != 0 && *start != '<';  start++)
575             continue;
576         if (*start == 0) {
577             report(stderr,
578                    GT_("Required APOP timestamp not found in greeting\n"));
579             return(PS_AUTHFAIL);
580         }
581
582         /* find end of timestamp */
583         for (end = start;  *end != 0  && *end != '>';  end++)
584             continue;
585         if (*end == 0 || end == start + 1) {
586             report(stderr, 
587                    GT_("Timestamp syntax error in greeting\n"));
588             return(PS_AUTHFAIL);
589         }
590         else
591             *++end = '\0';
592
593         /* copy timestamp and password into digestion buffer */
594         msg = xmalloc((end-start+1) + strlen(ctl->password) + 1);
595         strcpy(msg,start);
596         strcat(msg,ctl->password);
597         strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
598         free(msg);
599
600         ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
601         break;
602
603     case P_RPOP:
604         if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
605             ok = gen_transact(sock, "RPOP %s", ctl->password);
606         break;
607
608     default:
609         report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
610         ok = PS_ERROR;
611     }
612
613     if (ok != 0)
614     {
615         /* maybe we detected a lock-busy condition? */
616         if (ok == PS_LOCKBUSY)
617             report(stderr, GT_("lock busy!  Is another session active?\n")); 
618
619         return(ok);
620     }
621
622 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
623  * accepted by Matthias Andree.
624  *
625  * Rationale: the server must have locked the spool before returning +OK;
626  * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
627 #ifdef WANT_BOGUS
628     /*
629      * Empirical experience shows some server/OS combinations
630      * may need a brief pause even after any lockfiles on the
631      * server are released, to give the server time to finish
632      * copying back very large mailfolders from the temp-file...
633      * this is only ever an issue with extremely large mailboxes.
634      */
635     sleep(3); /* to be _really_ safe, probably need sleep(5)! */
636 #endif
637
638     /* we're approved */
639     return(PS_SUCCESS);
640 }
641
642 /* cut off C string at first POSIX space */
643 static void trim(char *s) {
644     s += strcspn(s, POSIX_space);
645     s[0] = '\0';
646 }
647
648 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
649 {
650     int ok;
651     int got_it;
652     char buf [POPBUFSIZE+1];
653     snprintf(buf, sizeof(buf), "TOP %d 1", num);
654     if ((ok = gen_transact(sock, buf )) != 0)
655        return ok;
656     got_it = 0;
657     while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0) 
658     {
659         if (DOTLINE(buf))
660             break;
661         if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
662             char *p = buf + 11;
663             got_it = 1;
664             p += strspn(p, POSIX_space);
665             strlcpy(id, p, idsize);
666             trim(id);
667         }
668     }
669     return 0;
670 }
671
672 /** Parse the UID response (leading +OK must have been
673  * stripped off) in buf, store the number in gotnum, and store the ID
674  * into the caller-provided buffer "id" of size "idsize".
675  * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
676 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
677 {
678     const char *i;
679     char *j;
680
681     /* skip leading blanks ourselves */
682     i = buf;
683     i += strspn(i, POSIX_space);
684     errno = 0;
685     *gotnum = strtoul(i, &j, 10);
686     if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
687         report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
688         return PS_PROTOCOL;
689     }
690     j += strspn(j, POSIX_space);
691     strlcpy(id, j, idsize);
692     trim(id);
693     return PS_SUCCESS;
694 }
695
696 /** request UIDL for single message \a num and stuff the result into the
697  * buffer \a id which can hold \a idsize bytes */
698 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
699 {
700     int ok;
701     char buf [POPBUFSIZE+1];
702     unsigned long gotnum;
703
704     gen_send(sock, "UIDL %d", num);
705     if ((ok = pop3_ok(sock, buf)) != 0)
706         return(ok);
707     if ((ok = parseuid(buf, &gotnum, id, idsize)))
708         return ok;
709     if (gotnum != num) {
710         report(stderr, GT_("Server responded with UID for wrong message.\n"));
711         return PS_PROTOCOL;
712     }
713     return(PS_SUCCESS);
714 }
715
716 static int pop3_fastuidl( int sock,  struct query *ctl, unsigned int count, int *newp)
717 {
718     int ok;
719     unsigned int first_nr, last_nr, try_nr;
720     char id [IDLEN+1];
721
722     first_nr = 0;
723     last_nr = count + 1;
724     while (first_nr < last_nr - 1)
725     {
726         struct idlist   *new;
727
728         try_nr = (first_nr + last_nr) / 2;
729         if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
730             return ok;
731         if ((new = str_in_list(&ctl->oldsaved, id, FALSE)))
732         {
733             flag mark = new->val.status.mark;
734             if (mark == UID_DELETED || mark == UID_EXPUNGED)
735             {
736                 if (outlevel >= O_VERBOSE)
737                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
738                 /* just mark it as seen now! */
739                 new->val.status.mark = mark = UID_SEEN;
740             }
741
742             /* narrow the search region! */
743             if (mark == UID_UNSEEN)
744             {
745                 if (outlevel >= O_DEBUG)
746                     report(stdout, GT_("%u is unseen\n"), try_nr);
747                 last_nr = try_nr;
748             }
749             else
750                 first_nr = try_nr;
751
752             /* save the number */
753             new->val.status.num = try_nr;
754         }
755         else
756         {
757             if (outlevel >= O_DEBUG)
758                 report(stdout, GT_("%u is unseen\n"), try_nr);
759             last_nr = try_nr;
760
761             /* save it */
762             new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
763             new->val.status.num = try_nr;
764         }
765     }
766     if (outlevel >= O_DEBUG && last_nr <= count)
767         report(stdout, GT_("%u is first unseen\n"), last_nr);
768
769     /* update last! */
770     *newp = count - first_nr;
771     last = first_nr;
772     return 0;
773 }
774
775 static int pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
776 {
777     /* This approach tries to get the message headers from the
778      * remote hosts and compares the message-id to the already known
779      * ones:
780      *  + if the first message containes a new id, all messages on
781      *    the server will be new
782      *  + if the first is known, try to estimate the last known message
783      *    on the server and check. If this works you know the total number
784      *    of messages to get.
785      *  + Otherwise run a binary search to determine the last known message
786      */
787     int ok, nolinear = 0;
788     int first_nr, list_len, try_id, try_nr, add_id;
789     int num;
790     char id [IDLEN+1];
791
792     if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
793         return ok;
794
795     if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
796         /* the first message is unknown -> all messages are new */
797         *newp = *countp;        
798         return 0;
799     }
800
801     /* check where we expect the latest known message */
802     list_len = count_list( &ctl->oldsaved );
803     try_id = list_len  - first_nr; /* -1 + 1 */
804     if( try_id > 1 ) {
805         if( try_id <= *countp ) {
806             if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
807                 return ok;
808     
809             try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
810         } else {
811             try_id = *countp+1;
812             try_nr = -1;
813         }
814         if( try_nr != list_len -1 ) {
815             /* some messages inbetween have been deleted... */
816             if( try_nr == -1 ) {
817                 nolinear = 1;
818
819                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
820                     ;
821                 for( ; add_id; add_id >>= 1 ) {
822                     if( try_nr == -1 ) {
823                         if( try_id - add_id <= 1 ) {
824                             continue;
825                         }
826                         try_id -= add_id;
827                     } else 
828                         try_id += add_id;
829                     
830                     if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
831                         return ok;
832                     try_nr = str_nr_in_list(&ctl->oldsaved, id);
833                 }
834                 if( try_nr == -1 ) {
835                     try_id--;
836                 }
837             } else {
838                 report(stderr, 
839                        GT_("Messages inserted into list on server. Cannot handle this.\n"));
840                 return -1;
841             }
842         } 
843     }
844     /* the first try_id messages are known -> copy them to the newsaved list */
845     for( num = first_nr; num < list_len; num++ )
846     {
847         struct idlist   *new = save_str(&ctl->newsaved, 
848                                 str_from_nr_list(&ctl->oldsaved, num),
849                                 UID_UNSEEN);
850         new->val.status.num = num - first_nr + 1;
851     }
852
853     if( nolinear ) {
854         free_str_list(&ctl->oldsaved);
855         ctl->oldsaved = 0;
856         last = try_id;
857     }
858
859     *newp = *countp - try_id;
860     return 0;
861 }
862
863 static int pop3_getrange(int sock, 
864                          struct query *ctl,
865                          const char *folder,
866                          int *countp, int *newp, int *bytes)
867 /* get range of messages to be fetched */
868 {
869     int ok;
870     char buf [POPBUFSIZE+1];
871
872     /* Ensure that the new list is properly empty */
873     ctl->newsaved = (struct idlist *)NULL;
874
875 #ifdef MBOX
876     /* Alain Knaff suggests this, but it's not RFC standard */
877     if (folder)
878         if ((ok = gen_transact(sock, "MBOX %s", folder)))
879             return ok;
880 #endif /* MBOX */
881
882     /* get the total message count */
883     gen_send(sock, "STAT");
884     ok = pop3_ok(sock, buf);
885     if (ok == 0)
886         sscanf(buf,"%d %d", countp, bytes);
887     else
888         return(ok);
889
890     /*
891      * Newer, RFC-1725-conformant POP servers may not have the LAST command.
892      * We work as hard as possible to hide this ugliness, but it makes
893      * counting new messages intrinsically quadratic in the worst case.
894      */
895     last = 0;
896     *newp = -1;
897     if (*countp > 0 && !ctl->fetchall)
898     {
899         int fastuidl;
900         char id [IDLEN+1];
901
902         /* should we do fast uidl this time? */
903         fastuidl = ctl->fastuidl;
904         if (*countp > 7 &&              /* linear search is better if there are few mails! */
905             !ctl->flush &&              /* with flush, it is safer to disable fastuidl */
906             NUM_NONZERO (fastuidl))
907         {
908             if (fastuidl == 1)
909                 dofastuidl = 1;
910             else
911                 dofastuidl = ctl->fastuidlcount != 0;
912         }
913         else
914             dofastuidl = 0;
915
916         if (!ctl->server.uidl) {
917             gen_send(sock, "LAST");
918             ok = pop3_ok(sock, buf);
919         } else
920             ok = 1;
921         if (ok == 0)
922         {
923             if (sscanf(buf, "%d", &last) == 0)
924             {
925                 report(stderr, GT_("protocol error\n"));
926                 return(PS_ERROR);
927             }
928             *newp = (*countp - last);
929         }
930         else
931         {
932             if (dofastuidl)
933                 return(pop3_fastuidl( sock, ctl, *countp, newp));
934             /* grab the mailbox's UID list */
935             if ((ok = gen_transact(sock, "UIDL")) != 0)
936             {
937                 /* don't worry, yet! do it the slow way */
938                 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
939                 {
940                     report(stderr, GT_("protocol error while fetching UIDLs\n"));
941                     return(PS_ERROR);
942                 }
943             }
944             else
945             {
946                 unsigned long unum;
947
948                 *newp = 0;
949                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
950                 {
951                     if (DOTLINE(buf))
952                         break;
953
954                     if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
955                     {
956                         struct idlist   *old, *new;
957
958                         new = save_str(&ctl->newsaved, id, UID_UNSEEN);
959                         new->val.status.num = unum;
960
961                         if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
962                         {
963                             flag mark = old->val.status.mark;
964                             if (mark == UID_DELETED || mark == UID_EXPUNGED)
965                             {
966                                 /* XXX FIXME: switch 3 occurrences from
967                                  * (int)unum or (unsigned int)unum to
968                                  * remove the cast and use %lu - not now
969                                  * though, time for new release */
970                                 if (outlevel >= O_VERBOSE)
971                                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
972                                 /* just mark it as seen now! */
973                                 old->val.status.mark = mark = UID_SEEN;
974                             }
975                             new->val.status.mark = mark;
976                             if (mark == UID_UNSEEN)
977                             {
978                                 (*newp)++;
979                                 if (outlevel >= O_DEBUG)
980                                     report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
981                             }
982                         }
983                         else
984                         {
985                             (*newp)++;
986                             if (outlevel >= O_DEBUG)
987                                 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
988                             /* add it to oldsaved also! In case, we do not
989                              * swap the lists (say, due to socket error),
990                              * the same mail will not be downloaded again.
991                              */
992                             old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
993                             old->val.status.num = unum;
994                         }
995                     } else
996                         return PS_ERROR;
997                 }
998             }
999         }
1000     }
1001
1002     return(PS_SUCCESS);
1003 }
1004
1005 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1006 /* capture the size of message #first */
1007 {
1008     int ok = 0, i;
1009     char buf [POPBUFSIZE+1];
1010     unsigned int num, size;
1011
1012     for (i = first; i <= last; i++) {
1013         gen_send(sock, "LIST %d", i);
1014         if ((ok = pop3_ok(sock, buf)) != 0)
1015             return(ok);
1016         if (sscanf(buf, "%u %u", &num, &size) == 2) {
1017             if (num == i)
1018                 sizes[i - first] = size;
1019             else
1020                 /* warn about possible attempt to induce buffer overrun
1021                  *
1022                  * we expect server reply message number and requested
1023                  * message number to match */
1024                 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1025         }
1026     }
1027     return(ok);
1028 }
1029
1030 static int pop3_getsizes(int sock, int count, int *sizes)
1031 /* capture the sizes of all messages */
1032 {
1033     int ok;
1034
1035     if ((ok = gen_transact(sock, "LIST")) != 0)
1036         return(ok);
1037     else
1038     {
1039         char buf [POPBUFSIZE+1];
1040
1041         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1042         {
1043             unsigned int num, size;
1044
1045             if (DOTLINE(buf))
1046                 break;
1047             else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1048                 if (num > 0 && num <= count)
1049                     sizes[num - 1] = size;
1050                 else
1051                     /* warn about possible attempt to induce buffer overrun */
1052                     report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1053             }
1054         }
1055
1056         return(ok);
1057     }
1058 }
1059
1060 static int pop3_is_old(int sock, struct query *ctl, int num)
1061 /* is the given message old? */
1062 {
1063     struct idlist *new;
1064     if (!ctl->oldsaved)
1065         return (num <= last);
1066     else if (dofastuidl)
1067     {
1068         char id [IDLEN+1];
1069
1070         if (num <= last)
1071             return(TRUE);
1072
1073         /* in fast uidl, we manipulate the old list only! */
1074
1075         if ((new = id_find(&ctl->oldsaved, num)))
1076         {
1077             /* we already have the id! */
1078             return(new->val.status.mark != UID_UNSEEN);
1079         }
1080
1081         /* get the uidl first! */
1082         if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1083             return(TRUE);
1084
1085         if ((new = str_in_list(&ctl->oldsaved, id, FALSE))) {
1086             /* we already have the id! */
1087             new->val.status.num = num;
1088             return(new->val.status.mark != UID_UNSEEN);
1089         }
1090
1091         /* save it */
1092         new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1093         new->val.status.num = num;
1094         return(FALSE);
1095     }
1096     else
1097         return ((new = id_find(&ctl->newsaved, num)) != NULL &&
1098             new->val.status.mark != UID_UNSEEN);
1099 }
1100
1101 #ifdef UNUSED
1102 /*
1103  * We could use this to fetch headers only as we do for IMAP.  The trouble 
1104  * is that there's no way to fetch the body only.  So the following RETR 
1105  * would have to re-fetch the header.  Enough messages have longer headers
1106  * than bodies to make this a net loss.
1107  */
1108 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1109 /* request headers of nth message */
1110 {
1111     int ok;
1112     char buf[POPBUFSIZE+1];
1113
1114     gen_send(sock, "TOP %d 0", number);
1115     if ((ok = pop3_ok(sock, buf)) != 0)
1116         return(ok);
1117
1118     *lenp = -1;         /* we got sizes from the LIST response */
1119
1120     return(PS_SUCCESS);
1121 }
1122 #endif /* UNUSED */
1123
1124 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1125 /* request nth message */
1126 {
1127     int ok;
1128     char buf[POPBUFSIZE+1];
1129
1130 #ifdef SDPS_ENABLE
1131     /*
1132      * See http://www.demon.net/services/mail/sdps-tech.html
1133      * for a description of what we're parsing here.
1134      */
1135     if (ctl->server.sdps)
1136     {
1137         int     linecount = 0;
1138
1139         sdps_envfrom = (char *)NULL;
1140         sdps_envto = (char *)NULL;
1141         gen_send(sock, "*ENV %d", number);
1142         do {
1143             if (gen_recv(sock, buf, sizeof(buf)))
1144             {
1145                 break;
1146             }
1147             linecount++;
1148             switch (linecount) {
1149             case 4:
1150                 /* No need to wrap envelope from address */
1151                 sdps_envfrom = xmalloc(strlen(buf)+1);
1152                 strcpy(sdps_envfrom,buf);
1153                 break;
1154             case 5:
1155                 /* Wrap address with To: <> so nxtaddr() likes it */
1156                 sdps_envto = xmalloc(strlen(buf)+7);
1157                 sprintf(sdps_envto,"To: <%s>",buf);
1158                 break;
1159             }
1160         } while
1161             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1162     }
1163 #endif /* SDPS_ENABLE */
1164
1165     /*
1166      * Though the POP RFCs don't document this fact, on almost every
1167      * POP3 server I know of messages are marked "seen" only at the
1168      * time the OK response to a RETR is issued.
1169      *
1170      * This means we can use TOP to fetch the message without setting its
1171      * seen flag.  This is good!  It means that if the protocol exchange
1172      * craps out during the message, it will still be marked `unseen' on
1173      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
1174      * reported to mark messages seen on a TOP fetch.)
1175      *
1176      * However...*don't* do this if we're using keep to suppress deletion!
1177      * In that case, marking the seen flag is the only way to prevent the
1178      * message from being re-fetched on subsequent runs.
1179      *
1180      * Also use RETR (that means no TOP, no peek) if fetchall is on.
1181      * This gives us a workaround for servers like usa.net's that bungle
1182      * TOP.  It's pretty harmless because fetchall guarantees that any
1183      * message dropped by an interrupted RETR will be picked up on the
1184      * next poll of the site.
1185      *
1186      * We take advantage here of the fact that, according to all the
1187      * POP RFCs, "if the number of lines requested by the POP3 client
1188      * is greater than than the number of lines in the body, then the
1189      * POP3 server sends the entire message.").
1190      *
1191      * The line count passed (99999999) is the maximum value CompuServe will
1192      * accept; it's much lower than the natural value 2147483646 (the maximum
1193      * twos-complement signed 32-bit integer minus 1) */
1194     if (!peek_capable)
1195         gen_send(sock, "RETR %d", number);
1196     else
1197         gen_send(sock, "TOP %d 99999999", number);
1198     if ((ok = pop3_ok(sock, buf)) != 0)
1199         return(ok);
1200
1201     *lenp = -1;         /* we got sizes from the LIST response */
1202
1203     return(PS_SUCCESS);
1204 }
1205
1206 static void mark_uid_seen(struct query *ctl, int number)
1207 /* Tell the UID code we've seen this. */
1208 {
1209     struct idlist       *sdp;
1210
1211     if ((sdp = id_find(&ctl->newsaved, number)))
1212         sdp->val.status.mark = UID_SEEN;
1213     /* mark it as seen in oldsaved also! In case, we do not swap the lists
1214      * (say, due to socket error), the same mail will not be downloaded
1215      * again.
1216      */
1217     if ((sdp = id_find(&ctl->oldsaved, number)))
1218         sdp->val.status.mark = UID_SEEN;
1219 }
1220
1221 static int pop3_delete(int sock, struct query *ctl, int number)
1222 /* delete a given message */
1223 {
1224     int ok;
1225     mark_uid_seen(ctl, number);
1226     /* actually, mark for deletion -- doesn't happen until QUIT time */
1227     ok = gen_transact(sock, "DELE %d", number);
1228     if (ok != PS_SUCCESS)
1229         return(ok);
1230     delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1231     return(PS_SUCCESS);
1232 }
1233
1234 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1235 /* mark a given message as seen */
1236 {
1237     mark_uid_seen(ctl, number);
1238     return(PS_SUCCESS);
1239 }
1240
1241 static int pop3_logout(int sock, struct query *ctl)
1242 /* send logout command */
1243 {
1244     int ok;
1245
1246 #ifdef __UNUSED__
1247     /*
1248      * We used to do this in case the server marks messages deleted when seen.
1249      * (Yes, this has been reported, in the MercuryP/NLM server.
1250      * It's even legal under RFC 1939 (section 8) as a site policy.)
1251      * It interacted badly with UIDL, though.  Thomas Zajic wrote:
1252      * "Running 'fetchmail -F -v' and checking the logs, I found out
1253      * that fetchmail did in fact flush my mailbox properly, but sent
1254      * a RSET just before sending QUIT to log off.  This caused the
1255      * POP3 server to undo/forget about the previous DELEs, resetting
1256      * my mailbox to its original (ie.  unflushed) state. The
1257      * ~/.fetchids file did get flushed though, so the next time
1258      * fetchmail was run it saw all the old messages as new ones ..."
1259      */
1260      if (ctl->keep)
1261         gen_transact(sock, "RSET");
1262 #endif /* __UNUSED__ */
1263
1264     ok = gen_transact(sock, "QUIT");
1265     if (!ok)
1266         expunge_uids(ctl);
1267
1268     return(ok);
1269 }
1270
1271 static const struct method pop3 =
1272 {
1273     "POP3",             /* Post Office Protocol v3 */
1274     "pop3",             /* standard POP3 port */
1275     "pop3s",            /* ssl POP3 port */
1276     FALSE,              /* this is not a tagged protocol */
1277     TRUE,               /* this uses a message delimiter */
1278     pop3_ok,            /* parse command response */
1279     pop3_getauth,       /* get authorization */
1280     pop3_getrange,      /* query range of messages */
1281     pop3_getsizes,      /* we can get a list of sizes */
1282     pop3_getpartialsizes,       /* we can get the size of 1 mail */
1283     pop3_is_old,        /* how do we tell a message is old? */
1284     pop3_fetch,         /* request given message */
1285     NULL,               /* no way to fetch body alone */
1286     NULL,               /* no message trailer */
1287     pop3_delete,        /* how to delete a message */
1288     pop3_mark_seen,     /* how to mark a message as seen */
1289     NULL,               /* no action at end of mailbox */
1290     pop3_logout,        /* log out, we're done */
1291     FALSE,              /* no, we can't re-poll */
1292 };
1293
1294 int doPOP3 (struct query *ctl)
1295 /* retrieve messages using POP3 */
1296 {
1297 #ifndef MBOX
1298     if (ctl->mailboxes->id) {
1299         fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1300         return(PS_SYNTAX);
1301     }
1302 #endif /* MBOX */
1303
1304     return(do_protocol(ctl, &pop3));
1305 }
1306 #endif /* POP3_ENABLE */
1307
1308 /* pop3.c ends here */