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 int pop3_ok (int sock, char *argbuf)
43 /* parse command response */
46 char buf [POPBUFSIZE+1];
49 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
52 if (*bufp == '+' || *bufp == '-')
57 while (isalpha(*bufp))
63 if (strcmp(buf,"+OK") == 0)
67 #endif /* OPIE_ENABLE */
70 else if (strncmp(buf,"-ERR", 4) == 0)
72 if (stage > STAGE_GETAUTH)
75 * We're checking for "lock busy", "unable to lock",
76 * "already locked", "wait a few minutes" etc. here.
77 * This indicates that we have to wait for the server to
78 * unwedge itself before we can poll again.
80 * PS_LOCKBUSY check empirically verified with two recent
81 * versions of the Berkeley popper; QPOP (version 2.2) and
82 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
83 * These are caught by the case-indifferent "lock" check.
84 * The "wait" catches "mail storage services unavailable,
85 * wait a few minutes and try again" on the InterMail server.
87 * If these aren't picked up on correctly, fetchmail will
88 * think there is an authentication failure and wedge the
89 * connection in order to prevent futile polls.
93 else if (strstr(bufp,"lock")
94 || strstr(bufp,"Lock")
95 || strstr(bufp,"LOCK")
96 || strstr(bufp,"wait")
97 /* these are blessed by RFC 2449 */
98 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
103 report(stderr, "%s\n", bufp);
115 int pop3_getauth(int sock, struct query *ctl, char *greeting)
116 /* apply for connection authorization */
123 #endif /* OPIE_ENABLE */
127 * This needs to catch both demon.co.uk and demon.net.
128 * If we see either, and we're in multidrop mode, try to use
129 * the SDPS *ENV extension.
131 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
132 ctl->server.sdps = TRUE;
133 #endif /* SDPS_ENABLE */
136 * In theory, we ought to probe with CAPA here (RFC 2449).
137 * But AFAIK this commpand is not widely implemented, and
138 * we have our own tests for optional commands, and it seems
139 * vanishingly unlikely that the RFC 2449 extended responses
140 * [IN-USE] and [LOGIN-DELAY] will ever be accidentally spoofed.
141 * So we'll not bother, and save ourselves the overhead.
144 switch (ctl->server.protocol) {
147 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
148 if (strstr(ctl->remotename, "@compuserve.com"))
150 /* AUTH command should return a list of available mechanisms */
151 if (gen_transact(sock, "AUTH") == 0)
154 flag has_rpa = FALSE;
156 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
158 if (buffer[0] == '.')
160 if (strncasecmp(buffer, "rpa", 3) == 0)
163 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
164 ctl->password, sock))
170 else /* not a CompuServe account */
171 #endif /* RPA_ENABLE */
172 ok = gen_transact(sock, "USER %s", ctl->remotename);
175 /* see RFC1938: A One-Time Password System */
176 if (challenge = strstr(lastok, "otp-")) {
177 char response[OPIE_RESPONSE_MAX+1];
180 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
181 if ((i == -2) && !run.poll_interval) {
182 char secret[OPIE_SECRET_MAX+1];
183 fprintf(stderr, _("Secret pass phrase: "));
184 if (opiereadpass(secret, sizeof(secret), 0))
185 i = opiegenerator(challenge, secret, response);
186 memset(secret, 0, sizeof(secret));
194 ok = gen_transact(sock, "PASS %s", response);
197 #endif /* OPIE_ENABLE */
199 /* ordinary validation, no one-time password or RPA */
200 ok = gen_transact(sock, "PASS %s", ctl->password);
204 /* build MD5 digest from greeting timestamp + password */
205 /* find start of timestamp */
206 for (start = greeting; *start != 0 && *start != '<'; start++)
210 _("Required APOP timestamp not found in greeting\n"));
214 /* find end of timestamp */
215 for (end = start; *end != 0 && *end != '>'; end++)
217 if (*end == 0 || end == start + 1) {
219 _("Timestamp syntax error in greeting\n"));
225 /* copy timestamp and password into digestion buffer */
226 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
228 strcat(msg,ctl->password);
230 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
232 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
236 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
237 ok = gen_transact(sock, "RPOP %s", ctl->password);
241 report(stderr, _("Undefined protocol request in POP3_auth\n"));
247 /* maybe we detected a lock-busy condition? */
248 if (ok == PS_LOCKBUSY)
249 report(stderr, _("lock busy! Is another session active?\n"));
255 * Empirical experience shows some server/OS combinations
256 * may need a brief pause even after any lockfiles on the
257 * server are released, to give the server time to finish
258 * copying back very large mailfolders from the temp-file...
259 * this is only ever an issue with extremely large mailboxes.
261 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
263 /* we're peek-capable if use of TOP is enabled */
264 peek_capable = !(ctl->fetchall || ctl->keep);
271 pop3_gettopid( int sock, int num , char *id)
275 char buf [POPBUFSIZE+1];
276 sprintf( buf, "TOP %d 1", num );
277 if( (ok = gen_transact(sock, buf ) ) != 0 )
280 while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
283 if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
285 /* prevent stack overflows */
287 sscanf( buf+12, "%s", id);
294 pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
296 /* This approach tries to get the message headers from the
297 * remote hosts and compares the message-id to the already known
299 * + if the first message containes a new id, all messages on
300 * the server will be new
301 * + if the first is known, try to estimate the last known message
302 * on the server and check. If this works you know the total number
303 * of messages to get.
304 * + Otherwise run a binary search to determine the last known message
306 int ok, nolinear = 0;
307 int first_nr, list_len, try_id, try_nr, add_id;
311 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
314 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
315 /* the first message is unknown -> all messages are new */
320 /* check where we expect the latest known message */
321 list_len = count_list( &ctl->oldsaved );
322 try_id = list_len - first_nr; /* -1 + 1 */
324 if( try_id <= *countp ) {
325 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
328 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
333 if( try_nr != list_len -1 ) {
334 /* some messages inbetween have been deleted... */
338 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
340 for( ; add_id; add_id >>= 1 ) {
342 if( try_id - add_id <= 1 ) {
349 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
351 try_nr = str_nr_in_list(&ctl->oldsaved, id);
358 _("Messages inserted into list on server. Cannot handle this.\n"));
363 /* the first try_id messages are known -> copy them to the newsaved list */
364 for( num = first_nr; num < list_len; num++ )
366 struct idlist *new = save_str(&ctl->newsaved,
367 str_from_nr_list(&ctl->oldsaved, num),
369 new->val.status.num = num - first_nr + 1;
373 free_str_list(&ctl->oldsaved);
378 *newp = *countp - try_id;
382 static int pop3_getrange(int sock,
385 int *countp, int *newp, int *bytes)
386 /* get range of messages to be fetched */
389 char buf [POPBUFSIZE+1];
391 /* Ensure that the new list is properly empty */
392 ctl->newsaved = (struct idlist *)NULL;
395 /* Alain Knaff suggests this, but it's not RFC standard */
397 if ((ok = gen_transact(sock, "MBOX %s", folder)))
401 /* get the total message count */
402 gen_send(sock, "STAT");
403 ok = pop3_ok(sock, buf);
405 sscanf(buf,"%d %d", countp, bytes);
410 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
411 * We work as hard as possible to hide this ugliness, but it makes
412 * counting new messages intrinsically quadratic in the worst case.
416 if (*countp > 0 && !ctl->fetchall)
420 if (!ctl->server.uidl) {
421 gen_send(sock, "LAST");
422 ok = pop3_ok(sock, buf);
427 if (sscanf(buf, "%d", &last) == 0)
429 report(stderr, _("protocol error\n"));
432 *newp = (*countp - last);
436 /* grab the mailbox's UID list */
437 if ((ok = gen_transact(sock, "UIDL")) != 0)
439 /* don't worry, yet! do it the slow way */
440 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
442 report(stderr, _("protocol error while fetching UIDLs\n"));
451 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
455 else if (sscanf(buf, "%d %s", &num, id) == 2)
459 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
460 new->val.status.num = num;
462 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
463 new->val.status.mark = UID_SEEN;
464 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
477 static int pop3_getsizes(int sock, int count, int *sizes)
478 /* capture the sizes of all messages */
482 if ((ok = gen_transact(sock, "LIST")) != 0)
486 char buf [POPBUFSIZE+1];
488 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
494 else if (sscanf(buf, "%d %d", &num, &size) == 2)
495 sizes[num - 1] = size;
502 static int pop3_is_old(int sock, struct query *ctl, int num)
503 /* is the given message old? */
506 return (num <= last);
508 return (str_in_list(&ctl->oldsaved,
509 str_find(&ctl->newsaved, num), FALSE));
514 * We could use this to fetch headers only as we do for IMAP. The trouble
515 * is that there's no way to fetch the body only. So the following RETR
516 * would have to re-fetch the header. Enough messages have longer headers
517 * than bodies to make this a net loss.
519 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
520 /* request headers of nth message */
523 char buf[POPBUFSIZE+1];
525 gen_send(sock, "TOP %d 0", number);
526 if ((ok = pop3_ok(sock, buf)) != 0)
529 *lenp = -1; /* we got sizes from the LIST response */
535 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
536 /* request nth message */
539 char buf[POPBUFSIZE+1];
543 * See http://www.demon.net/services/mail/sdps-tech.html
544 * for a description of what we're parsing here.
546 if (ctl->server.sdps)
550 sdps_envfrom = (char *)NULL;
551 sdps_envto = (char *)NULL;
552 gen_send(sock, "*ENV %d", number);
554 if (gen_recv(sock, buf, sizeof(buf)))
561 /* No need to wrap envelope from address */
562 sdps_envfrom = xmalloc(strlen(buf)+1);
563 strcpy(sdps_envfrom,buf);
566 /* Wrap address with To: <> so nxtaddr() likes it */
567 sdps_envto = xmalloc(strlen(buf)+7);
568 sprintf(sdps_envto,"To: <%s>",buf);
572 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
574 #endif /* SDPS_ENABLE */
577 * Though the POP RFCs don't document this fact, on almost every
578 * POP3 server I know of messages are marked "seen" only at the
579 * time the OK response to a RETR is issued.
581 * This means we can use TOP to fetch the message without setting its
582 * seen flag. This is good! It means that if the protocol exchange
583 * craps out during the message, it will still be marked `unseen' on
584 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
585 * reported to mark messages seen on a TOP fetch.)
587 * However...*don't* do this if we're using keep to suppress deletion!
588 * In that case, marking the seen flag is the only way to prevent the
589 * message from being re-fetched on subsequent runs.
591 * Also use RETR if fetchall is on. This gives us a workaround
592 * for servers like usa.net's that bungle TOP. It's pretty
593 * harmless because fetchall guarantees that any message dropped
594 * by an interrupted RETR will be picked up on the next poll of the
597 * We take advantage here of the fact that, according to all the
598 * POP RFCs, "if the number of lines requested by the POP3 client
599 * is greater than than the number of lines in the body, then the
600 * POP3 server sends the entire message.").
602 * The line count passed (99999999) is the maximum value CompuServe will
603 * accept; it's much lower than the natural value 2147483646 (the maximum
604 * twos-complement signed 32-bit integer minus 1) */
605 if (ctl->keep || ctl->fetchall)
606 gen_send(sock, "RETR %d", number);
608 gen_send(sock, "TOP %d 99999999", number);
609 if ((ok = pop3_ok(sock, buf)) != 0)
612 *lenp = -1; /* we got sizes from the LIST response */
617 static int pop3_delete(int sock, struct query *ctl, int number)
618 /* delete a given message */
620 /* actually, mark for deletion -- doesn't happen until QUIT time */
621 return(gen_transact(sock, "DELE %d", number));
624 static int pop3_logout(int sock, struct query *ctl)
625 /* send logout command */
629 ok = gen_transact(sock, "QUIT");
636 const static struct method pop3 =
638 "POP3", /* Post Office Protocol v3 */
640 "pop3", /* standard POP3 port */
641 "pop3s", /* ssl POP3 port */
642 #else /* INET6_ENABLE */
643 110, /* standard POP3 port */
644 995, /* ssl POP3 port */
645 #endif /* INET6_ENABLE */
646 FALSE, /* this is not a tagged protocol */
647 TRUE, /* this uses a message delimiter */
648 pop3_ok, /* parse command response */
649 NULL, /* no password canonicalization */
650 pop3_getauth, /* get authorization */
651 pop3_getrange, /* query range of messages */
652 pop3_getsizes, /* we can get a list of sizes */
653 pop3_is_old, /* how do we tell a message is old? */
654 pop3_fetch, /* request given message */
655 NULL, /* no way to fetch body alone */
656 NULL, /* no message trailer */
657 pop3_delete, /* how to delete a message */
658 pop3_logout, /* log out, we're done */
659 FALSE, /* no, we can't re-poll */
662 int doPOP3 (struct query *ctl)
663 /* retrieve messages using POP3 */
666 if (ctl->mailboxes->id) {
667 fprintf(stderr,_("Option --remote is not supported with POP3\n"));
671 peek_capable = !ctl->fetchall;
672 return(do_protocol(ctl, &pop3));
674 #endif /* POP3_ENABLE */
676 /* pop3.c ends here */