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 flag did_stls = FALSE;
149 #endif /* SSL_ENABLE */
153 * This needs to catch both demon.co.uk and demon.net.
154 * If we see either, and we're in multidrop mode, try to use
155 * the SDPS *ENV extension.
157 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
158 ctl->server.sdps = TRUE;
159 #endif /* SDPS_ENABLE */
161 switch (ctl->server.protocol) {
164 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
165 if (strstr(ctl->remotename, "@compuserve.com"))
167 /* AUTH command should return a list of available mechanisms */
168 if (gen_transact(sock, "AUTH") == 0)
171 flag has_rpa = FALSE;
173 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
177 if (strncasecmp(buffer, "rpa", 3) == 0)
180 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
181 ctl->password, sock))
187 #endif /* RPA_ENABLE */
190 * CAPA command may return a list including available
191 * authentication mechanisms. if it doesn't, no harm done, we
192 * just fall back to a plain login. Note that this code
193 * latches the server's authentication type, so that in daemon mode
194 * the CAPA check only needs to be done once at start of run.
196 * If CAPA fails, then force the authentication method to PASSORD
197 * and repoll immediately.
199 * These authentication methods are blessed by RFC1734,
200 * describing the POP3 AUTHentication command.
202 if (ctl->server.authenticate == A_ANY)
204 ok = gen_transact(sock, "CAPA");
205 if (ok == PS_SUCCESS)
209 /* determine what authentication methods we have available */
210 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
215 if (strstr(buffer, "STLS"))
217 #endif /* SSL_ENABLE */
219 if (strstr(buffer, "GSSAPI"))
221 #endif /* defined(GSSAPI) */
222 #if defined(KERBEROS_V4)
223 if (strstr(buffer, "KERBEROS_V4"))
225 #endif /* defined(KERBEROS_V4) */
227 if (strstr(buffer, "X-OTP"))
229 #endif /* OPIE_ENABLE */
230 if (strstr(buffer, "CRAM-MD5"))
234 /* we are in STAGE_GETAUTH! */
235 else if (ok == PS_AUTHFAIL ||
236 /* Some servers directly close the socket. However, if we
237 * have already authenticated before, then a previous CAPA
238 * must have succeeded. In that case, treat this as a
239 * genuine socket error and do not change the auth method.
241 (ok == PS_SOCKET && !ctl->wehaveauthed))
243 ctl->server.authenticate = A_PASSWORD;
244 /* repoll immediately */
253 && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
257 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
258 gen_transact(sock, "STLS");
260 /* We use "tls1" instead of ctl->sslproto, as we want STLS,
261 * not other SSL protocols
263 if (SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
265 if (!ctl->sslproto && !ctl->wehaveauthed)
267 ctl->sslproto = xstrdup("");
268 /* repoll immediately */
272 GT_("SSL connection failed.\n"));
277 #endif /* SSL_ENABLE */
280 * OK, we have an authentication type now.
282 #if defined(KERBEROS_V4)
284 * Servers doing KPOP have to go through a dummy login sequence
285 * rather than doing SASL.
289 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
290 #else /* INET6_ENABLE */
291 ctl->server.port != KPOP_PORT
292 #endif /* INET6_ENABLE */
293 && (ctl->server.authenticate == A_KERBEROS_V4
294 || ctl->server.authenticate == A_KERBEROS_V5
295 || ctl->server.authenticate == A_ANY))
297 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
298 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
301 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
305 (ctl->server.authenticate == A_GSSAPI ||
306 ctl->server.authenticate == A_ANY))
308 ok = do_gssauth(sock,"AUTH",ctl->server.truename,ctl->remotename);
309 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
312 #endif /* defined(GSSAPI) */
316 (ctl->server.authenticate == A_OTP ||
317 ctl->server.authenticate == A_ANY))
319 ok = do_otp(sock, "AUTH", ctl);
320 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
323 #endif /* OPIE_ENABLE */
326 (ctl->server.authenticate == A_CRAM_MD5 ||
327 ctl->server.authenticate == A_ANY))
329 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
330 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
334 /* ordinary validation, no one-time password or RPA */
335 gen_transact(sock, "USER %s", ctl->remotename);
338 /* see RFC1938: A One-Time Password System */
339 if (challenge = strstr(lastok, "otp-")) {
340 char response[OPIE_RESPONSE_MAX+1];
343 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
344 if ((i == -2) && !run.poll_interval) {
345 char secret[OPIE_SECRET_MAX+1];
346 fprintf(stderr, GT_("Secret pass phrase: "));
347 if (opiereadpass(secret, sizeof(secret), 0))
348 i = opiegenerator(challenge, secret, response);
349 memset(secret, 0, sizeof(secret));
357 ok = gen_transact(sock, "PASS %s", response);
360 #endif /* OPIE_ENABLE */
362 strcpy(shroud, ctl->password);
363 ok = gen_transact(sock, "PASS %s", ctl->password);
366 /* this is for servers which claim to support TLS, but actually
368 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
370 ctl->sslproto = xstrdup("");
371 /* repoll immediately */
378 /* build MD5 digest from greeting timestamp + password */
379 /* find start of timestamp */
380 for (start = greeting; *start != 0 && *start != '<'; start++)
384 GT_("Required APOP timestamp not found in greeting\n"));
388 /* find end of timestamp */
389 for (end = start; *end != 0 && *end != '>'; end++)
391 if (*end == 0 || end == start + 1) {
393 GT_("Timestamp syntax error in greeting\n"));
399 /* copy timestamp and password into digestion buffer */
400 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
402 strcat(msg,ctl->password);
404 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
406 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
410 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
411 ok = gen_transact(sock, "RPOP %s", ctl->password);
415 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
421 /* maybe we detected a lock-busy condition? */
422 if (ok == PS_LOCKBUSY)
423 report(stderr, GT_("lock busy! Is another session active?\n"));
429 * Empirical experience shows some server/OS combinations
430 * may need a brief pause even after any lockfiles on the
431 * server are released, to give the server time to finish
432 * copying back very large mailfolders from the temp-file...
433 * this is only ever an issue with extremely large mailboxes.
435 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
437 /* we're peek-capable if use of TOP is enabled */
438 peek_capable = !(ctl->fetchall || ctl->keep);
444 static int pop3_gettopid( int sock, int num , char *id)
448 char buf [POPBUFSIZE+1];
449 sprintf( buf, "TOP %d 1", num );
450 if ((ok = gen_transact(sock, buf )) != 0)
453 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
457 if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
459 /* prevent stack overflows */
461 sscanf( buf+12, "%s", id);
467 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
469 /* This approach tries to get the message headers from the
470 * remote hosts and compares the message-id to the already known
472 * + if the first message containes a new id, all messages on
473 * the server will be new
474 * + if the first is known, try to estimate the last known message
475 * on the server and check. If this works you know the total number
476 * of messages to get.
477 * + Otherwise run a binary search to determine the last known message
479 int ok, nolinear = 0;
480 int first_nr, list_len, try_id, try_nr, add_id;
484 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
487 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
488 /* the first message is unknown -> all messages are new */
493 /* check where we expect the latest known message */
494 list_len = count_list( &ctl->oldsaved );
495 try_id = list_len - first_nr; /* -1 + 1 */
497 if( try_id <= *countp ) {
498 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
501 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
506 if( try_nr != list_len -1 ) {
507 /* some messages inbetween have been deleted... */
511 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
513 for( ; add_id; add_id >>= 1 ) {
515 if( try_id - add_id <= 1 ) {
522 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
524 try_nr = str_nr_in_list(&ctl->oldsaved, id);
531 GT_("Messages inserted into list on server. Cannot handle this.\n"));
536 /* the first try_id messages are known -> copy them to the newsaved list */
537 for( num = first_nr; num < list_len; num++ )
539 struct idlist *new = save_str(&ctl->newsaved,
540 str_from_nr_list(&ctl->oldsaved, num),
542 new->val.status.num = num - first_nr + 1;
546 free_str_list(&ctl->oldsaved);
551 *newp = *countp - try_id;
555 static int pop3_getrange(int sock,
558 int *countp, int *newp, int *bytes)
559 /* get range of messages to be fetched */
562 char buf [POPBUFSIZE+1];
564 /* Ensure that the new list is properly empty */
565 ctl->newsaved = (struct idlist *)NULL;
568 /* Alain Knaff suggests this, but it's not RFC standard */
570 if ((ok = gen_transact(sock, "MBOX %s", folder)))
574 /* get the total message count */
575 gen_send(sock, "STAT");
576 ok = pop3_ok(sock, buf);
578 sscanf(buf,"%d %d", countp, bytes);
583 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
584 * We work as hard as possible to hide this ugliness, but it makes
585 * counting new messages intrinsically quadratic in the worst case.
589 if (*countp > 0 && !ctl->fetchall)
593 if (!ctl->server.uidl) {
594 gen_send(sock, "LAST");
595 ok = pop3_ok(sock, buf);
600 if (sscanf(buf, "%d", &last) == 0)
602 report(stderr, GT_("protocol error\n"));
605 *newp = (*countp - last);
609 /* grab the mailbox's UID list */
610 if ((ok = gen_transact(sock, "UIDL")) != 0)
612 /* don't worry, yet! do it the slow way */
613 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
615 report(stderr, GT_("protocol error while fetching UIDLs\n"));
624 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
628 else if (sscanf(buf, "%d %s", &num, id) == 2)
632 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
633 new->val.status.num = num;
635 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
636 new->val.status.mark = UID_SEEN;
637 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
650 static int pop3_getsizes(int sock, int count, int *sizes)
651 /* capture the sizes of all messages */
655 if ((ok = gen_transact(sock, "LIST")) != 0)
659 char buf [POPBUFSIZE+1];
661 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
663 unsigned int num, size;
667 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
668 if (num > 0 && num <= count)
669 sizes[num - 1] = size;
671 /* warn about possible attempt to induce buffer overrun */
672 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
680 static int pop3_is_old(int sock, struct query *ctl, int num)
681 /* is the given message old? */
684 return (num <= last);
686 return (str_in_list(&ctl->oldsaved,
687 str_find(&ctl->newsaved, num), FALSE));
692 * We could use this to fetch headers only as we do for IMAP. The trouble
693 * is that there's no way to fetch the body only. So the following RETR
694 * would have to re-fetch the header. Enough messages have longer headers
695 * than bodies to make this a net loss.
697 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
698 /* request headers of nth message */
701 char buf[POPBUFSIZE+1];
703 gen_send(sock, "TOP %d 0", number);
704 if ((ok = pop3_ok(sock, buf)) != 0)
707 *lenp = -1; /* we got sizes from the LIST response */
713 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
714 /* request nth message */
717 char buf[POPBUFSIZE+1];
721 * See http://www.demon.net/services/mail/sdps-tech.html
722 * for a description of what we're parsing here.
724 if (ctl->server.sdps)
728 sdps_envfrom = (char *)NULL;
729 sdps_envto = (char *)NULL;
730 gen_send(sock, "*ENV %d", number);
732 if (gen_recv(sock, buf, sizeof(buf)))
739 /* No need to wrap envelope from address */
740 sdps_envfrom = xmalloc(strlen(buf)+1);
741 strcpy(sdps_envfrom,buf);
744 /* Wrap address with To: <> so nxtaddr() likes it */
745 sdps_envto = xmalloc(strlen(buf)+7);
746 sprintf(sdps_envto,"To: <%s>",buf);
750 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
752 #endif /* SDPS_ENABLE */
755 * Though the POP RFCs don't document this fact, on almost every
756 * POP3 server I know of messages are marked "seen" only at the
757 * time the OK response to a RETR is issued.
759 * This means we can use TOP to fetch the message without setting its
760 * seen flag. This is good! It means that if the protocol exchange
761 * craps out during the message, it will still be marked `unseen' on
762 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
763 * reported to mark messages seen on a TOP fetch.)
765 * However...*don't* do this if we're using keep to suppress deletion!
766 * In that case, marking the seen flag is the only way to prevent the
767 * message from being re-fetched on subsequent runs.
769 * Also use RETR if fetchall is on. This gives us a workaround
770 * for servers like usa.net's that bungle TOP. It's pretty
771 * harmless because fetchall guarantees that any message dropped
772 * by an interrupted RETR will be picked up on the next poll of the
775 * We take advantage here of the fact that, according to all the
776 * POP RFCs, "if the number of lines requested by the POP3 client
777 * is greater than than the number of lines in the body, then the
778 * POP3 server sends the entire message.").
780 * The line count passed (99999999) is the maximum value CompuServe will
781 * accept; it's much lower than the natural value 2147483646 (the maximum
782 * twos-complement signed 32-bit integer minus 1) */
783 if (ctl->keep || ctl->fetchall)
784 gen_send(sock, "RETR %d", number);
786 gen_send(sock, "TOP %d 99999999", number);
787 if ((ok = pop3_ok(sock, buf)) != 0)
790 *lenp = -1; /* we got sizes from the LIST response */
795 static void mark_uid_seen(struct query *ctl, int number)
796 /* Tell the UID code we've seen this. */
802 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
803 if (sdp->val.status.num == number)
805 sdp->val.status.mark = UID_SEEN;
806 save_str(&ctl->oldsaved, sdp->id,UID_SEEN);
811 static int pop3_delete(int sock, struct query *ctl, int number)
812 /* delete a given message */
815 mark_uid_seen(ctl, number);
816 /* actually, mark for deletion -- doesn't happen until QUIT time */
817 ok = gen_transact(sock, "DELE %d", number);
818 if (ok != PS_SUCCESS)
820 delete_str(&ctl->newsaved, number);
824 static int pop3_mark_seen(int sock, struct query *ctl, int number)
825 /* mark a given message as seen */
827 mark_uid_seen(ctl, number);
831 static int pop3_logout(int sock, struct query *ctl)
832 /* send logout command */
838 * We used to do this in case the server marks messages deleted when seen.
839 * (Yes, this has been reported, in the MercuryP/NLM server.
840 * It's even legal under RFC 1939 (section 8) as a site policy.)
841 * It interacted badly with UIDL, though. Thomas Zajic wrote:
842 * "Running 'fetchmail -F -v' and checking the logs, I found out
843 * that fetchmail did in fact flush my mailbox properly, but sent
844 * a RSET just before sending QUIT to log off. This caused the
845 * POP3 server to undo/forget about the previous DELEs, resetting
846 * my mailbox to its original (ie. unflushed) state. The
847 * ~/.fetchids file did get flushed though, so the next time
848 * fetchmail was run it saw all the old messages as new ones ..."
851 gen_transact(sock, "RSET");
852 #endif /* __UNUSED__ */
854 ok = gen_transact(sock, "QUIT");
867 const static struct method pop3 =
869 "POP3", /* Post Office Protocol v3 */
871 "pop3", /* standard POP3 port */
872 "pop3s", /* ssl POP3 port */
873 #else /* INET6_ENABLE */
874 110, /* standard POP3 port */
875 995, /* ssl POP3 port */
876 #endif /* INET6_ENABLE */
877 FALSE, /* this is not a tagged protocol */
878 TRUE, /* this uses a message delimiter */
879 pop3_ok, /* parse command response */
880 pop3_getauth, /* get authorization */
881 pop3_getrange, /* query range of messages */
882 pop3_getsizes, /* we can get a list of sizes */
883 pop3_is_old, /* how do we tell a message is old? */
884 pop3_fetch, /* request given message */
885 NULL, /* no way to fetch body alone */
886 NULL, /* no message trailer */
887 pop3_delete, /* how to delete a message */
888 pop3_mark_seen, /* how to mark a message as seen */
889 pop3_logout, /* log out, we're done */
890 FALSE, /* no, we can't re-poll */
893 int doPOP3 (struct query *ctl)
894 /* retrieve messages using POP3 */
897 if (ctl->mailboxes->id) {
898 fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
902 peek_capable = !ctl->fetchall;
903 return(do_protocol(ctl, &pop3));
905 #endif /* POP3_ENABLE */
907 /* pop3.c ends here */