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