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 */
197 * This needs to catch both demon.co.uk and demon.net.
198 * If we see either, and we're in multidrop mode, try to use
199 * the SDPS *ENV extension.
201 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
202 ctl->server.sdps = TRUE;
203 #endif /* SDPS_ENABLE */
205 switch (ctl->server.protocol) {
208 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
209 if (strstr(ctl->remotename, "@compuserve.com"))
211 /* AUTH command should return a list of available mechanisms */
212 if (gen_transact(sock, "AUTH") == 0)
215 flag has_rpa = FALSE;
217 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
221 if (strncasecmp(buffer, "rpa", 3) == 0)
224 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
225 ctl->password, sock))
231 #endif /* RPA_ENABLE */
234 * CAPA command may return a list including available
235 * authentication mechanisms. if it doesn't, no harm done, we
236 * just fall back to a plain login. Note that this code
237 * latches the server's authentication type, so that in daemon mode
238 * the CAPA check only needs to be done once at start of run.
240 * If CAPA fails, then force the authentication method to PASSORD
241 * and repoll immediately.
243 * These authentication methods are blessed by RFC1734,
244 * describing the POP3 AUTHentication command.
246 if (ctl->server.authenticate == A_ANY)
248 if (capa_probe(sock) != PS_SUCCESS)
249 /* we are in STAGE_GETAUTH! */
250 if (ok == PS_AUTHFAIL ||
251 /* Some servers directly close the socket. However, if we
252 * have already authenticated before, then a previous CAPA
253 * must have succeeded. In that case, treat this as a
254 * genuine socket error and do not change the auth method.
256 (ok == PS_SOCKET && !ctl->wehaveauthed))
258 ctl->server.authenticate = A_PASSWORD;
259 /* repoll immediately */
268 && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
272 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
273 ok = gen_transact(sock, "STLS");
275 /* We use "tls1" instead of ctl->sslproto, as we want STLS,
276 * not other SSL protocols
278 if (ok == PS_SUCCESS &&
279 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
281 if (!ctl->sslproto && !ctl->wehaveauthed)
283 ctl->sslproto = xstrdup("");
284 /* repoll immediately */
288 GT_("SSL connection failed.\n"));
294 * RFC 2595 says this:
296 * "Once TLS has been started, the client MUST discard cached
297 * information about server capabilities and SHOULD re-issue the
298 * CAPABILITY command. This is necessary to protect against
299 * man-in-the-middle attacks which alter the capabilities list prior
300 * to STARTTLS. The server MAY advertise different capabilities
305 #endif /* SSL_ENABLE */
308 * OK, we have an authentication type now.
310 #if defined(KERBEROS_V4)
312 * Servers doing KPOP have to go through a dummy login sequence
313 * rather than doing SASL.
317 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
318 #else /* INET6_ENABLE */
319 ctl->server.port != KPOP_PORT
320 #endif /* INET6_ENABLE */
321 && (ctl->server.authenticate == A_KERBEROS_V4
322 || ctl->server.authenticate == A_KERBEROS_V5
323 || ctl->server.authenticate == A_ANY))
325 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
326 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
329 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
333 (ctl->server.authenticate == A_GSSAPI ||
334 ctl->server.authenticate == A_ANY))
336 ok = do_gssauth(sock,"AUTH",ctl->server.truename,ctl->remotename);
337 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
340 #endif /* defined(GSSAPI) */
344 (ctl->server.authenticate == A_OTP ||
345 ctl->server.authenticate == A_ANY))
347 ok = do_otp(sock, "AUTH", ctl);
348 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
351 #endif /* OPIE_ENABLE */
354 (ctl->server.authenticate == A_CRAM_MD5 ||
355 ctl->server.authenticate == A_ANY))
357 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
358 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
362 /* ordinary validation, no one-time password or RPA */
363 gen_transact(sock, "USER %s", ctl->remotename);
366 /* see RFC1938: A One-Time Password System */
367 if (challenge = strstr(lastok, "otp-")) {
368 char response[OPIE_RESPONSE_MAX+1];
371 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
372 if ((i == -2) && !run.poll_interval) {
373 char secret[OPIE_SECRET_MAX+1];
374 fprintf(stderr, GT_("Secret pass phrase: "));
375 if (opiereadpass(secret, sizeof(secret), 0))
376 i = opiegenerator(challenge, secret, response);
377 memset(secret, 0, sizeof(secret));
385 ok = gen_transact(sock, "PASS %s", response);
388 #endif /* OPIE_ENABLE */
390 strcpy(shroud, ctl->password);
391 ok = gen_transact(sock, "PASS %s", ctl->password);
394 /* this is for servers which claim to support TLS, but actually
396 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
398 ctl->sslproto = xstrdup("");
399 /* repoll immediately */
406 /* build MD5 digest from greeting timestamp + password */
407 /* find start of timestamp */
408 for (start = greeting; *start != 0 && *start != '<'; start++)
412 GT_("Required APOP timestamp not found in greeting\n"));
416 /* find end of timestamp */
417 for (end = start; *end != 0 && *end != '>'; end++)
419 if (*end == 0 || end == start + 1) {
421 GT_("Timestamp syntax error in greeting\n"));
427 /* copy timestamp and password into digestion buffer */
428 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
430 strcat(msg,ctl->password);
432 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
434 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
438 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
439 ok = gen_transact(sock, "RPOP %s", ctl->password);
443 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
449 /* maybe we detected a lock-busy condition? */
450 if (ok == PS_LOCKBUSY)
451 report(stderr, GT_("lock busy! Is another session active?\n"));
457 * Empirical experience shows some server/OS combinations
458 * may need a brief pause even after any lockfiles on the
459 * server are released, to give the server time to finish
460 * copying back very large mailfolders from the temp-file...
461 * this is only ever an issue with extremely large mailboxes.
463 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
465 /* we're peek-capable if use of TOP is enabled */
466 peek_capable = !(ctl->fetchall || ctl->keep);
472 static int pop3_gettopid( int sock, int num , char *id)
476 char buf [POPBUFSIZE+1];
477 sprintf( buf, "TOP %d 1", num );
478 if ((ok = gen_transact(sock, buf )) != 0)
481 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
485 if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
487 /* prevent stack overflows */
489 sscanf( buf+12, "%s", id);
495 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
497 /* This approach tries to get the message headers from the
498 * remote hosts and compares the message-id to the already known
500 * + if the first message containes a new id, all messages on
501 * the server will be new
502 * + if the first is known, try to estimate the last known message
503 * on the server and check. If this works you know the total number
504 * of messages to get.
505 * + Otherwise run a binary search to determine the last known message
507 int ok, nolinear = 0;
508 int first_nr, list_len, try_id, try_nr, add_id;
512 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
515 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
516 /* the first message is unknown -> all messages are new */
521 /* check where we expect the latest known message */
522 list_len = count_list( &ctl->oldsaved );
523 try_id = list_len - first_nr; /* -1 + 1 */
525 if( try_id <= *countp ) {
526 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
529 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
534 if( try_nr != list_len -1 ) {
535 /* some messages inbetween have been deleted... */
539 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
541 for( ; add_id; add_id >>= 1 ) {
543 if( try_id - add_id <= 1 ) {
550 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
552 try_nr = str_nr_in_list(&ctl->oldsaved, id);
559 GT_("Messages inserted into list on server. Cannot handle this.\n"));
564 /* the first try_id messages are known -> copy them to the newsaved list */
565 for( num = first_nr; num < list_len; num++ )
567 struct idlist *new = save_str(&ctl->newsaved,
568 str_from_nr_list(&ctl->oldsaved, num),
570 new->val.status.num = num - first_nr + 1;
574 free_str_list(&ctl->oldsaved);
579 *newp = *countp - try_id;
583 static int pop3_getrange(int sock,
586 int *countp, int *newp, int *bytes)
587 /* get range of messages to be fetched */
590 char buf [POPBUFSIZE+1];
592 /* Ensure that the new list is properly empty */
593 ctl->newsaved = (struct idlist *)NULL;
596 /* Alain Knaff suggests this, but it's not RFC standard */
598 if ((ok = gen_transact(sock, "MBOX %s", folder)))
602 /* get the total message count */
603 gen_send(sock, "STAT");
604 ok = pop3_ok(sock, buf);
606 sscanf(buf,"%d %d", countp, bytes);
611 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
612 * We work as hard as possible to hide this ugliness, but it makes
613 * counting new messages intrinsically quadratic in the worst case.
617 if (*countp > 0 && !ctl->fetchall)
621 if (!ctl->server.uidl) {
622 gen_send(sock, "LAST");
623 ok = pop3_ok(sock, buf);
628 if (sscanf(buf, "%d", &last) == 0)
630 report(stderr, GT_("protocol error\n"));
633 *newp = (*countp - last);
637 /* grab the mailbox's UID list */
638 if ((ok = gen_transact(sock, "UIDL")) != 0)
640 /* don't worry, yet! do it the slow way */
641 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
643 report(stderr, GT_("protocol error while fetching UIDLs\n"));
652 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
656 else if (sscanf(buf, "%d %s", &num, id) == 2)
660 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
661 new->val.status.num = num;
663 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
664 new->val.status.mark = UID_SEEN;
665 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
678 static int pop3_getsizes(int sock, int count, int *sizes)
679 /* capture the sizes of all messages */
683 if ((ok = gen_transact(sock, "LIST")) != 0)
687 char buf [POPBUFSIZE+1];
689 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
691 unsigned int num, size;
695 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
696 if (num > 0 && num <= count)
697 sizes[num - 1] = size;
699 /* warn about possible attempt to induce buffer overrun */
700 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
708 static int pop3_is_old(int sock, struct query *ctl, int num)
709 /* is the given message old? */
712 return (num <= last);
714 return (str_in_list(&ctl->oldsaved,
715 str_find(&ctl->newsaved, num), FALSE));
720 * We could use this to fetch headers only as we do for IMAP. The trouble
721 * is that there's no way to fetch the body only. So the following RETR
722 * would have to re-fetch the header. Enough messages have longer headers
723 * than bodies to make this a net loss.
725 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
726 /* request headers of nth message */
729 char buf[POPBUFSIZE+1];
731 gen_send(sock, "TOP %d 0", number);
732 if ((ok = pop3_ok(sock, buf)) != 0)
735 *lenp = -1; /* we got sizes from the LIST response */
741 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
742 /* request nth message */
745 char buf[POPBUFSIZE+1];
749 * See http://www.demon.net/services/mail/sdps-tech.html
750 * for a description of what we're parsing here.
752 if (ctl->server.sdps)
756 sdps_envfrom = (char *)NULL;
757 sdps_envto = (char *)NULL;
758 gen_send(sock, "*ENV %d", number);
760 if (gen_recv(sock, buf, sizeof(buf)))
767 /* No need to wrap envelope from address */
768 sdps_envfrom = xmalloc(strlen(buf)+1);
769 strcpy(sdps_envfrom,buf);
772 /* Wrap address with To: <> so nxtaddr() likes it */
773 sdps_envto = xmalloc(strlen(buf)+7);
774 sprintf(sdps_envto,"To: <%s>",buf);
778 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
780 #endif /* SDPS_ENABLE */
783 * Though the POP RFCs don't document this fact, on almost every
784 * POP3 server I know of messages are marked "seen" only at the
785 * time the OK response to a RETR is issued.
787 * This means we can use TOP to fetch the message without setting its
788 * seen flag. This is good! It means that if the protocol exchange
789 * craps out during the message, it will still be marked `unseen' on
790 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
791 * reported to mark messages seen on a TOP fetch.)
793 * However...*don't* do this if we're using keep to suppress deletion!
794 * In that case, marking the seen flag is the only way to prevent the
795 * message from being re-fetched on subsequent runs.
797 * Also use RETR if fetchall is on. This gives us a workaround
798 * for servers like usa.net's that bungle TOP. It's pretty
799 * harmless because fetchall guarantees that any message dropped
800 * by an interrupted RETR will be picked up on the next poll of the
803 * We take advantage here of the fact that, according to all the
804 * POP RFCs, "if the number of lines requested by the POP3 client
805 * is greater than than the number of lines in the body, then the
806 * POP3 server sends the entire message.").
808 * The line count passed (99999999) is the maximum value CompuServe will
809 * accept; it's much lower than the natural value 2147483646 (the maximum
810 * twos-complement signed 32-bit integer minus 1) */
811 if (ctl->keep || ctl->fetchall)
812 gen_send(sock, "RETR %d", number);
814 gen_send(sock, "TOP %d 99999999", number);
815 if ((ok = pop3_ok(sock, buf)) != 0)
818 *lenp = -1; /* we got sizes from the LIST response */
823 static void mark_uid_seen(struct query *ctl, int number)
824 /* Tell the UID code we've seen this. */
830 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
831 if (sdp->val.status.num == number)
833 sdp->val.status.mark = UID_SEEN;
834 save_str(&ctl->oldsaved, sdp->id,UID_SEEN);
839 static int pop3_delete(int sock, struct query *ctl, int number)
840 /* delete a given message */
843 mark_uid_seen(ctl, number);
844 /* actually, mark for deletion -- doesn't happen until QUIT time */
845 ok = gen_transact(sock, "DELE %d", number);
846 if (ok != PS_SUCCESS)
848 delete_str(&ctl->newsaved, number);
852 static int pop3_mark_seen(int sock, struct query *ctl, int number)
853 /* mark a given message as seen */
855 mark_uid_seen(ctl, number);
859 static int pop3_logout(int sock, struct query *ctl)
860 /* send logout command */
866 * We used to do this in case the server marks messages deleted when seen.
867 * (Yes, this has been reported, in the MercuryP/NLM server.
868 * It's even legal under RFC 1939 (section 8) as a site policy.)
869 * It interacted badly with UIDL, though. Thomas Zajic wrote:
870 * "Running 'fetchmail -F -v' and checking the logs, I found out
871 * that fetchmail did in fact flush my mailbox properly, but sent
872 * a RSET just before sending QUIT to log off. This caused the
873 * POP3 server to undo/forget about the previous DELEs, resetting
874 * my mailbox to its original (ie. unflushed) state. The
875 * ~/.fetchids file did get flushed though, so the next time
876 * fetchmail was run it saw all the old messages as new ones ..."
879 gen_transact(sock, "RSET");
880 #endif /* __UNUSED__ */
882 ok = gen_transact(sock, "QUIT");
895 const static struct method pop3 =
897 "POP3", /* Post Office Protocol v3 */
899 "pop3", /* standard POP3 port */
900 "pop3s", /* ssl POP3 port */
901 #else /* INET6_ENABLE */
902 110, /* standard POP3 port */
903 995, /* ssl POP3 port */
904 #endif /* INET6_ENABLE */
905 FALSE, /* this is not a tagged protocol */
906 TRUE, /* this uses a message delimiter */
907 pop3_ok, /* parse command response */
908 pop3_getauth, /* get authorization */
909 pop3_getrange, /* query range of messages */
910 pop3_getsizes, /* we can get a list of sizes */
911 pop3_is_old, /* how do we tell a message is old? */
912 pop3_fetch, /* request given message */
913 NULL, /* no way to fetch body alone */
914 NULL, /* no message trailer */
915 pop3_delete, /* how to delete a message */
916 pop3_mark_seen, /* how to mark a message as seen */
917 pop3_logout, /* log out, we're done */
918 FALSE, /* no, we can't re-poll */
921 int doPOP3 (struct query *ctl)
922 /* retrieve messages using POP3 */
925 if (ctl->mailboxes->id) {
926 fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
930 peek_capable = !ctl->fetchall;
931 return(do_protocol(ctl, &pop3));
933 #endif /* POP3_ENABLE */
935 /* pop3.c ends here */