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