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