2 * pop3.c -- POP3 protocol methods
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
13 #if defined(HAVE_UNISTD_H)
16 #if defined(STDC_HEADERS)
21 #include "fetchmail.h"
27 #endif /* OPIE_ENABLE */
29 /* global variables: please reinitialize them explicitly for proper
30 * working in daemon mode */
32 /* TODO: session variables to be initialized before server greeting */
34 static char lastok[POPBUFSIZE+1];
35 #endif /* OPIE_ENABLE */
37 /* session variables initialized in capa_probe() or pop3_getauth() */
39 flag has_gssapi = FALSE;
40 #endif /* defined(GSSAPI) */
41 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
42 flag has_kerberos = FALSE;
43 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
44 static flag has_cram = FALSE;
47 #endif /* OPIE_ENABLE */
49 static flag has_ssl = FALSE;
50 #endif /* SSL_ENABLE */
52 /* mailbox variables initialized in pop3_getrange() */
55 /* mail variables initialized in pop3_fetch() */
59 #endif /* SDPS_ENABLE */
65 * NTLM support by Grant Edwards.
67 * Handle MS-Exchange NTLM authentication method. This is the same
68 * as the NTLM auth used by Samba for SMB related services. We just
69 * encode the packets in base64 instead of sending them out via a
72 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
75 static int do_pop3_ntlm(int sock, struct query *ctl,
76 int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
78 tSmbNtlmAuthRequest request;
79 tSmbNtlmAuthChallenge challenge;
80 tSmbNtlmAuthResponse response;
85 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
87 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
93 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
95 if (outlevel >= O_DEBUG)
96 dumpSmbNtlmAuthRequest(stdout, &request);
98 memset(msgbuf,0,sizeof msgbuf);
99 to64frombits (msgbuf, &request, SmbLength(&request));
101 if (outlevel >= O_MONITOR)
102 report(stdout, "POP3> %s\n", msgbuf);
104 strcat(msgbuf,"\r\n");
105 SockWrite (sock, msgbuf, strlen (msgbuf));
107 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
110 len = from64tobits (&challenge, msgbuf, sizeof(msgbuf));
112 if (outlevel >= O_DEBUG)
113 dumpSmbNtlmAuthChallenge(stdout, &challenge);
115 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
117 if (outlevel >= O_DEBUG)
118 dumpSmbNtlmAuthResponse(stdout, &response);
120 memset(msgbuf,0,sizeof msgbuf);
121 to64frombits (msgbuf, &response, SmbLength(&response));
123 if (outlevel >= O_MONITOR)
124 report(stdout, "POP3> %s\n", msgbuf);
126 strcat(msgbuf,"\r\n");
127 SockWrite (sock, msgbuf, strlen (msgbuf));
129 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
132 if (strstr (msgbuf, "OK"))
140 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
142 static int pop3_ok (int sock, char *argbuf)
143 /* parse command response */
146 char buf [POPBUFSIZE+1];
149 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
151 if (*bufp == '+' || *bufp == '-')
156 while (isalpha((unsigned char)*bufp))
162 if (strcmp(buf,"+OK") == 0)
165 strcpy(lastok, bufp);
166 #endif /* OPIE_ENABLE */
169 else if (strncmp(buf,"-ERR", 4) == 0)
171 if (stage == STAGE_FETCH)
173 else if (stage > STAGE_GETAUTH)
176 * We're checking for "lock busy", "unable to lock",
177 * "already locked", "wait a few minutes" etc. here.
178 * This indicates that we have to wait for the server to
179 * unwedge itself before we can poll again.
181 * PS_LOCKBUSY check empirically verified with two recent
182 * versions of the Berkeley popper; QPOP (version 2.2) and
183 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
184 * These are caught by the case-indifferent "lock" check.
185 * The "wait" catches "mail storage services unavailable,
186 * wait a few minutes and try again" on the InterMail server.
188 * If these aren't picked up on correctly, fetchmail will
189 * think there is an authentication failure and wedge the
190 * connection in order to prevent futile polls.
194 else if (strstr(bufp,"lock")
195 || strstr(bufp,"Lock")
196 || strstr(bufp,"LOCK")
197 || strstr(bufp,"wait")
198 /* these are blessed by RFC 2449 */
199 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
201 else if ((strstr(bufp,"Service")
202 || strstr(bufp,"service"))
203 && (strstr(bufp,"unavailable")))
208 * We always want to pass the user lock-busy messages, because
209 * they're red flags. Other stuff (like AUTH failures on non-
210 * RFC1734 servers) only if we're debugging.
212 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
213 report(stderr, "%s\n", bufp);
218 #if POPBUFSIZE > MSGBUFSIZE
219 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
230 static int capa_probe(int sock)
231 /* probe the capabilities of the remote server */
237 #endif /* defined(GSSAPI) */
238 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
239 has_kerberos = FALSE;
240 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
244 #endif /* OPIE_ENABLE */
246 ok = gen_transact(sock, "CAPA");
247 if (ok == PS_SUCCESS)
251 /* determine what authentication methods we have available */
252 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
257 if (strstr(buffer, "STLS"))
259 #endif /* SSL_ENABLE */
261 if (strstr(buffer, "GSSAPI"))
263 #endif /* defined(GSSAPI) */
264 #if defined(KERBEROS_V4)
265 if (strstr(buffer, "KERBEROS_V4"))
267 #endif /* defined(KERBEROS_V4) */
269 if (strstr(buffer, "X-OTP"))
271 #endif /* OPIE_ENABLE */
272 if (strstr(buffer, "CRAM-MD5"))
279 static void set_peek_capable(struct query *ctl)
281 /* we're peek-capable means that the use of TOP is enabled,
282 * see pop3_fetch for details - short story, we can use TOP if
283 * we have a means of reliably tracking which mail we need to
284 * refetch should the connection abort in the middle.
285 * fetchall forces RETR, as does keep without UIDL */
286 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
289 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
290 /* apply for connection authorization */
297 #endif /* OPIE_ENABLE */
299 flag did_stls = FALSE;
300 #endif /* SSL_ENABLE */
304 #endif /* defined(GSSAPI) */
305 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
306 has_kerberos = FALSE;
307 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
311 #endif /* OPIE_ENABLE */
314 #endif /* SSL_ENABLE */
316 /* Set this up before authentication quits early. */
317 set_peek_capable(ctl);
319 * The "Maillennium POP3/PROXY server" deliberately truncates
320 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
321 * disable TOP. Comcast once spewed marketing babble to the extent
322 * of protecting Outlook -- pretty overzealous to break a protocol
323 * for that that Microsoft could have read, too. Comcast aren't
324 * alone in using this software though.
325 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
326 * (Thanks to Ed Wilts for reminding me of that.)
328 * The warning is printed once per server, until fetchmail exits.
329 * It will be suppressed when --fetchall or other circumstances make
330 * us use RETR anyhow.
334 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
335 if ((ctl->server.workarounds & WKA_TOP) == 0) {
336 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
337 ctl->server.workarounds |= WKA_TOP;
341 if (ctl->server.authenticate == A_SSH) {
347 * This needs to catch both demon.co.uk and demon.net.
348 * If we see either, and we're in multidrop mode, try to use
349 * the SDPS *ENV extension.
351 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
352 ctl->server.sdps = TRUE;
353 #endif /* SDPS_ENABLE */
356 /* MSN servers require the use of NTLM (MSN) authentication */
357 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
358 ctl->server.authenticate == A_MSN)
359 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
360 if (ctl->server.authenticate == A_NTLM)
361 return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
363 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
366 GT_("Required NTLM capability not compiled into fetchmail\n"));
370 switch (ctl->server.protocol) {
373 /* XXX FIXME: AUTH probing (RFC1734) should become global */
374 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
375 if (strstr(ctl->remotename, "@compuserve.com"))
377 /* AUTH command should return a list of available mechanisms */
378 if (gen_transact(sock, "AUTH") == 0)
381 flag has_rpa = FALSE;
383 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
387 if (strncasecmp(buffer, "rpa", 3) == 0)
390 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
391 ctl->password, sock))
397 #endif /* RPA_ENABLE */
400 * CAPA command may return a list including available
401 * authentication mechanisms. if it doesn't, no harm done, we
402 * just fall back to a plain login. Note that this code
403 * latches the server's authentication type, so that in daemon mode
404 * the CAPA check only needs to be done once at start of run.
406 * If CAPA fails, then force the authentication method to PASSORD
407 * and repoll immediately.
409 * These authentication methods are blessed by RFC1734,
410 * describing the POP3 AUTHentication command.
412 if ((ctl->server.authenticate == A_ANY) ||
413 (ctl->server.authenticate == A_GSSAPI) ||
414 (ctl->server.authenticate == A_KERBEROS_V4) ||
415 (ctl->server.authenticate == A_OTP) ||
416 (ctl->server.authenticate == A_CRAM_MD5))
418 if ((ok = capa_probe(sock)) != PS_SUCCESS)
419 /* we are in STAGE_GETAUTH! */
420 if (ok == PS_AUTHFAIL ||
421 /* Some servers directly close the socket. However, if we
422 * have already authenticated before, then a previous CAPA
423 * must have succeeded. In that case, treat this as a
424 * genuine socket error and do not change the auth method.
426 (ok == PS_SOCKET && !ctl->wehaveauthed))
428 ctl->server.authenticate = A_PASSWORD;
429 /* repoll immediately */
438 && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
442 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
443 ok = gen_transact(sock, "STLS");
445 /* We use "tls1" instead of ctl->sslproto, as we want STLS,
446 * not other SSL protocols
448 if (ok == PS_SUCCESS &&
449 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
451 if (!ctl->sslproto && !ctl->wehaveauthed)
453 ctl->sslproto = xstrdup("");
454 /* repoll immediately */
458 GT_("SSL connection failed.\n"));
464 * RFC 2595 says this:
466 * "Once TLS has been started, the client MUST discard cached
467 * information about server capabilities and SHOULD re-issue the
468 * CAPABILITY command. This is necessary to protect against
469 * man-in-the-middle attacks which alter the capabilities list prior
470 * to STARTTLS. The server MAY advertise different capabilities
475 #endif /* SSL_ENABLE */
478 * OK, we have an authentication type now.
480 #if defined(KERBEROS_V4)
482 * Servers doing KPOP have to go through a dummy login sequence
483 * rather than doing SASL.
486 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
487 && (ctl->server.authenticate == A_KERBEROS_V4
488 || ctl->server.authenticate == A_KERBEROS_V5
489 || ctl->server.authenticate == A_ANY))
491 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
492 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
495 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
499 (ctl->server.authenticate == A_GSSAPI ||
500 ctl->server.authenticate == A_ANY))
502 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
503 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
506 #endif /* defined(GSSAPI) */
510 (ctl->server.authenticate == A_OTP ||
511 ctl->server.authenticate == A_ANY))
513 ok = do_otp(sock, "AUTH", ctl);
514 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
517 #endif /* OPIE_ENABLE */
519 if (ctl->server.authenticate == A_CRAM_MD5 ||
520 (has_cram && ctl->server.authenticate == A_ANY))
522 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
523 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
527 /* ordinary validation, no one-time password or RPA */
528 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
532 /* see RFC1938: A One-Time Password System */
533 if ((challenge = strstr(lastok, "otp-"))) {
534 char response[OPIE_RESPONSE_MAX+1];
537 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
538 if ((i == -2) && !run.poll_interval) {
539 char secret[OPIE_SECRET_MAX+1];
540 fprintf(stderr, GT_("Secret pass phrase: "));
541 if (opiereadpass(secret, sizeof(secret), 0))
542 i = opiegenerator(challenge, secret, response);
543 memset(secret, 0, sizeof(secret));
551 ok = gen_transact(sock, "PASS %s", response);
554 #endif /* OPIE_ENABLE */
556 strlcpy(shroud, ctl->password, sizeof(shroud));
557 ok = gen_transact(sock, "PASS %s", ctl->password);
560 /* this is for servers which claim to support TLS, but actually
562 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
564 ctl->sslproto = xstrdup("");
565 /* repoll immediately */
572 /* build MD5 digest from greeting timestamp + password */
573 /* find start of timestamp */
574 for (start = greeting; *start != 0 && *start != '<'; start++)
578 GT_("Required APOP timestamp not found in greeting\n"));
582 /* find end of timestamp */
583 for (end = start; *end != 0 && *end != '>'; end++)
585 if (*end == 0 || end == start + 1) {
587 GT_("Timestamp syntax error in greeting\n"));
593 /* copy timestamp and password into digestion buffer */
594 msg = xmalloc((end-start+1) + strlen(ctl->password) + 1);
596 strcat(msg,ctl->password);
597 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
600 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
604 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
605 ok = gen_transact(sock, "RPOP %s", ctl->password);
609 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
615 /* maybe we detected a lock-busy condition? */
616 if (ok == PS_LOCKBUSY)
617 report(stderr, GT_("lock busy! Is another session active?\n"));
622 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
623 * accepted by Matthias Andree.
625 * Rationale: the server must have locked the spool before returning +OK;
626 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
629 * Empirical experience shows some server/OS combinations
630 * may need a brief pause even after any lockfiles on the
631 * server are released, to give the server time to finish
632 * copying back very large mailfolders from the temp-file...
633 * this is only ever an issue with extremely large mailboxes.
635 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
642 /* cut off C string at first POSIX space */
643 static void trim(char *s) {
644 s += strcspn(s, POSIX_space);
648 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
652 char buf [POPBUFSIZE+1];
653 snprintf(buf, sizeof(buf), "TOP %d 1", num);
654 if ((ok = gen_transact(sock, buf )) != 0)
657 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
661 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
664 p += strspn(p, POSIX_space);
665 strlcpy(id, p, idsize);
672 /** Parse the UID response (leading +OK must have been
673 * stripped off) in buf, store the number in gotnum, and store the ID
674 * into the caller-provided buffer "id" of size "idsize".
675 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
676 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
681 /* skip leading blanks ourselves */
683 i += strspn(i, POSIX_space);
685 *gotnum = strtoul(i, &j, 10);
686 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
687 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
690 j += strspn(j, POSIX_space);
691 strlcpy(id, j, idsize);
696 /** request UIDL for single message \a num and stuff the result into the
697 * buffer \a id which can hold \a idsize bytes */
698 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
701 char buf [POPBUFSIZE+1];
702 unsigned long gotnum;
704 gen_send(sock, "UIDL %d", num);
705 if ((ok = pop3_ok(sock, buf)) != 0)
707 if ((ok = parseuid(buf, &gotnum, id, idsize)))
709 if (gotnum != (unsigned long)num) {
710 report(stderr, GT_("Server responded with UID for wrong message.\n"));
716 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
719 unsigned int first_nr, last_nr, try_nr;
724 while (first_nr < last_nr - 1)
728 try_nr = (first_nr + last_nr) / 2;
729 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
731 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE)))
733 flag mark = newl->val.status.mark;
734 if (mark == UID_DELETED || mark == UID_EXPUNGED)
736 if (outlevel >= O_VERBOSE)
737 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
738 /* just mark it as seen now! */
739 newl->val.status.mark = mark = UID_SEEN;
742 /* narrow the search region! */
743 if (mark == UID_UNSEEN)
745 if (outlevel >= O_DEBUG)
746 report(stdout, GT_("%u is unseen\n"), try_nr);
752 /* save the number */
753 newl->val.status.num = try_nr;
757 if (outlevel >= O_DEBUG)
758 report(stdout, GT_("%u is unseen\n"), try_nr);
762 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
763 newl->val.status.num = try_nr;
766 if (outlevel >= O_DEBUG && last_nr <= count)
767 report(stdout, GT_("%u is first unseen\n"), last_nr);
770 *newp = count - first_nr;
775 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
777 /* This approach tries to get the message headers from the
778 * remote hosts and compares the message-id to the already known
780 * + if the first message containes a new id, all messages on
781 * the server will be new
782 * + if the first is known, try to estimate the last known message
783 * on the server and check. If this works you know the total number
784 * of messages to get.
785 * + Otherwise run a binary search to determine the last known message
787 int ok, nolinear = 0;
788 int first_nr, list_len, try_id, try_nr, add_id;
792 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
795 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
796 /* the first message is unknown -> all messages are new */
801 /* check where we expect the latest known message */
802 list_len = count_list( &ctl->oldsaved );
803 try_id = list_len - first_nr; /* -1 + 1 */
805 if( try_id <= *countp ) {
806 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
809 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
814 if( try_nr != list_len -1 ) {
815 /* some messages inbetween have been deleted... */
819 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
821 for( ; add_id; add_id >>= 1 ) {
823 if( try_id - add_id <= 1 ) {
830 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
832 try_nr = str_nr_in_list(&ctl->oldsaved, id);
839 GT_("Messages inserted into list on server. Cannot handle this.\n"));
844 /* the first try_id messages are known -> copy them to the newsaved list */
845 for( num = first_nr; num < list_len; num++ )
847 struct idlist *newl = save_str(&ctl->newsaved,
848 str_from_nr_list(&ctl->oldsaved, num),
850 newl->val.status.num = num - first_nr + 1;
854 free_str_list(&ctl->oldsaved);
859 *newp = *countp - try_id;
863 static int pop3_getrange(int sock,
866 int *countp, int *newp, int *bytes)
867 /* get range of messages to be fetched */
870 char buf [POPBUFSIZE+1];
873 /* Ensure that the new list is properly empty */
874 ctl->newsaved = (struct idlist *)NULL;
877 /* Alain Knaff suggests this, but it's not RFC standard */
879 if ((ok = gen_transact(sock, "MBOX %s", folder)))
883 /* get the total message count */
884 gen_send(sock, "STAT");
885 ok = pop3_ok(sock, buf);
887 sscanf(buf,"%d %d", countp, bytes);
892 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST command.
893 * We work as hard as possible to hide this, but it makes
894 * counting new messages intrinsically quadratic in the worst case.
898 /* if there are messages, and UIDL is desired, use UIDL
899 * also use UIDL if fetchall is unset */
900 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
905 /* should we do fast uidl this time? */
906 fastuidl = ctl->fastuidl;
907 if (*countp > 7 && /* linear search is better if there are few mails! */
908 !ctl->fetchall && /* with fetchall, all uids are required */
909 !ctl->flush && /* with flush, it is safer to disable fastuidl */
910 NUM_NONZERO (fastuidl))
915 dofastuidl = ctl->fastuidlcount != 0;
920 if (!ctl->server.uidl) {
921 gen_send(sock, "LAST");
922 ok = pop3_ok(sock, buf);
928 /* scan LAST reply */
929 if (sscanf(buf, "%d", &last) == 0)
931 report(stderr, GT_("protocol error\n"));
934 *newp = (*countp - last);
940 return(pop3_fastuidl( sock, ctl, *countp, newp));
941 /* grab the mailbox's UID list */
942 if ((ok = gen_transact(sock, "UIDL")) != 0)
944 /* don't worry, yet! do it the slow way */
945 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
947 report(stderr, GT_("protocol error while fetching UIDLs\n"));
953 /* UIDL worked - parse reply */
957 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
962 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
964 struct idlist *old, *newl;
966 newl = save_str(&ctl->newsaved, id, UID_UNSEEN);
967 newl->val.status.num = unum;
969 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
971 flag mark = old->val.status.mark;
972 if (mark == UID_DELETED || mark == UID_EXPUNGED)
974 /* XXX FIXME: switch 3 occurrences from
975 * (int)unum or (unsigned int)unum to
976 * remove the cast and use %lu - not now
977 * though, time for new release */
978 if (outlevel >= O_VERBOSE)
979 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
980 /* just mark it as seen now! */
981 old->val.status.mark = mark = UID_SEEN;
983 newl->val.status.mark = mark;
984 if (mark == UID_UNSEEN)
987 if (outlevel >= O_DEBUG)
988 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
994 if (outlevel >= O_DEBUG)
995 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
996 /* add it to oldsaved also! In case, we do not
997 * swap the lists (say, due to socket error),
998 * the same mail will not be downloaded again.
1000 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1001 old->val.status.num = unum;
1005 } /* multi-line loop for UIDL reply */
1013 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1014 /* capture the size of message #first */
1017 char buf [POPBUFSIZE+1];
1020 for (i = first; i <= last; i++) {
1021 gen_send(sock, "LIST %d", i);
1022 if ((ok = pop3_ok(sock, buf)) != 0)
1024 if (sscanf(buf, "%d %u", &num, &size) == 2) {
1026 sizes[i - first] = size;
1028 /* warn about possible attempt to induce buffer overrun
1030 * we expect server reply message number and requested
1031 * message number to match */
1032 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1038 static int pop3_getsizes(int sock, int count, int *sizes)
1039 /* capture the sizes of all messages */
1043 if ((ok = gen_transact(sock, "LIST")) != 0)
1047 char buf [POPBUFSIZE+1];
1049 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1051 unsigned int num, size;
1055 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1056 if (num > 0 && num <= (unsigned)count)
1057 sizes[num - 1] = size;
1059 /* warn about possible attempt to induce buffer overrun */
1060 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1068 static int pop3_is_old(int sock, struct query *ctl, int num)
1069 /* is the given message old? */
1071 struct idlist *newl;
1073 return (num <= last);
1074 else if (dofastuidl)
1081 /* in fast uidl, we manipulate the old list only! */
1083 if ((newl = id_find(&ctl->oldsaved, num)))
1085 /* we already have the id! */
1086 return(newl->val.status.mark != UID_UNSEEN);
1089 /* get the uidl first! */
1090 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1093 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE))) {
1094 /* we already have the id! */
1095 newl->val.status.num = num;
1096 return(newl->val.status.mark != UID_UNSEEN);
1100 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1101 newl->val.status.num = num;
1105 return ((newl = id_find(&ctl->newsaved, num)) != NULL &&
1106 newl->val.status.mark != UID_UNSEEN);
1111 * We could use this to fetch headers only as we do for IMAP. The trouble
1112 * is that there's no way to fetch the body only. So the following RETR
1113 * would have to re-fetch the header. Enough messages have longer headers
1114 * than bodies to make this a net loss.
1116 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1117 /* request headers of nth message */
1120 char buf[POPBUFSIZE+1];
1122 gen_send(sock, "TOP %d 0", number);
1123 if ((ok = pop3_ok(sock, buf)) != 0)
1126 *lenp = -1; /* we got sizes from the LIST response */
1132 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1133 /* request nth message */
1136 char buf[POPBUFSIZE+1];
1140 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1141 * for a description of what we're parsing here.
1142 * -- updated 2006-02-22
1144 if (ctl->server.sdps)
1148 sdps_envfrom = (char *)NULL;
1149 sdps_envto = (char *)NULL;
1150 gen_send(sock, "*ENV %d", number);
1152 if (gen_recv(sock, buf, sizeof(buf)))
1157 switch (linecount) {
1159 /* No need to wrap envelope from address */
1160 /* FIXME: some parts of fetchmail don't handle null
1161 * envelope senders, so use <> to mark null sender
1162 * as a workaround. */
1163 if (strspn(buf, " \t") == strlen(buf))
1165 sdps_envfrom = xmalloc(strlen(buf)+1);
1166 strcpy(sdps_envfrom,buf);
1169 /* Wrap address with To: <> so nxtaddr() likes it */
1170 sdps_envto = xmalloc(strlen(buf)+7);
1171 sprintf(sdps_envto,"To: <%s>",buf);
1175 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1177 #endif /* SDPS_ENABLE */
1180 * Though the POP RFCs don't document this fact, on almost every
1181 * POP3 server I know of messages are marked "seen" only at the
1182 * time the OK response to a RETR is issued.
1184 * This means we can use TOP to fetch the message without setting its
1185 * seen flag. This is good! It means that if the protocol exchange
1186 * craps out during the message, it will still be marked `unseen' on
1187 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1188 * reported to mark messages seen on a TOP fetch.)
1190 * However...*don't* do this if we're using keep to suppress deletion!
1191 * In that case, marking the seen flag is the only way to prevent the
1192 * message from being re-fetched on subsequent runs.
1194 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1195 * This gives us a workaround for servers like usa.net's that bungle
1196 * TOP. It's pretty harmless because fetchall guarantees that any
1197 * message dropped by an interrupted RETR will be picked up on the
1198 * next poll of the site.
1200 * We take advantage here of the fact that, according to all the
1201 * POP RFCs, "if the number of lines requested by the POP3 client
1202 * is greater than than the number of lines in the body, then the
1203 * POP3 server sends the entire message.").
1205 * The line count passed (99999999) is the maximum value CompuServe will
1206 * accept; it's much lower than the natural value 2147483646 (the maximum
1207 * twos-complement signed 32-bit integer minus 1) */
1209 gen_send(sock, "RETR %d", number);
1211 gen_send(sock, "TOP %d 99999999", number);
1212 if ((ok = pop3_ok(sock, buf)) != 0)
1215 *lenp = -1; /* we got sizes from the LIST response */
1220 static void mark_uid_seen(struct query *ctl, int number)
1221 /* Tell the UID code we've seen this. */
1225 if ((sdp = id_find(&ctl->newsaved, number)))
1226 sdp->val.status.mark = UID_SEEN;
1227 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1228 * (say, due to socket error), the same mail will not be downloaded
1231 if ((sdp = id_find(&ctl->oldsaved, number)))
1232 sdp->val.status.mark = UID_SEEN;
1235 static int pop3_delete(int sock, struct query *ctl, int number)
1236 /* delete a given message */
1239 mark_uid_seen(ctl, number);
1240 /* actually, mark for deletion -- doesn't happen until QUIT time */
1241 ok = gen_transact(sock, "DELE %d", number);
1242 if (ok != PS_SUCCESS)
1244 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1248 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1249 /* mark a given message as seen */
1252 mark_uid_seen(ctl, number);
1256 static int pop3_logout(int sock, struct query *ctl)
1257 /* send logout command */
1263 * We used to do this in case the server marks messages deleted when seen.
1264 * (Yes, this has been reported, in the MercuryP/NLM server.
1265 * It's even legal under RFC 1939 (section 8) as a site policy.)
1266 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1267 * "Running 'fetchmail -F -v' and checking the logs, I found out
1268 * that fetchmail did in fact flush my mailbox properly, but sent
1269 * a RSET just before sending QUIT to log off. This caused the
1270 * POP3 server to undo/forget about the previous DELEs, resetting
1271 * my mailbox to its original (ie. unflushed) state. The
1272 * ~/.fetchids file did get flushed though, so the next time
1273 * fetchmail was run it saw all the old messages as new ones ..."
1276 gen_transact(sock, "RSET");
1277 #endif /* __UNUSED__ */
1279 ok = gen_transact(sock, "QUIT");
1286 static const struct method pop3 =
1288 "POP3", /* Post Office Protocol v3 */
1289 "pop3", /* standard POP3 port */
1290 "pop3s", /* ssl POP3 port */
1291 FALSE, /* this is not a tagged protocol */
1292 TRUE, /* this uses a message delimiter */
1293 pop3_ok, /* parse command response */
1294 pop3_getauth, /* get authorization */
1295 pop3_getrange, /* query range of messages */
1296 pop3_getsizes, /* we can get a list of sizes */
1297 pop3_getpartialsizes, /* we can get the size of 1 mail */
1298 pop3_is_old, /* how do we tell a message is old? */
1299 pop3_fetch, /* request given message */
1300 NULL, /* no way to fetch body alone */
1301 NULL, /* no message trailer */
1302 pop3_delete, /* how to delete a message */
1303 pop3_mark_seen, /* how to mark a message as seen */
1304 NULL, /* no action at end of mailbox */
1305 pop3_logout, /* log out, we're done */
1306 FALSE, /* no, we can't re-poll */
1309 int doPOP3 (struct query *ctl)
1310 /* retrieve messages using POP3 */
1313 if (ctl->mailboxes->id) {
1314 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1319 return(do_protocol(ctl, &pop3));
1321 #endif /* POP3_ENABLE */
1323 /* pop3.c ends here */