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 report(stderr, "%s\n", bufp);
117 int pop3_getauth(int sock, struct query *ctl, char *greeting)
118 /* apply for connection authorization */
125 #endif /* OPIE_ENABLE */
129 * This needs to catch both demon.co.uk and demon.net.
130 * If we see either, and we're in multidrop mode, try to use
131 * the SDPS *ENV extension.
133 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
134 ctl->server.sdps = TRUE;
135 #endif /* SDPS_ENABLE */
138 * In theory, we ought to probe with CAPA here (RFC 2449).
139 * But AFAIK this commpand is not widely implemented, and
140 * we have our own tests for optional commands, and it seems
141 * vanishingly unlikely that the RFC 2449 extended responses
142 * [IN-USE] and [LOGIN-DELAY] will ever be accidentally spoofed.
143 * So we'll not bother, and save ourselves the overhead.
146 switch (ctl->server.protocol) {
149 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
150 if (strstr(ctl->remotename, "@compuserve.com"))
152 /* AUTH command should return a list of available mechanisms */
153 if (gen_transact(sock, "AUTH") == 0)
156 flag has_rpa = FALSE;
158 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
162 if (strncasecmp(buffer, "rpa", 3) == 0)
165 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
166 ctl->password, sock))
172 else /* not a CompuServe account */
173 #endif /* RPA_ENABLE */
174 ok = gen_transact(sock, "USER %s", ctl->remotename);
177 /* see RFC1938: A One-Time Password System */
178 if (challenge = strstr(lastok, "otp-")) {
179 char response[OPIE_RESPONSE_MAX+1];
182 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
183 if ((i == -2) && !run.poll_interval) {
184 char secret[OPIE_SECRET_MAX+1];
185 fprintf(stderr, _("Secret pass phrase: "));
186 if (opiereadpass(secret, sizeof(secret), 0))
187 i = opiegenerator(challenge, secret, response);
188 memset(secret, 0, sizeof(secret));
196 ok = gen_transact(sock, "PASS %s", response);
199 #endif /* OPIE_ENABLE */
202 * AUTH command may return a list of available mechanisms.
203 * if it doesn't, no harm done. Efficiency hack: most servers
204 * don't implement this, so don't do it at all unless the
205 * server advertises APOP with <> in the greeting line. This
206 * certainly catches IMAP-2000's POP3 gateway.
208 * These authentication methods are blessed by RFC1734,
209 * POP3 AUTHentication command.
211 if (strchr(greeting, '<') && gen_transact(sock, "AUTH") == 0)
214 flag has_cram = FALSE;
215 #if defined(KERBEROS_IV)
216 flag has_kerberos = FALSE;
217 #endif /* defined(KERBEROS_IV) */
219 flag has_opie = FALSE;
220 #endif /* OPIE_ENABLE */
222 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
226 if (strncasecmp(buffer, "CRAM-MD5", 8) == 0)
228 #if defined(KERBEROS_IV)
229 if (strncasecmp(buffer, "KERBEROS_V4", 8) == 0)
231 #endif /* defined(KERBEROS_IV) */
233 if (strncasecmp(buffer, "X-OTP", 8) == 0)
235 #endif /* OPIE_ENABLE */
237 #if defined(KERBEROS_IV)
239 return(do_rfc1731(sock, "AUTH", ctl->server.truename));
240 #endif /* defined(KERBEROS_IV) */
244 #endif /* OPIE_ENABLE */
246 return(do_cram_md5(sock, "AUTH", ctl));
249 /* ordinary validation, no one-time password or RPA */
250 ok = gen_transact(sock, "PASS %s", ctl->password);
254 /* build MD5 digest from greeting timestamp + password */
255 /* find start of timestamp */
256 for (start = greeting; *start != 0 && *start != '<'; start++)
260 _("Required APOP timestamp not found in greeting\n"));
264 /* find end of timestamp */
265 for (end = start; *end != 0 && *end != '>'; end++)
267 if (*end == 0 || end == start + 1) {
269 _("Timestamp syntax error in greeting\n"));
275 /* copy timestamp and password into digestion buffer */
276 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
278 strcat(msg,ctl->password);
280 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
282 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
286 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
287 ok = gen_transact(sock, "RPOP %s", ctl->password);
291 report(stderr, _("Undefined protocol request in POP3_auth\n"));
297 /* maybe we detected a lock-busy condition? */
298 if (ok == PS_LOCKBUSY)
299 report(stderr, _("lock busy! Is another session active?\n"));
305 * Empirical experience shows some server/OS combinations
306 * may need a brief pause even after any lockfiles on the
307 * server are released, to give the server time to finish
308 * copying back very large mailfolders from the temp-file...
309 * this is only ever an issue with extremely large mailboxes.
311 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
313 /* we're peek-capable if use of TOP is enabled */
314 peek_capable = !(ctl->fetchall || ctl->keep);
321 pop3_gettopid( int sock, int num , char *id)
325 char buf [POPBUFSIZE+1];
326 sprintf( buf, "TOP %d 1", num );
327 if ((ok = gen_transact(sock, buf )) != 0)
330 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
334 if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
336 /* prevent stack overflows */
338 sscanf( buf+12, "%s", id);
345 pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
347 /* This approach tries to get the message headers from the
348 * remote hosts and compares the message-id to the already known
350 * + if the first message containes a new id, all messages on
351 * the server will be new
352 * + if the first is known, try to estimate the last known message
353 * on the server and check. If this works you know the total number
354 * of messages to get.
355 * + Otherwise run a binary search to determine the last known message
357 int ok, nolinear = 0;
358 int first_nr, list_len, try_id, try_nr, add_id;
362 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
365 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
366 /* the first message is unknown -> all messages are new */
371 /* check where we expect the latest known message */
372 list_len = count_list( &ctl->oldsaved );
373 try_id = list_len - first_nr; /* -1 + 1 */
375 if( try_id <= *countp ) {
376 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
379 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
384 if( try_nr != list_len -1 ) {
385 /* some messages inbetween have been deleted... */
389 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
391 for( ; add_id; add_id >>= 1 ) {
393 if( try_id - add_id <= 1 ) {
400 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
402 try_nr = str_nr_in_list(&ctl->oldsaved, id);
409 _("Messages inserted into list on server. Cannot handle this.\n"));
414 /* the first try_id messages are known -> copy them to the newsaved list */
415 for( num = first_nr; num < list_len; num++ )
417 struct idlist *new = save_str(&ctl->newsaved,
418 str_from_nr_list(&ctl->oldsaved, num),
420 new->val.status.num = num - first_nr + 1;
424 free_str_list(&ctl->oldsaved);
429 *newp = *countp - try_id;
433 static int pop3_getrange(int sock,
436 int *countp, int *newp, int *bytes)
437 /* get range of messages to be fetched */
440 char buf [POPBUFSIZE+1];
442 /* Ensure that the new list is properly empty */
443 ctl->newsaved = (struct idlist *)NULL;
446 /* Alain Knaff suggests this, but it's not RFC standard */
448 if ((ok = gen_transact(sock, "MBOX %s", folder)))
452 /* get the total message count */
453 gen_send(sock, "STAT");
454 ok = pop3_ok(sock, buf);
456 sscanf(buf,"%d %d", countp, bytes);
461 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
462 * We work as hard as possible to hide this ugliness, but it makes
463 * counting new messages intrinsically quadratic in the worst case.
467 if (*countp > 0 && !ctl->fetchall)
471 if (!ctl->server.uidl) {
472 gen_send(sock, "LAST");
473 ok = pop3_ok(sock, buf);
478 if (sscanf(buf, "%d", &last) == 0)
480 report(stderr, _("protocol error\n"));
483 *newp = (*countp - last);
487 /* grab the mailbox's UID list */
488 if ((ok = gen_transact(sock, "UIDL")) != 0)
490 /* don't worry, yet! do it the slow way */
491 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
493 report(stderr, _("protocol error while fetching UIDLs\n"));
502 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
506 else if (sscanf(buf, "%d %s", &num, id) == 2)
510 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
511 new->val.status.num = num;
513 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
514 new->val.status.mark = UID_SEEN;
515 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
528 static int pop3_getsizes(int sock, int count, int *sizes)
529 /* capture the sizes of all messages */
533 if ((ok = gen_transact(sock, "LIST")) != 0)
537 char buf [POPBUFSIZE+1];
539 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
545 else if (sscanf(buf, "%d %d", &num, &size) == 2)
546 sizes[num - 1] = size;
553 static int pop3_is_old(int sock, struct query *ctl, int num)
554 /* is the given message old? */
557 return (num <= last);
559 return (str_in_list(&ctl->oldsaved,
560 str_find(&ctl->newsaved, num), FALSE));
565 * We could use this to fetch headers only as we do for IMAP. The trouble
566 * is that there's no way to fetch the body only. So the following RETR
567 * would have to re-fetch the header. Enough messages have longer headers
568 * than bodies to make this a net loss.
570 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
571 /* request headers of nth message */
574 char buf[POPBUFSIZE+1];
576 gen_send(sock, "TOP %d 0", number);
577 if ((ok = pop3_ok(sock, buf)) != 0)
580 *lenp = -1; /* we got sizes from the LIST response */
586 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
587 /* request nth message */
590 char buf[POPBUFSIZE+1];
594 * See http://www.demon.net/services/mail/sdps-tech.html
595 * for a description of what we're parsing here.
597 if (ctl->server.sdps)
601 sdps_envfrom = (char *)NULL;
602 sdps_envto = (char *)NULL;
603 gen_send(sock, "*ENV %d", number);
605 if (gen_recv(sock, buf, sizeof(buf)))
612 /* No need to wrap envelope from address */
613 sdps_envfrom = xmalloc(strlen(buf)+1);
614 strcpy(sdps_envfrom,buf);
617 /* Wrap address with To: <> so nxtaddr() likes it */
618 sdps_envto = xmalloc(strlen(buf)+7);
619 sprintf(sdps_envto,"To: <%s>",buf);
623 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
625 #endif /* SDPS_ENABLE */
628 * Though the POP RFCs don't document this fact, on almost every
629 * POP3 server I know of messages are marked "seen" only at the
630 * time the OK response to a RETR is issued.
632 * This means we can use TOP to fetch the message without setting its
633 * seen flag. This is good! It means that if the protocol exchange
634 * craps out during the message, it will still be marked `unseen' on
635 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
636 * reported to mark messages seen on a TOP fetch.)
638 * However...*don't* do this if we're using keep to suppress deletion!
639 * In that case, marking the seen flag is the only way to prevent the
640 * message from being re-fetched on subsequent runs.
642 * Also use RETR if fetchall is on. This gives us a workaround
643 * for servers like usa.net's that bungle TOP. It's pretty
644 * harmless because fetchall guarantees that any message dropped
645 * by an interrupted RETR will be picked up on the next poll of the
648 * We take advantage here of the fact that, according to all the
649 * POP RFCs, "if the number of lines requested by the POP3 client
650 * is greater than than the number of lines in the body, then the
651 * POP3 server sends the entire message.").
653 * The line count passed (99999999) is the maximum value CompuServe will
654 * accept; it's much lower than the natural value 2147483646 (the maximum
655 * twos-complement signed 32-bit integer minus 1) */
656 if (ctl->keep || ctl->fetchall)
657 gen_send(sock, "RETR %d", number);
659 gen_send(sock, "TOP %d 99999999", number);
660 if ((ok = pop3_ok(sock, buf)) != 0)
663 *lenp = -1; /* we got sizes from the LIST response */
668 static int pop3_delete(int sock, struct query *ctl, int number)
669 /* delete a given message */
671 /* actually, mark for deletion -- doesn't happen until QUIT time */
672 return(gen_transact(sock, "DELE %d", number));
675 static int pop3_logout(int sock, struct query *ctl)
676 /* send logout command */
680 ok = gen_transact(sock, "QUIT");
693 const static struct method pop3 =
695 "POP3", /* Post Office Protocol v3 */
697 "pop3", /* standard POP3 port */
698 "pop3s", /* ssl POP3 port */
699 #else /* INET6_ENABLE */
700 110, /* standard POP3 port */
701 995, /* ssl POP3 port */
702 #endif /* INET6_ENABLE */
703 FALSE, /* this is not a tagged protocol */
704 TRUE, /* this uses a message delimiter */
705 pop3_ok, /* parse command response */
706 NULL, /* no password canonicalization */
707 pop3_getauth, /* get authorization */
708 pop3_getrange, /* query range of messages */
709 pop3_getsizes, /* we can get a list of sizes */
710 pop3_is_old, /* how do we tell a message is old? */
711 pop3_fetch, /* request given message */
712 NULL, /* no way to fetch body alone */
713 NULL, /* no message trailer */
714 pop3_delete, /* how to delete a message */
715 pop3_logout, /* log out, we're done */
716 FALSE, /* no, we can't re-poll */
719 int doPOP3 (struct query *ctl)
720 /* retrieve messages using POP3 */
723 if (ctl->mailboxes->id) {
724 fprintf(stderr,_("Option --remote is not supported with POP3\n"));
728 peek_capable = !ctl->fetchall;
729 return(do_protocol(ctl, &pop3));
731 #endif /* POP3_ENABLE */
733 /* pop3.c ends here */