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 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)
54 if (*bufp == '+' || *bufp == '-')
59 while (isalpha(*bufp))
65 if (strcmp(buf,"+OK") == 0)
69 #endif /* OPIE_ENABLE */
72 else if (strncmp(buf,"-ERR", 4) == 0)
74 if (stage > STAGE_GETAUTH)
77 * We're checking for "lock busy", "unable to lock",
78 * "already locked", "wait a few minutes" etc. here.
79 * This indicates that we have to wait for the server to
80 * unwedge itself before we can poll again.
82 * PS_LOCKBUSY check empirically verified with two recent
83 * versions of the Berkeley popper; QPOP (version 2.2) and
84 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
85 * These are caught by the case-indifferent "lock" check.
86 * The "wait" catches "mail storage services unavailable,
87 * wait a few minutes and try again" on the InterMail server.
89 * If these aren't picked up on correctly, fetchmail will
90 * think there is an authentication failure and wedge the
91 * connection in order to prevent futile polls.
95 else if (strstr(bufp,"lock")
96 || strstr(bufp,"Lock")
97 || strstr(bufp,"LOCK")
98 || strstr(bufp,"wait")
99 /* these are blessed by RFC 2449 */
100 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
105 * We always want to pass the user lock-busy messages, because
106 * they're red flags. Other stuff (like AUTH failures on non-
107 * RFC1734 servers) only if we're debugging.
109 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
110 report(stderr, "%s\n", bufp);
122 int pop3_getauth(int sock, struct query *ctl, char *greeting)
123 /* apply for connection authorization */
130 #endif /* OPIE_ENABLE */
134 * This needs to catch both demon.co.uk and demon.net.
135 * If we see either, and we're in multidrop mode, try to use
136 * the SDPS *ENV extension.
138 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
139 ctl->server.sdps = TRUE;
140 #endif /* SDPS_ENABLE */
142 switch (ctl->server.protocol) {
145 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
146 if (strstr(ctl->remotename, "@compuserve.com"))
148 /* AUTH command should return a list of available mechanisms */
149 if (gen_transact(sock, "AUTH") == 0)
152 flag has_rpa = FALSE;
154 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
158 if (strncasecmp(buffer, "rpa", 3) == 0)
161 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
162 ctl->password, sock))
168 #endif /* RPA_ENABLE */
171 * CAPA command may return a list including available
172 * authentication mechanisms. if it doesn't, no harm done, we
173 * just fall back to a plain login. Note that this code
174 * latches the server's authentication type, so that in daemon mode
175 * the CAPA check only needs to be done once at start of run.
177 * APOP was introduced in RFC 1450, and CAPA not until
178 * RFC2449. So the < check is an easy way to prevent CAPA from
179 * being sent to the more primitive POP3 servers dating from
180 * RFC 1081 and RFC 1225, which seem more likely to choke on
181 * it. This certainly catches IMAP-2000's POP3 gateway.
183 * These authentication methods are blessed by RFC1734,
184 * describing the POP3 AUTHentication command.
186 if (ctl->server.authenticate == A_ANY
187 && strchr(greeting, '<')
188 && gen_transact(sock, "CAPA") == 0)
191 flag has_gssapi = FALSE;
192 #endif /* defined(GSSAPI) */
193 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
194 flag has_kerberos = FALSE;
195 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
196 flag has_cram = FALSE;
198 flag has_otp = FALSE;
199 #endif /* OPIE_ENABLE */
202 /* determine what authentication methods we have available */
203 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
208 if (strstr(buffer, "GSSAPI"))
210 #endif /* defined(GSSAPI) */
211 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
212 if (strstr(buffer, "KERBEROS_V4"))
214 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
216 if (strstr(buffer, "X-OTP"))
218 #endif /* OPIE_ENABLE */
219 if (strstr(buffer, "CRAM-MD5"))
224 * Here's where we set priorities. Note that we must do tests
225 * in *reverse* order of desirability.
228 ctl->server.authenticate = A_CRAM_MD5;
231 ctl->server.authenticate = A_OTP;
232 #endif /* OPIE_ENABLE */
235 ctl->server.authenticate = A_GSSAPI;
236 #endif /* defined(GSSAPI) */
237 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
239 ctl->server.authenticate = A_KERBEROS_V4;
240 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
244 * OK, we have an authentication type now.
246 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
248 * Servers doing KPOP have to go through a dummy login sequence
249 * rather than doing SASL.
253 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
254 #else /* INET6_ENABLE */
255 ctl->server.port != KPOP_PORT
256 #endif /* INET6_ENABLE */
257 && (ctl->server.authenticate == A_KERBEROS_V4
258 || ctl->server.authenticate == A_KERBEROS_V5))
259 return(do_rfc1731(sock, "AUTH", ctl->server.truename));
260 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
262 if (ctl->server.authenticate==A_GSSAPI))
263 return(do_gssauth(sock, "AUTH",
264 ctl->server.truename, ctl->remotename));
265 #endif /* defined(GSSAPI) */
267 if (ctl->server.authenticate == A_OTP)
268 do_otp(sock, "AUTH", ctl);
269 #endif /* OPIE_ENABLE */
270 if (ctl->server.authenticate == A_CRAM_MD5)
271 return(do_cram_md5(sock, "AUTH", ctl));
273 /* ordinary validation, no one-time password or RPA */
274 gen_transact(sock, "USER %s", ctl->remotename);
275 ok = gen_transact(sock, "PASS %s", ctl->password);
279 /* build MD5 digest from greeting timestamp + password */
280 /* find start of timestamp */
281 for (start = greeting; *start != 0 && *start != '<'; start++)
285 _("Required APOP timestamp not found in greeting\n"));
289 /* find end of timestamp */
290 for (end = start; *end != 0 && *end != '>'; end++)
292 if (*end == 0 || end == start + 1) {
294 _("Timestamp syntax error in greeting\n"));
300 /* copy timestamp and password into digestion buffer */
301 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
303 strcat(msg,ctl->password);
305 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
307 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
311 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
312 ok = gen_transact(sock, "RPOP %s", ctl->password);
316 report(stderr, _("Undefined protocol request in POP3_auth\n"));
322 /* maybe we detected a lock-busy condition? */
323 if (ok == PS_LOCKBUSY)
324 report(stderr, _("lock busy! Is another session active?\n"));
330 * Empirical experience shows some server/OS combinations
331 * may need a brief pause even after any lockfiles on the
332 * server are released, to give the server time to finish
333 * copying back very large mailfolders from the temp-file...
334 * this is only ever an issue with extremely large mailboxes.
336 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
338 /* we're peek-capable if use of TOP is enabled */
339 peek_capable = !(ctl->fetchall || ctl->keep);
346 pop3_gettopid( int sock, int num , char *id)
350 char buf [POPBUFSIZE+1];
351 sprintf( buf, "TOP %d 1", num );
352 if ((ok = gen_transact(sock, buf )) != 0)
355 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
359 if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
361 /* prevent stack overflows */
363 sscanf( buf+12, "%s", id);
370 pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
372 /* This approach tries to get the message headers from the
373 * remote hosts and compares the message-id to the already known
375 * + if the first message containes a new id, all messages on
376 * the server will be new
377 * + if the first is known, try to estimate the last known message
378 * on the server and check. If this works you know the total number
379 * of messages to get.
380 * + Otherwise run a binary search to determine the last known message
382 int ok, nolinear = 0;
383 int first_nr, list_len, try_id, try_nr, add_id;
387 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
390 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
391 /* the first message is unknown -> all messages are new */
396 /* check where we expect the latest known message */
397 list_len = count_list( &ctl->oldsaved );
398 try_id = list_len - first_nr; /* -1 + 1 */
400 if( try_id <= *countp ) {
401 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
404 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
409 if( try_nr != list_len -1 ) {
410 /* some messages inbetween have been deleted... */
414 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
416 for( ; add_id; add_id >>= 1 ) {
418 if( try_id - add_id <= 1 ) {
425 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
427 try_nr = str_nr_in_list(&ctl->oldsaved, id);
434 _("Messages inserted into list on server. Cannot handle this.\n"));
439 /* the first try_id messages are known -> copy them to the newsaved list */
440 for( num = first_nr; num < list_len; num++ )
442 struct idlist *new = save_str(&ctl->newsaved,
443 str_from_nr_list(&ctl->oldsaved, num),
445 new->val.status.num = num - first_nr + 1;
449 free_str_list(&ctl->oldsaved);
454 *newp = *countp - try_id;
458 static int pop3_getrange(int sock,
461 int *countp, int *newp, int *bytes)
462 /* get range of messages to be fetched */
465 char buf [POPBUFSIZE+1];
467 /* Ensure that the new list is properly empty */
468 ctl->newsaved = (struct idlist *)NULL;
471 /* Alain Knaff suggests this, but it's not RFC standard */
473 if ((ok = gen_transact(sock, "MBOX %s", folder)))
477 /* get the total message count */
478 gen_send(sock, "STAT");
479 ok = pop3_ok(sock, buf);
481 sscanf(buf,"%d %d", countp, bytes);
486 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
487 * We work as hard as possible to hide this ugliness, but it makes
488 * counting new messages intrinsically quadratic in the worst case.
492 if (*countp > 0 && !ctl->fetchall)
496 if (!ctl->server.uidl) {
497 gen_send(sock, "LAST");
498 ok = pop3_ok(sock, buf);
503 if (sscanf(buf, "%d", &last) == 0)
505 report(stderr, _("protocol error\n"));
508 *newp = (*countp - last);
512 /* grab the mailbox's UID list */
513 if ((ok = gen_transact(sock, "UIDL")) != 0)
515 /* don't worry, yet! do it the slow way */
516 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
518 report(stderr, _("protocol error while fetching UIDLs\n"));
527 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
531 else if (sscanf(buf, "%d %s", &num, id) == 2)
535 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
536 new->val.status.num = num;
538 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
539 new->val.status.mark = UID_SEEN;
540 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
553 static int pop3_getsizes(int sock, int count, int *sizes)
554 /* capture the sizes of all messages */
558 if ((ok = gen_transact(sock, "LIST")) != 0)
562 char buf [POPBUFSIZE+1];
564 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
570 else if (sscanf(buf, "%d %d", &num, &size) == 2)
571 sizes[num - 1] = size;
578 static int pop3_is_old(int sock, struct query *ctl, int num)
579 /* is the given message old? */
582 return (num <= last);
584 return (str_in_list(&ctl->oldsaved,
585 str_find(&ctl->newsaved, num), FALSE));
590 * We could use this to fetch headers only as we do for IMAP. The trouble
591 * is that there's no way to fetch the body only. So the following RETR
592 * would have to re-fetch the header. Enough messages have longer headers
593 * than bodies to make this a net loss.
595 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
596 /* request headers of nth message */
599 char buf[POPBUFSIZE+1];
601 gen_send(sock, "TOP %d 0", number);
602 if ((ok = pop3_ok(sock, buf)) != 0)
605 *lenp = -1; /* we got sizes from the LIST response */
611 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
612 /* request nth message */
615 char buf[POPBUFSIZE+1];
619 * See http://www.demon.net/services/mail/sdps-tech.html
620 * for a description of what we're parsing here.
622 if (ctl->server.sdps)
626 sdps_envfrom = (char *)NULL;
627 sdps_envto = (char *)NULL;
628 gen_send(sock, "*ENV %d", number);
630 if (gen_recv(sock, buf, sizeof(buf)))
637 /* No need to wrap envelope from address */
638 sdps_envfrom = xmalloc(strlen(buf)+1);
639 strcpy(sdps_envfrom,buf);
642 /* Wrap address with To: <> so nxtaddr() likes it */
643 sdps_envto = xmalloc(strlen(buf)+7);
644 sprintf(sdps_envto,"To: <%s>",buf);
648 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
650 #endif /* SDPS_ENABLE */
653 * Though the POP RFCs don't document this fact, on almost every
654 * POP3 server I know of messages are marked "seen" only at the
655 * time the OK response to a RETR is issued.
657 * This means we can use TOP to fetch the message without setting its
658 * seen flag. This is good! It means that if the protocol exchange
659 * craps out during the message, it will still be marked `unseen' on
660 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
661 * reported to mark messages seen on a TOP fetch.)
663 * However...*don't* do this if we're using keep to suppress deletion!
664 * In that case, marking the seen flag is the only way to prevent the
665 * message from being re-fetched on subsequent runs.
667 * Also use RETR if fetchall is on. This gives us a workaround
668 * for servers like usa.net's that bungle TOP. It's pretty
669 * harmless because fetchall guarantees that any message dropped
670 * by an interrupted RETR will be picked up on the next poll of the
673 * We take advantage here of the fact that, according to all the
674 * POP RFCs, "if the number of lines requested by the POP3 client
675 * is greater than than the number of lines in the body, then the
676 * POP3 server sends the entire message.").
678 * The line count passed (99999999) is the maximum value CompuServe will
679 * accept; it's much lower than the natural value 2147483646 (the maximum
680 * twos-complement signed 32-bit integer minus 1) */
681 if (ctl->keep || ctl->fetchall)
682 gen_send(sock, "RETR %d", number);
684 gen_send(sock, "TOP %d 99999999", number);
685 if ((ok = pop3_ok(sock, buf)) != 0)
688 *lenp = -1; /* we got sizes from the LIST response */
693 static int pop3_delete(int sock, struct query *ctl, int number)
694 /* delete a given message */
696 /* actually, mark for deletion -- doesn't happen until QUIT time */
697 return(gen_transact(sock, "DELE %d", number));
700 static int pop3_logout(int sock, struct query *ctl)
701 /* send logout command */
705 ok = gen_transact(sock, "QUIT");
718 const static struct method pop3 =
720 "POP3", /* Post Office Protocol v3 */
722 "pop3", /* standard POP3 port */
723 "pop3s", /* ssl POP3 port */
724 #else /* INET6_ENABLE */
725 110, /* standard POP3 port */
726 995, /* ssl POP3 port */
727 #endif /* INET6_ENABLE */
728 FALSE, /* this is not a tagged protocol */
729 TRUE, /* this uses a message delimiter */
730 pop3_ok, /* parse command response */
731 NULL, /* no password canonicalization */
732 pop3_getauth, /* get authorization */
733 pop3_getrange, /* query range of messages */
734 pop3_getsizes, /* we can get a list of sizes */
735 pop3_is_old, /* how do we tell a message is old? */
736 pop3_fetch, /* request given message */
737 NULL, /* no way to fetch body alone */
738 NULL, /* no message trailer */
739 pop3_delete, /* how to delete a message */
740 pop3_logout, /* log out, we're done */
741 FALSE, /* no, we can't re-poll */
744 int doPOP3 (struct query *ctl)
745 /* retrieve messages using POP3 */
748 if (ctl->mailboxes->id) {
749 fprintf(stderr,_("Option --remote is not supported with POP3\n"));
753 peek_capable = !ctl->fetchall;
754 return(do_protocol(ctl, &pop3));
756 #endif /* POP3_ENABLE */
758 /* pop3.c ends here */