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 /* these variables are shared between the CAPA probe and the authenticator */
44 flag has_gssapi = FALSE;
45 #endif /* defined(GSSAPI) */
46 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
47 flag has_kerberos = FALSE;
48 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
49 flag has_cram = FALSE;
52 #endif /* OPIE_ENABLE */
55 #endif /* SSL_ENABLE */
57 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
59 static int pop3_ok (int sock, char *argbuf)
60 /* parse command response */
63 char buf [POPBUFSIZE+1];
66 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
68 if (*bufp == '+' || *bufp == '-')
73 while (isalpha(*bufp))
79 if (strcmp(buf,"+OK") == 0)
83 #endif /* OPIE_ENABLE */
86 else if (strncmp(buf,"-ERR", 4) == 0)
88 if (stage == STAGE_FETCH)
90 else if (stage > STAGE_GETAUTH)
93 * We're checking for "lock busy", "unable to lock",
94 * "already locked", "wait a few minutes" etc. here.
95 * This indicates that we have to wait for the server to
96 * unwedge itself before we can poll again.
98 * PS_LOCKBUSY check empirically verified with two recent
99 * versions of the Berkeley popper; QPOP (version 2.2) and
100 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
101 * These are caught by the case-indifferent "lock" check.
102 * The "wait" catches "mail storage services unavailable,
103 * wait a few minutes and try again" on the InterMail server.
105 * If these aren't picked up on correctly, fetchmail will
106 * think there is an authentication failure and wedge the
107 * connection in order to prevent futile polls.
111 else if (strstr(bufp,"lock")
112 || strstr(bufp,"Lock")
113 || strstr(bufp,"LOCK")
114 || strstr(bufp,"wait")
115 /* these are blessed by RFC 2449 */
116 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
118 else if ((strstr(bufp,"Service")
119 || strstr(bufp,"service"))
120 && (strstr(bufp,"unavailable")))
125 * We always want to pass the user lock-busy messages, because
126 * they're red flags. Other stuff (like AUTH failures on non-
127 * RFC1734 servers) only if we're debugging.
129 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
130 report(stderr, "%s\n", bufp);
144 static int capa_probe(sock)
145 /* probe the capabilities of the remote server */
149 ok = gen_transact(sock, "CAPA");
150 if (ok == PS_SUCCESS)
154 /* determine what authentication methods we have available */
155 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
160 if (strstr(buffer, "STLS"))
162 #endif /* SSL_ENABLE */
164 if (strstr(buffer, "GSSAPI"))
166 #endif /* defined(GSSAPI) */
167 #if defined(KERBEROS_V4)
168 if (strstr(buffer, "KERBEROS_V4"))
170 #endif /* defined(KERBEROS_V4) */
172 if (strstr(buffer, "X-OTP"))
174 #endif /* OPIE_ENABLE */
175 if (strstr(buffer, "CRAM-MD5"))
182 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
183 /* apply for connection authorization */
190 #endif /* OPIE_ENABLE */
192 flag did_stls = FALSE;
193 #endif /* SSL_ENABLE */
195 if (ctl->server.authenticate == A_SSH) {
201 * This needs to catch both demon.co.uk and demon.net.
202 * If we see either, and we're in multidrop mode, try to use
203 * the SDPS *ENV extension.
205 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
206 ctl->server.sdps = TRUE;
207 #endif /* SDPS_ENABLE */
209 switch (ctl->server.protocol) {
212 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
213 if (strstr(ctl->remotename, "@compuserve.com"))
215 /* AUTH command should return a list of available mechanisms */
216 if (gen_transact(sock, "AUTH") == 0)
219 flag has_rpa = FALSE;
221 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
225 if (strncasecmp(buffer, "rpa", 3) == 0)
228 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
229 ctl->password, sock))
235 #endif /* RPA_ENABLE */
238 * CAPA command may return a list including available
239 * authentication mechanisms. if it doesn't, no harm done, we
240 * just fall back to a plain login. Note that this code
241 * latches the server's authentication type, so that in daemon mode
242 * the CAPA check only needs to be done once at start of run.
244 * If CAPA fails, then force the authentication method to PASSORD
245 * and repoll immediately.
247 * These authentication methods are blessed by RFC1734,
248 * describing the POP3 AUTHentication command.
250 if (ctl->server.authenticate == A_ANY)
252 if (capa_probe(sock) != PS_SUCCESS)
253 /* we are in STAGE_GETAUTH! */
254 if (ok == PS_AUTHFAIL ||
255 /* Some servers directly close the socket. However, if we
256 * have already authenticated before, then a previous CAPA
257 * must have succeeded. In that case, treat this as a
258 * genuine socket error and do not change the auth method.
260 (ok == PS_SOCKET && !ctl->wehaveauthed))
262 ctl->server.authenticate = A_PASSWORD;
263 /* repoll immediately */
272 && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
276 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
277 ok = gen_transact(sock, "STLS");
279 /* We use "tls1" instead of ctl->sslproto, as we want STLS,
280 * not other SSL protocols
282 if (ok == PS_SUCCESS &&
283 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
285 if (!ctl->sslproto && !ctl->wehaveauthed)
287 ctl->sslproto = xstrdup("");
288 /* repoll immediately */
292 GT_("SSL connection failed.\n"));
298 * RFC 2595 says this:
300 * "Once TLS has been started, the client MUST discard cached
301 * information about server capabilities and SHOULD re-issue the
302 * CAPABILITY command. This is necessary to protect against
303 * man-in-the-middle attacks which alter the capabilities list prior
304 * to STARTTLS. The server MAY advertise different capabilities
309 #endif /* SSL_ENABLE */
312 * OK, we have an authentication type now.
314 #if defined(KERBEROS_V4)
316 * Servers doing KPOP have to go through a dummy login sequence
317 * rather than doing SASL.
321 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
322 #else /* INET6_ENABLE */
323 ctl->server.port != KPOP_PORT
324 #endif /* INET6_ENABLE */
325 && (ctl->server.authenticate == A_KERBEROS_V4
326 || ctl->server.authenticate == A_KERBEROS_V5
327 || ctl->server.authenticate == A_ANY))
329 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
330 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
333 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
337 (ctl->server.authenticate == A_GSSAPI ||
338 ctl->server.authenticate == A_ANY))
340 ok = do_gssauth(sock,"AUTH",ctl->server.truename,ctl->remotename);
341 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
344 #endif /* defined(GSSAPI) */
348 (ctl->server.authenticate == A_OTP ||
349 ctl->server.authenticate == A_ANY))
351 ok = do_otp(sock, "AUTH", ctl);
352 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
355 #endif /* OPIE_ENABLE */
357 if (ctl->server.authenticate == A_CRAM_MD5 ||
358 (has_cram && ctl->server.authenticate == A_ANY))
360 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
361 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
365 /* ordinary validation, no one-time password or RPA */
366 gen_transact(sock, "USER %s", ctl->remotename);
369 /* see RFC1938: A One-Time Password System */
370 if (challenge = strstr(lastok, "otp-")) {
371 char response[OPIE_RESPONSE_MAX+1];
374 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
375 if ((i == -2) && !run.poll_interval) {
376 char secret[OPIE_SECRET_MAX+1];
377 fprintf(stderr, GT_("Secret pass phrase: "));
378 if (opiereadpass(secret, sizeof(secret), 0))
379 i = opiegenerator(challenge, secret, response);
380 memset(secret, 0, sizeof(secret));
388 ok = gen_transact(sock, "PASS %s", response);
391 #endif /* OPIE_ENABLE */
393 strcpy(shroud, ctl->password);
394 ok = gen_transact(sock, "PASS %s", ctl->password);
397 /* this is for servers which claim to support TLS, but actually
399 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
401 ctl->sslproto = xstrdup("");
402 /* repoll immediately */
409 /* build MD5 digest from greeting timestamp + password */
410 /* find start of timestamp */
411 for (start = greeting; *start != 0 && *start != '<'; start++)
415 GT_("Required APOP timestamp not found in greeting\n"));
419 /* find end of timestamp */
420 for (end = start; *end != 0 && *end != '>'; end++)
422 if (*end == 0 || end == start + 1) {
424 GT_("Timestamp syntax error in greeting\n"));
430 /* copy timestamp and password into digestion buffer */
431 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
433 strcat(msg,ctl->password);
435 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
437 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
441 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
442 ok = gen_transact(sock, "RPOP %s", ctl->password);
446 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
452 /* maybe we detected a lock-busy condition? */
453 if (ok == PS_LOCKBUSY)
454 report(stderr, GT_("lock busy! Is another session active?\n"));
460 * Empirical experience shows some server/OS combinations
461 * may need a brief pause even after any lockfiles on the
462 * server are released, to give the server time to finish
463 * copying back very large mailfolders from the temp-file...
464 * this is only ever an issue with extremely large mailboxes.
466 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
468 /* we're peek-capable if use of TOP is enabled */
469 peek_capable = !(ctl->fetchall || ctl->keep);
475 static int pop3_gettopid( int sock, int num , char *id)
479 char buf [POPBUFSIZE+1];
480 sprintf( buf, "TOP %d 1", num );
481 if ((ok = gen_transact(sock, buf )) != 0)
484 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
488 if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
490 /* prevent stack overflows */
492 sscanf( buf+12, "%s", id);
498 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
500 /* This approach tries to get the message headers from the
501 * remote hosts and compares the message-id to the already known
503 * + if the first message containes a new id, all messages on
504 * the server will be new
505 * + if the first is known, try to estimate the last known message
506 * on the server and check. If this works you know the total number
507 * of messages to get.
508 * + Otherwise run a binary search to determine the last known message
510 int ok, nolinear = 0;
511 int first_nr, list_len, try_id, try_nr, add_id;
515 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
518 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
519 /* the first message is unknown -> all messages are new */
524 /* check where we expect the latest known message */
525 list_len = count_list( &ctl->oldsaved );
526 try_id = list_len - first_nr; /* -1 + 1 */
528 if( try_id <= *countp ) {
529 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
532 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
537 if( try_nr != list_len -1 ) {
538 /* some messages inbetween have been deleted... */
542 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
544 for( ; add_id; add_id >>= 1 ) {
546 if( try_id - add_id <= 1 ) {
553 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
555 try_nr = str_nr_in_list(&ctl->oldsaved, id);
562 GT_("Messages inserted into list on server. Cannot handle this.\n"));
567 /* the first try_id messages are known -> copy them to the newsaved list */
568 for( num = first_nr; num < list_len; num++ )
570 struct idlist *new = save_str(&ctl->newsaved,
571 str_from_nr_list(&ctl->oldsaved, num),
573 new->val.status.num = num - first_nr + 1;
577 free_str_list(&ctl->oldsaved);
582 *newp = *countp - try_id;
586 static int pop3_getrange(int sock,
589 int *countp, int *newp, int *bytes)
590 /* get range of messages to be fetched */
593 char buf [POPBUFSIZE+1];
595 /* Ensure that the new list is properly empty */
596 ctl->newsaved = (struct idlist *)NULL;
599 /* Alain Knaff suggests this, but it's not RFC standard */
601 if ((ok = gen_transact(sock, "MBOX %s", folder)))
605 /* get the total message count */
606 gen_send(sock, "STAT");
607 ok = pop3_ok(sock, buf);
609 sscanf(buf,"%d %d", countp, bytes);
614 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
615 * We work as hard as possible to hide this ugliness, but it makes
616 * counting new messages intrinsically quadratic in the worst case.
620 if (*countp > 0 && !ctl->fetchall)
624 if (!ctl->server.uidl) {
625 gen_send(sock, "LAST");
626 ok = pop3_ok(sock, buf);
631 if (sscanf(buf, "%d", &last) == 0)
633 report(stderr, GT_("protocol error\n"));
636 *newp = (*countp - last);
640 /* grab the mailbox's UID list */
641 if ((ok = gen_transact(sock, "UIDL")) != 0)
643 /* don't worry, yet! do it the slow way */
644 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
646 report(stderr, GT_("protocol error while fetching UIDLs\n"));
655 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
659 else if (sscanf(buf, "%d %s", &num, id) == 2)
663 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
664 new->val.status.num = num;
666 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
667 new->val.status.mark = UID_SEEN;
668 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
681 static int pop3_getsizes(int sock, int count, int *sizes)
682 /* capture the sizes of all messages */
686 if ((ok = gen_transact(sock, "LIST")) != 0)
690 char buf [POPBUFSIZE+1];
692 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
694 unsigned int num, size;
698 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
699 if (num > 0 && num <= count)
700 sizes[num - 1] = size;
702 /* warn about possible attempt to induce buffer overrun */
703 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
711 static int pop3_is_old(int sock, struct query *ctl, int num)
712 /* is the given message old? */
715 return (num <= last);
717 return (str_in_list(&ctl->oldsaved,
718 str_find(&ctl->newsaved, num), FALSE));
723 * We could use this to fetch headers only as we do for IMAP. The trouble
724 * is that there's no way to fetch the body only. So the following RETR
725 * would have to re-fetch the header. Enough messages have longer headers
726 * than bodies to make this a net loss.
728 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
729 /* request headers of nth message */
732 char buf[POPBUFSIZE+1];
734 gen_send(sock, "TOP %d 0", number);
735 if ((ok = pop3_ok(sock, buf)) != 0)
738 *lenp = -1; /* we got sizes from the LIST response */
744 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
745 /* request nth message */
748 char buf[POPBUFSIZE+1];
752 * See http://www.demon.net/services/mail/sdps-tech.html
753 * for a description of what we're parsing here.
755 if (ctl->server.sdps)
759 sdps_envfrom = (char *)NULL;
760 sdps_envto = (char *)NULL;
761 gen_send(sock, "*ENV %d", number);
763 if (gen_recv(sock, buf, sizeof(buf)))
770 /* No need to wrap envelope from address */
771 sdps_envfrom = xmalloc(strlen(buf)+1);
772 strcpy(sdps_envfrom,buf);
775 /* Wrap address with To: <> so nxtaddr() likes it */
776 sdps_envto = xmalloc(strlen(buf)+7);
777 sprintf(sdps_envto,"To: <%s>",buf);
781 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
783 #endif /* SDPS_ENABLE */
786 * Though the POP RFCs don't document this fact, on almost every
787 * POP3 server I know of messages are marked "seen" only at the
788 * time the OK response to a RETR is issued.
790 * This means we can use TOP to fetch the message without setting its
791 * seen flag. This is good! It means that if the protocol exchange
792 * craps out during the message, it will still be marked `unseen' on
793 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
794 * reported to mark messages seen on a TOP fetch.)
796 * However...*don't* do this if we're using keep to suppress deletion!
797 * In that case, marking the seen flag is the only way to prevent the
798 * message from being re-fetched on subsequent runs.
800 * Also use RETR if fetchall is on. This gives us a workaround
801 * for servers like usa.net's that bungle TOP. It's pretty
802 * harmless because fetchall guarantees that any message dropped
803 * by an interrupted RETR will be picked up on the next poll of the
806 * We take advantage here of the fact that, according to all the
807 * POP RFCs, "if the number of lines requested by the POP3 client
808 * is greater than than the number of lines in the body, then the
809 * POP3 server sends the entire message.").
811 * The line count passed (99999999) is the maximum value CompuServe will
812 * accept; it's much lower than the natural value 2147483646 (the maximum
813 * twos-complement signed 32-bit integer minus 1) */
814 if (ctl->keep || ctl->fetchall)
815 gen_send(sock, "RETR %d", number);
817 gen_send(sock, "TOP %d 99999999", number);
818 if ((ok = pop3_ok(sock, buf)) != 0)
821 *lenp = -1; /* we got sizes from the LIST response */
826 static void mark_uid_seen(struct query *ctl, int number)
827 /* Tell the UID code we've seen this. */
833 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
834 if (sdp->val.status.num == number)
836 sdp->val.status.mark = UID_SEEN;
837 save_str(&ctl->oldsaved, sdp->id,UID_SEEN);
842 static int pop3_delete(int sock, struct query *ctl, int number)
843 /* delete a given message */
846 mark_uid_seen(ctl, number);
847 /* actually, mark for deletion -- doesn't happen until QUIT time */
848 ok = gen_transact(sock, "DELE %d", number);
849 if (ok != PS_SUCCESS)
851 delete_str(&ctl->newsaved, number);
855 static int pop3_mark_seen(int sock, struct query *ctl, int number)
856 /* mark a given message as seen */
858 mark_uid_seen(ctl, number);
862 static int pop3_logout(int sock, struct query *ctl)
863 /* send logout command */
869 * We used to do this in case the server marks messages deleted when seen.
870 * (Yes, this has been reported, in the MercuryP/NLM server.
871 * It's even legal under RFC 1939 (section 8) as a site policy.)
872 * It interacted badly with UIDL, though. Thomas Zajic wrote:
873 * "Running 'fetchmail -F -v' and checking the logs, I found out
874 * that fetchmail did in fact flush my mailbox properly, but sent
875 * a RSET just before sending QUIT to log off. This caused the
876 * POP3 server to undo/forget about the previous DELEs, resetting
877 * my mailbox to its original (ie. unflushed) state. The
878 * ~/.fetchids file did get flushed though, so the next time
879 * fetchmail was run it saw all the old messages as new ones ..."
882 gen_transact(sock, "RSET");
883 #endif /* __UNUSED__ */
885 ok = gen_transact(sock, "QUIT");
898 const static struct method pop3 =
900 "POP3", /* Post Office Protocol v3 */
902 "pop3", /* standard POP3 port */
903 "pop3s", /* ssl POP3 port */
904 #else /* INET6_ENABLE */
905 110, /* standard POP3 port */
906 995, /* ssl POP3 port */
907 #endif /* INET6_ENABLE */
908 FALSE, /* this is not a tagged protocol */
909 TRUE, /* this uses a message delimiter */
910 pop3_ok, /* parse command response */
911 pop3_getauth, /* get authorization */
912 pop3_getrange, /* query range of messages */
913 pop3_getsizes, /* we can get a list of sizes */
914 pop3_is_old, /* how do we tell a message is old? */
915 pop3_fetch, /* request given message */
916 NULL, /* no way to fetch body alone */
917 NULL, /* no message trailer */
918 pop3_delete, /* how to delete a message */
919 pop3_mark_seen, /* how to mark a message as seen */
920 pop3_logout, /* log out, we're done */
921 FALSE, /* no, we can't re-poll */
924 int doPOP3 (struct query *ctl)
925 /* retrieve messages using POP3 */
928 if (ctl->mailboxes->id) {
929 fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
933 peek_capable = !ctl->fetchall;
934 return(do_protocol(ctl, &pop3));
936 #endif /* POP3_ENABLE */
938 /* pop3.c ends here */