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)
20 #include "fetchmail.h"
26 #endif /* OPIE_ENABLE */
28 #ifndef strstr /* glibc-2.1 declares this as a macro */
29 extern char *strstr(); /* needed on sysV68 R3V7.1. */
36 #endif /* SDPS_ENABLE */
39 static char lastok[POPBUFSIZE+1];
40 #endif /* OPIE_ENABLE */
42 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
44 static int pop3_ok (int sock, char *argbuf)
45 /* parse command response */
48 char buf [POPBUFSIZE+1];
51 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
53 if (*bufp == '+' || *bufp == '-')
58 while (isalpha(*bufp))
64 if (strcmp(buf,"+OK") == 0)
68 #endif /* OPIE_ENABLE */
71 else if (strncmp(buf,"-ERR", 4) == 0)
73 if (stage == STAGE_FETCH)
75 else if (stage > STAGE_GETAUTH)
78 * We're checking for "lock busy", "unable to lock",
79 * "already locked", "wait a few minutes" etc. here.
80 * This indicates that we have to wait for the server to
81 * unwedge itself before we can poll again.
83 * PS_LOCKBUSY check empirically verified with two recent
84 * versions of the Berkeley popper; QPOP (version 2.2) and
85 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
86 * These are caught by the case-indifferent "lock" check.
87 * The "wait" catches "mail storage services unavailable,
88 * wait a few minutes and try again" on the InterMail server.
90 * If these aren't picked up on correctly, fetchmail will
91 * think there is an authentication failure and wedge the
92 * connection in order to prevent futile polls.
96 else if (strstr(bufp,"lock")
97 || strstr(bufp,"Lock")
98 || strstr(bufp,"LOCK")
99 || strstr(bufp,"wait")
100 /* these are blessed by RFC 2449 */
101 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
103 else if ((strstr(bufp,"Service")
104 || strstr(bufp,"service"))
105 && (strstr(bufp,"unavailable")))
110 * We always want to pass the user lock-busy messages, because
111 * they're red flags. Other stuff (like AUTH failures on non-
112 * RFC1734 servers) only if we're debugging.
114 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
115 report(stderr, "%s\n", bufp);
127 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
128 /* apply for connection authorization */
135 #endif /* OPIE_ENABLE */
137 flag has_gssapi = FALSE;
138 #endif /* defined(GSSAPI) */
139 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
140 flag has_kerberos = FALSE;
141 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
142 flag has_cram = FALSE;
144 flag has_otp = FALSE;
145 #endif /* OPIE_ENABLE */
147 flag has_ssl = FALSE;
148 #endif /* SSL_ENABLE */
152 * This needs to catch both demon.co.uk and demon.net.
153 * If we see either, and we're in multidrop mode, try to use
154 * the SDPS *ENV extension.
156 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
157 ctl->server.sdps = TRUE;
158 #endif /* SDPS_ENABLE */
160 switch (ctl->server.protocol) {
163 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
164 if (strstr(ctl->remotename, "@compuserve.com"))
166 /* AUTH command should return a list of available mechanisms */
167 if (gen_transact(sock, "AUTH") == 0)
170 flag has_rpa = FALSE;
172 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
176 if (strncasecmp(buffer, "rpa", 3) == 0)
179 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
180 ctl->password, sock))
186 #endif /* RPA_ENABLE */
189 * CAPA command may return a list including available
190 * authentication mechanisms. if it doesn't, no harm done, we
191 * just fall back to a plain login. Note that this code
192 * latches the server's authentication type, so that in daemon mode
193 * the CAPA check only needs to be done once at start of run.
195 * If CAPA fails, then force the authentication method to PASSORD
196 * and repoll immediately.
198 * These authentication methods are blessed by RFC1734,
199 * describing the POP3 AUTHentication command.
201 if (ctl->server.authenticate == A_ANY)
203 ok = gen_transact(sock, "CAPA");
204 if (ok == PS_SUCCESS)
208 /* determine what authentication methods we have available */
209 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
214 if (strstr(buffer, "STLS"))
216 #endif /* SSL_ENABLE */
218 if (strstr(buffer, "GSSAPI"))
220 #endif /* defined(GSSAPI) */
221 #if defined(KERBEROS_V4)
222 if (strstr(buffer, "KERBEROS_V4"))
224 #endif /* defined(KERBEROS_V4) */
226 if (strstr(buffer, "X-OTP"))
228 #endif /* OPIE_ENABLE */
229 if (strstr(buffer, "CRAM-MD5"))
233 /* we are in STAGE_GETAUTH! */
234 else if (ok == PS_AUTHFAIL ||
235 /* Some servers directly close the socket. However, if we
236 * have already authenticated before, then a previous CAPA
237 * must have succeeded. In that case, treat this as a
238 * genuine socket error and do not change the auth method.
240 (ok == PS_SOCKET && !ctl->wehaveauthed))
242 ctl->server.authenticate = A_PASSWORD;
243 /* repoll immediately */
252 && (ctl->server.authenticate == A_ANY))
256 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
257 gen_transact(sock, "STLS");
258 if (SSLOpen(sock,ctl->sslcert,ctl->sslkey,ctl->sslproto,ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
261 GT_("SSL connection failed.\n"));
265 #endif /* SSL_ENABLE */
268 * OK, we have an authentication type now.
270 #if defined(KERBEROS_V4)
272 * Servers doing KPOP have to go through a dummy login sequence
273 * rather than doing SASL.
277 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
278 #else /* INET6_ENABLE */
279 ctl->server.port != KPOP_PORT
280 #endif /* INET6_ENABLE */
281 && (ctl->server.authenticate == A_KERBEROS_V4
282 || ctl->server.authenticate == A_KERBEROS_V5
283 || ctl->server.authenticate == A_ANY))
285 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
286 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
289 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
293 (ctl->server.authenticate == A_GSSAPI ||
294 ctl->server.authenticate == A_ANY))
296 ok = do_gssauth(sock,"AUTH",ctl->server.truename,ctl->remotename);
297 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
300 #endif /* defined(GSSAPI) */
304 (ctl->server.authenticate == A_OTP ||
305 ctl->server.authenticate == A_ANY))
307 ok = do_otp(sock, "AUTH", ctl);
308 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
311 #endif /* OPIE_ENABLE */
314 (ctl->server.authenticate == A_CRAM_MD5 ||
315 ctl->server.authenticate == A_ANY))
317 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
318 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
322 /* ordinary validation, no one-time password or RPA */
323 gen_transact(sock, "USER %s", ctl->remotename);
326 /* see RFC1938: A One-Time Password System */
327 if (challenge = strstr(lastok, "otp-")) {
328 char response[OPIE_RESPONSE_MAX+1];
331 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
332 if ((i == -2) && !run.poll_interval) {
333 char secret[OPIE_SECRET_MAX+1];
334 fprintf(stderr, GT_("Secret pass phrase: "));
335 if (opiereadpass(secret, sizeof(secret), 0))
336 i = opiegenerator(challenge, secret, response);
337 memset(secret, 0, sizeof(secret));
345 ok = gen_transact(sock, "PASS %s", response);
348 #endif /* OPIE_ENABLE */
350 strcpy(shroud, ctl->password);
351 ok = gen_transact(sock, "PASS %s", ctl->password);
356 /* build MD5 digest from greeting timestamp + password */
357 /* find start of timestamp */
358 for (start = greeting; *start != 0 && *start != '<'; start++)
362 GT_("Required APOP timestamp not found in greeting\n"));
366 /* find end of timestamp */
367 for (end = start; *end != 0 && *end != '>'; end++)
369 if (*end == 0 || end == start + 1) {
371 GT_("Timestamp syntax error in greeting\n"));
377 /* copy timestamp and password into digestion buffer */
378 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
380 strcat(msg,ctl->password);
382 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
384 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
388 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
389 ok = gen_transact(sock, "RPOP %s", ctl->password);
393 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
399 /* maybe we detected a lock-busy condition? */
400 if (ok == PS_LOCKBUSY)
401 report(stderr, GT_("lock busy! Is another session active?\n"));
407 * Empirical experience shows some server/OS combinations
408 * may need a brief pause even after any lockfiles on the
409 * server are released, to give the server time to finish
410 * copying back very large mailfolders from the temp-file...
411 * this is only ever an issue with extremely large mailboxes.
413 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
415 /* we're peek-capable if use of TOP is enabled */
416 peek_capable = !(ctl->fetchall || ctl->keep);
422 static int pop3_gettopid( int sock, int num , char *id)
426 char buf [POPBUFSIZE+1];
427 sprintf( buf, "TOP %d 1", num );
428 if ((ok = gen_transact(sock, buf )) != 0)
431 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
435 if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
437 /* prevent stack overflows */
439 sscanf( buf+12, "%s", id);
445 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
447 /* This approach tries to get the message headers from the
448 * remote hosts and compares the message-id to the already known
450 * + if the first message containes a new id, all messages on
451 * the server will be new
452 * + if the first is known, try to estimate the last known message
453 * on the server and check. If this works you know the total number
454 * of messages to get.
455 * + Otherwise run a binary search to determine the last known message
457 int ok, nolinear = 0;
458 int first_nr, list_len, try_id, try_nr, add_id;
462 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
465 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
466 /* the first message is unknown -> all messages are new */
471 /* check where we expect the latest known message */
472 list_len = count_list( &ctl->oldsaved );
473 try_id = list_len - first_nr; /* -1 + 1 */
475 if( try_id <= *countp ) {
476 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
479 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
484 if( try_nr != list_len -1 ) {
485 /* some messages inbetween have been deleted... */
489 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
491 for( ; add_id; add_id >>= 1 ) {
493 if( try_id - add_id <= 1 ) {
500 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
502 try_nr = str_nr_in_list(&ctl->oldsaved, id);
509 GT_("Messages inserted into list on server. Cannot handle this.\n"));
514 /* the first try_id messages are known -> copy them to the newsaved list */
515 for( num = first_nr; num < list_len; num++ )
517 struct idlist *new = save_str(&ctl->newsaved,
518 str_from_nr_list(&ctl->oldsaved, num),
520 new->val.status.num = num - first_nr + 1;
524 free_str_list(&ctl->oldsaved);
529 *newp = *countp - try_id;
533 static int pop3_getrange(int sock,
536 int *countp, int *newp, int *bytes)
537 /* get range of messages to be fetched */
540 char buf [POPBUFSIZE+1];
542 /* Ensure that the new list is properly empty */
543 ctl->newsaved = (struct idlist *)NULL;
546 /* Alain Knaff suggests this, but it's not RFC standard */
548 if ((ok = gen_transact(sock, "MBOX %s", folder)))
552 /* get the total message count */
553 gen_send(sock, "STAT");
554 ok = pop3_ok(sock, buf);
556 sscanf(buf,"%d %d", countp, bytes);
561 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
562 * We work as hard as possible to hide this ugliness, but it makes
563 * counting new messages intrinsically quadratic in the worst case.
567 if (*countp > 0 && !ctl->fetchall)
571 if (!ctl->server.uidl) {
572 gen_send(sock, "LAST");
573 ok = pop3_ok(sock, buf);
578 if (sscanf(buf, "%d", &last) == 0)
580 report(stderr, GT_("protocol error\n"));
583 *newp = (*countp - last);
587 /* grab the mailbox's UID list */
588 if ((ok = gen_transact(sock, "UIDL")) != 0)
590 /* don't worry, yet! do it the slow way */
591 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
593 report(stderr, GT_("protocol error while fetching UIDLs\n"));
602 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
606 else if (sscanf(buf, "%d %s", &num, id) == 2)
610 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
611 new->val.status.num = num;
613 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
614 new->val.status.mark = UID_SEEN;
615 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
628 static int pop3_getsizes(int sock, int count, int *sizes)
629 /* capture the sizes of all messages */
633 if ((ok = gen_transact(sock, "LIST")) != 0)
637 char buf [POPBUFSIZE+1];
639 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
641 unsigned int num, size;
645 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
646 if (num > 0 && num <= count)
647 sizes[num - 1] = size;
649 /* warn about possible attempt to induce buffer overrun */
650 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
658 static int pop3_is_old(int sock, struct query *ctl, int num)
659 /* is the given message old? */
662 return (num <= last);
664 return (str_in_list(&ctl->oldsaved,
665 str_find(&ctl->newsaved, num), FALSE));
670 * We could use this to fetch headers only as we do for IMAP. The trouble
671 * is that there's no way to fetch the body only. So the following RETR
672 * would have to re-fetch the header. Enough messages have longer headers
673 * than bodies to make this a net loss.
675 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
676 /* request headers of nth message */
679 char buf[POPBUFSIZE+1];
681 gen_send(sock, "TOP %d 0", number);
682 if ((ok = pop3_ok(sock, buf)) != 0)
685 *lenp = -1; /* we got sizes from the LIST response */
691 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
692 /* request nth message */
695 char buf[POPBUFSIZE+1];
699 * See http://www.demon.net/services/mail/sdps-tech.html
700 * for a description of what we're parsing here.
702 if (ctl->server.sdps)
706 sdps_envfrom = (char *)NULL;
707 sdps_envto = (char *)NULL;
708 gen_send(sock, "*ENV %d", number);
710 if (gen_recv(sock, buf, sizeof(buf)))
717 /* No need to wrap envelope from address */
718 sdps_envfrom = xmalloc(strlen(buf)+1);
719 strcpy(sdps_envfrom,buf);
722 /* Wrap address with To: <> so nxtaddr() likes it */
723 sdps_envto = xmalloc(strlen(buf)+7);
724 sprintf(sdps_envto,"To: <%s>",buf);
728 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
730 #endif /* SDPS_ENABLE */
733 * Though the POP RFCs don't document this fact, on almost every
734 * POP3 server I know of messages are marked "seen" only at the
735 * time the OK response to a RETR is issued.
737 * This means we can use TOP to fetch the message without setting its
738 * seen flag. This is good! It means that if the protocol exchange
739 * craps out during the message, it will still be marked `unseen' on
740 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
741 * reported to mark messages seen on a TOP fetch.)
743 * However...*don't* do this if we're using keep to suppress deletion!
744 * In that case, marking the seen flag is the only way to prevent the
745 * message from being re-fetched on subsequent runs.
747 * Also use RETR if fetchall is on. This gives us a workaround
748 * for servers like usa.net's that bungle TOP. It's pretty
749 * harmless because fetchall guarantees that any message dropped
750 * by an interrupted RETR will be picked up on the next poll of the
753 * We take advantage here of the fact that, according to all the
754 * POP RFCs, "if the number of lines requested by the POP3 client
755 * is greater than than the number of lines in the body, then the
756 * POP3 server sends the entire message.").
758 * The line count passed (99999999) is the maximum value CompuServe will
759 * accept; it's much lower than the natural value 2147483646 (the maximum
760 * twos-complement signed 32-bit integer minus 1) */
761 if (ctl->keep || ctl->fetchall)
762 gen_send(sock, "RETR %d", number);
764 gen_send(sock, "TOP %d 99999999", number);
765 if ((ok = pop3_ok(sock, buf)) != 0)
768 *lenp = -1; /* we got sizes from the LIST response */
773 static int pop3_delete(int sock, struct query *ctl, int number)
774 /* delete a given message */
776 /* actually, mark for deletion -- doesn't happen until QUIT time */
777 return(gen_transact(sock, "DELE %d", number));
780 static int pop3_logout(int sock, struct query *ctl)
781 /* send logout command */
787 * We used to do this in case the server marks messages deleted when seen.
788 * (Yes, this has been reported, in the MercuryP/NLM server.
789 * It's even legal under RFC 1939 (section 8) as a site policy.)
790 * It interacted badly with UIDL, though. Thomas Zajic wrote:
791 * "Running 'fetchmail -F -v' and checking the logs, I found out
792 * that fetchmail did in fact flush my mailbox properly, but sent
793 * a RSET just before sending QUIT to log off. This caused the
794 * POP3 server to undo/forget about the previous DELEs, resetting
795 * my mailbox to its original (ie. unflushed) state. The
796 * ~/.fetchids file did get flushed though, so the next time
797 * fetchmail was run it saw all the old messages as new ones ..."
800 gen_transact(sock, "RSET");
801 #endif /* __UNUSED__ */
803 ok = gen_transact(sock, "QUIT");
816 const static struct method pop3 =
818 "POP3", /* Post Office Protocol v3 */
820 "pop3", /* standard POP3 port */
821 "pop3s", /* ssl POP3 port */
822 #else /* INET6_ENABLE */
823 110, /* standard POP3 port */
824 995, /* ssl POP3 port */
825 #endif /* INET6_ENABLE */
826 FALSE, /* this is not a tagged protocol */
827 TRUE, /* this uses a message delimiter */
828 pop3_ok, /* parse command response */
829 pop3_getauth, /* get authorization */
830 pop3_getrange, /* query range of messages */
831 pop3_getsizes, /* we can get a list of sizes */
832 pop3_is_old, /* how do we tell a message is old? */
833 pop3_fetch, /* request given message */
834 NULL, /* no way to fetch body alone */
835 NULL, /* no message trailer */
836 pop3_delete, /* how to delete a message */
837 pop3_logout, /* log out, we're done */
838 FALSE, /* no, we can't re-poll */
841 int doPOP3 (struct query *ctl)
842 /* retrieve messages using POP3 */
845 if (ctl->mailboxes->id) {
846 fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
850 peek_capable = !ctl->fetchall;
851 return(do_protocol(ctl, &pop3));
853 #endif /* POP3_ENABLE */
855 /* pop3.c ends here */