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_GETAUTH)
76 * We're checking for "lock busy", "unable to lock",
77 * "already locked", "wait a few minutes" etc. here.
78 * This indicates that we have to wait for the server to
79 * unwedge itself before we can poll again.
81 * PS_LOCKBUSY check empirically verified with two recent
82 * versions of the Berkeley popper; QPOP (version 2.2) and
83 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
84 * These are caught by the case-indifferent "lock" check.
85 * The "wait" catches "mail storage services unavailable,
86 * wait a few minutes and try again" on the InterMail server.
88 * If these aren't picked up on correctly, fetchmail will
89 * think there is an authentication failure and wedge the
90 * connection in order to prevent futile polls.
94 else if (strstr(bufp,"lock")
95 || strstr(bufp,"Lock")
96 || strstr(bufp,"LOCK")
97 || strstr(bufp,"wait")
98 /* these are blessed by RFC 2449 */
99 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
101 else if ((strstr(bufp,"Service")
102 || strstr(bufp,"service"))
103 && (strstr(bufp,"unavailable")))
108 * We always want to pass the user lock-busy messages, because
109 * they're red flags. Other stuff (like AUTH failures on non-
110 * RFC1734 servers) only if we're debugging.
112 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
113 report(stderr, "%s\n", bufp);
125 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
126 /* apply for connection authorization */
133 #endif /* OPIE_ENABLE */
135 flag has_gssapi = FALSE;
136 #endif /* defined(GSSAPI) */
137 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
138 flag has_kerberos = FALSE;
139 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
140 flag has_cram = FALSE;
142 flag has_otp = FALSE;
143 #endif /* OPIE_ENABLE */
147 * This needs to catch both demon.co.uk and demon.net.
148 * If we see either, and we're in multidrop mode, try to use
149 * the SDPS *ENV extension.
151 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
152 ctl->server.sdps = TRUE;
153 #endif /* SDPS_ENABLE */
155 switch (ctl->server.protocol) {
158 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
159 if (strstr(ctl->remotename, "@compuserve.com"))
161 /* AUTH command should return a list of available mechanisms */
162 if (gen_transact(sock, "AUTH") == 0)
165 flag has_rpa = FALSE;
167 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
171 if (strncasecmp(buffer, "rpa", 3) == 0)
174 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
175 ctl->password, sock))
181 #endif /* RPA_ENABLE */
184 * CAPA command may return a list including available
185 * authentication mechanisms. if it doesn't, no harm done, we
186 * just fall back to a plain login. Note that this code
187 * latches the server's authentication type, so that in daemon mode
188 * the CAPA check only needs to be done once at start of run.
190 * APOP was introduced in RFC 1450, and CAPA not until
191 * RFC2449. So the < check is an easy way to prevent CAPA from
192 * being sent to the more primitive POP3 servers dating from
193 * RFC 1081 and RFC 1225, which seem more likely to choke on
194 * it. This certainly catches IMAP-2000's POP3 gateway.
196 * These authentication methods are blessed by RFC1734,
197 * describing the POP3 AUTHentication command.
199 if (ctl->server.authenticate == A_ANY
200 && strchr(greeting, '<')
201 && gen_transact(sock, "CAPA") == 0)
205 /* determine what authentication methods we have available */
206 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
211 if (strstr(buffer, "GSSAPI"))
213 #endif /* defined(GSSAPI) */
214 #if defined(KERBEROS_V4)
215 if (strstr(buffer, "KERBEROS_V4"))
217 #endif /* defined(KERBEROS_V4) */
219 if (strstr(buffer, "X-OTP"))
221 #endif /* OPIE_ENABLE */
222 if (strstr(buffer, "CRAM-MD5"))
228 * OK, we have an authentication type now.
230 #if defined(KERBEROS_V4)
232 * Servers doing KPOP have to go through a dummy login sequence
233 * rather than doing SASL.
237 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
238 #else /* INET6_ENABLE */
239 ctl->server.port != KPOP_PORT
240 #endif /* INET6_ENABLE */
241 && (ctl->server.authenticate == A_KERBEROS_V4
242 || ctl->server.authenticate == A_KERBEROS_V5
243 || ctl->server.authenticate == A_ANY))
245 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
246 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
249 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
253 (ctl->server.authenticate == A_GSSAPI ||
254 ctl->server.authenticate == A_ANY))
256 ok = do_gssauth(sock,"AUTH",ctl->server.truename,ctl->remotename);
257 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
260 #endif /* defined(GSSAPI) */
264 (ctl->server.authenticate == A_OTP ||
265 ctl->server.authenticate == A_ANY))
267 ok = do_otp(sock, "AUTH", ctl);
268 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
271 #endif /* OPIE_ENABLE */
274 (ctl->server.authenticate == A_CRAM_MD5 ||
275 ctl->server.authenticate == A_ANY))
277 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
278 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
282 /* ordinary validation, no one-time password or RPA */
283 gen_transact(sock, "USER %s", ctl->remotename);
284 strcpy(shroud, ctl->password);
285 ok = gen_transact(sock, "PASS %s", ctl->password);
290 /* build MD5 digest from greeting timestamp + password */
291 /* find start of timestamp */
292 for (start = greeting; *start != 0 && *start != '<'; start++)
296 _("Required APOP timestamp not found in greeting\n"));
300 /* find end of timestamp */
301 for (end = start; *end != 0 && *end != '>'; end++)
303 if (*end == 0 || end == start + 1) {
305 _("Timestamp syntax error in greeting\n"));
311 /* copy timestamp and password into digestion buffer */
312 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
314 strcat(msg,ctl->password);
316 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
318 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
322 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
323 ok = gen_transact(sock, "RPOP %s", ctl->password);
327 report(stderr, _("Undefined protocol request in POP3_auth\n"));
333 /* maybe we detected a lock-busy condition? */
334 if (ok == PS_LOCKBUSY)
335 report(stderr, _("lock busy! Is another session active?\n"));
341 * Empirical experience shows some server/OS combinations
342 * may need a brief pause even after any lockfiles on the
343 * server are released, to give the server time to finish
344 * copying back very large mailfolders from the temp-file...
345 * this is only ever an issue with extremely large mailboxes.
347 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
349 /* we're peek-capable if use of TOP is enabled */
350 peek_capable = !(ctl->fetchall || ctl->keep);
356 static int pop3_gettopid( int sock, int num , char *id)
360 char buf [POPBUFSIZE+1];
361 sprintf( buf, "TOP %d 1", num );
362 if ((ok = gen_transact(sock, buf )) != 0)
365 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
369 if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
371 /* prevent stack overflows */
373 sscanf( buf+12, "%s", id);
379 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
381 /* This approach tries to get the message headers from the
382 * remote hosts and compares the message-id to the already known
384 * + if the first message containes a new id, all messages on
385 * the server will be new
386 * + if the first is known, try to estimate the last known message
387 * on the server and check. If this works you know the total number
388 * of messages to get.
389 * + Otherwise run a binary search to determine the last known message
391 int ok, nolinear = 0;
392 int first_nr, list_len, try_id, try_nr, add_id;
396 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
399 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
400 /* the first message is unknown -> all messages are new */
405 /* check where we expect the latest known message */
406 list_len = count_list( &ctl->oldsaved );
407 try_id = list_len - first_nr; /* -1 + 1 */
409 if( try_id <= *countp ) {
410 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
413 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
418 if( try_nr != list_len -1 ) {
419 /* some messages inbetween have been deleted... */
423 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
425 for( ; add_id; add_id >>= 1 ) {
427 if( try_id - add_id <= 1 ) {
434 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
436 try_nr = str_nr_in_list(&ctl->oldsaved, id);
443 _("Messages inserted into list on server. Cannot handle this.\n"));
448 /* the first try_id messages are known -> copy them to the newsaved list */
449 for( num = first_nr; num < list_len; num++ )
451 struct idlist *new = save_str(&ctl->newsaved,
452 str_from_nr_list(&ctl->oldsaved, num),
454 new->val.status.num = num - first_nr + 1;
458 free_str_list(&ctl->oldsaved);
463 *newp = *countp - try_id;
467 static int pop3_getrange(int sock,
470 int *countp, int *newp, int *bytes)
471 /* get range of messages to be fetched */
474 char buf [POPBUFSIZE+1];
476 /* Ensure that the new list is properly empty */
477 ctl->newsaved = (struct idlist *)NULL;
480 /* Alain Knaff suggests this, but it's not RFC standard */
482 if ((ok = gen_transact(sock, "MBOX %s", folder)))
486 /* get the total message count */
487 gen_send(sock, "STAT");
488 ok = pop3_ok(sock, buf);
490 sscanf(buf,"%d %d", countp, bytes);
495 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
496 * We work as hard as possible to hide this ugliness, but it makes
497 * counting new messages intrinsically quadratic in the worst case.
501 if (*countp > 0 && !ctl->fetchall)
505 if (!ctl->server.uidl) {
506 gen_send(sock, "LAST");
507 ok = pop3_ok(sock, buf);
512 if (sscanf(buf, "%d", &last) == 0)
514 report(stderr, _("protocol error\n"));
517 *newp = (*countp - last);
521 /* grab the mailbox's UID list */
522 if ((ok = gen_transact(sock, "UIDL")) != 0)
524 /* don't worry, yet! do it the slow way */
525 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
527 report(stderr, _("protocol error while fetching UIDLs\n"));
536 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
540 else if (sscanf(buf, "%d %s", &num, id) == 2)
544 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
545 new->val.status.num = num;
547 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
548 new->val.status.mark = UID_SEEN;
549 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
562 static int pop3_getsizes(int sock, int count, int *sizes)
563 /* capture the sizes of all messages */
567 if ((ok = gen_transact(sock, "LIST")) != 0)
571 char buf [POPBUFSIZE+1];
573 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
579 else if (sscanf(buf, "%d %d", &num, &size) == 2)
580 sizes[num - 1] = size;
587 static int pop3_is_old(int sock, struct query *ctl, int num)
588 /* is the given message old? */
591 return (num <= last);
593 return (str_in_list(&ctl->oldsaved,
594 str_find(&ctl->newsaved, num), FALSE));
599 * We could use this to fetch headers only as we do for IMAP. The trouble
600 * is that there's no way to fetch the body only. So the following RETR
601 * would have to re-fetch the header. Enough messages have longer headers
602 * than bodies to make this a net loss.
604 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
605 /* request headers of nth message */
608 char buf[POPBUFSIZE+1];
610 gen_send(sock, "TOP %d 0", number);
611 if ((ok = pop3_ok(sock, buf)) != 0)
614 *lenp = -1; /* we got sizes from the LIST response */
620 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
621 /* request nth message */
624 char buf[POPBUFSIZE+1];
628 * See http://www.demon.net/services/mail/sdps-tech.html
629 * for a description of what we're parsing here.
631 if (ctl->server.sdps)
635 sdps_envfrom = (char *)NULL;
636 sdps_envto = (char *)NULL;
637 gen_send(sock, "*ENV %d", number);
639 if (gen_recv(sock, buf, sizeof(buf)))
646 /* No need to wrap envelope from address */
647 sdps_envfrom = xmalloc(strlen(buf)+1);
648 strcpy(sdps_envfrom,buf);
651 /* Wrap address with To: <> so nxtaddr() likes it */
652 sdps_envto = xmalloc(strlen(buf)+7);
653 sprintf(sdps_envto,"To: <%s>",buf);
657 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
659 #endif /* SDPS_ENABLE */
662 * Though the POP RFCs don't document this fact, on almost every
663 * POP3 server I know of messages are marked "seen" only at the
664 * time the OK response to a RETR is issued.
666 * This means we can use TOP to fetch the message without setting its
667 * seen flag. This is good! It means that if the protocol exchange
668 * craps out during the message, it will still be marked `unseen' on
669 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
670 * reported to mark messages seen on a TOP fetch.)
672 * However...*don't* do this if we're using keep to suppress deletion!
673 * In that case, marking the seen flag is the only way to prevent the
674 * message from being re-fetched on subsequent runs.
676 * Also use RETR if fetchall is on. This gives us a workaround
677 * for servers like usa.net's that bungle TOP. It's pretty
678 * harmless because fetchall guarantees that any message dropped
679 * by an interrupted RETR will be picked up on the next poll of the
682 * We take advantage here of the fact that, according to all the
683 * POP RFCs, "if the number of lines requested by the POP3 client
684 * is greater than than the number of lines in the body, then the
685 * POP3 server sends the entire message.").
687 * The line count passed (99999999) is the maximum value CompuServe will
688 * accept; it's much lower than the natural value 2147483646 (the maximum
689 * twos-complement signed 32-bit integer minus 1) */
690 if (ctl->keep || ctl->fetchall)
691 gen_send(sock, "RETR %d", number);
693 gen_send(sock, "TOP %d 99999999", number);
694 if ((ok = pop3_ok(sock, buf)) != 0)
697 *lenp = -1; /* we got sizes from the LIST response */
702 static int pop3_delete(int sock, struct query *ctl, int number)
703 /* delete a given message */
705 /* actually, mark for deletion -- doesn't happen until QUIT time */
706 return(gen_transact(sock, "DELE %d", number));
709 static int pop3_logout(int sock, struct query *ctl)
710 /* send logout command */
715 * Just in case the server marks messages deleted when seen.
716 * Yes, this has been reported, in the MercuryP/NLM server.
717 * It's even legal under RFC 1939 (section 8) as a site policy.
720 gen_transact(sock, "RSET");
722 ok = gen_transact(sock, "QUIT");
735 const static struct method pop3 =
737 "POP3", /* Post Office Protocol v3 */
739 "pop3", /* standard POP3 port */
740 "pop3s", /* ssl POP3 port */
741 #else /* INET6_ENABLE */
742 110, /* standard POP3 port */
743 995, /* ssl POP3 port */
744 #endif /* INET6_ENABLE */
745 FALSE, /* this is not a tagged protocol */
746 TRUE, /* this uses a message delimiter */
747 pop3_ok, /* parse command response */
748 pop3_getauth, /* get authorization */
749 pop3_getrange, /* query range of messages */
750 pop3_getsizes, /* we can get a list of sizes */
751 pop3_is_old, /* how do we tell a message is old? */
752 pop3_fetch, /* request given message */
753 NULL, /* no way to fetch body alone */
754 NULL, /* no message trailer */
755 pop3_delete, /* how to delete a message */
756 pop3_logout, /* log out, we're done */
757 FALSE, /* no, we can't re-poll */
760 int doPOP3 (struct query *ctl)
761 /* retrieve messages using POP3 */
764 if (ctl->mailboxes->id) {
765 fprintf(stderr,_("Option --remote is not supported with POP3\n"));
769 peek_capable = !ctl->fetchall;
770 return(do_protocol(ctl, &pop3));
772 #endif /* POP3_ENABLE */
774 /* pop3.c ends here */