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"
28 #ifndef strstr /* glibc-2.1 declares this as a macro */
29 extern char *strstr(); /* needed on sysV68 R3V7.1. */
32 static int pop3_phase;
33 #define PHASE_GETAUTH 0
34 #define PHASE_GETRANGE 1
35 #define PHASE_GETSIZES 2
37 #define PHASE_LOGOUT 4
42 #endif /* SDPS_ENABLE */
45 static char lastok[POPBUFSIZE+1];
48 int pop3_ok (int sock, char *argbuf)
49 /* parse command response */
52 char buf [POPBUFSIZE+1];
55 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
58 if (*bufp == '+' || *bufp == '-')
63 while (isalpha(*bufp))
69 if (strcmp(buf,"+OK") == 0)
76 else if (strncmp(buf,"-ERR", 4) == 0)
78 if (pop3_phase > PHASE_GETAUTH)
81 * We're checking for "lock busy", "unable to lock",
82 * "already locked" etc. here. This indicates that we
83 * have to wait for the server to clean up before we
86 * PS_LOCKBUSY check empirically verified with two recent
87 * versions the Berkeley popper; QPOP (version 2.2) and
88 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
90 else if (strstr(bufp,"lock")||strstr(bufp,"Lock")||strstr(bufp,"LOCK"))
95 report(stderr, "%s\n", bufp);
107 int pop3_getauth(int sock, struct query *ctl, char *greeting)
108 /* apply for connection authorization */
117 pop3_phase = PHASE_GETAUTH;
121 * This needs to catch both demon.co.uk and demon.net.
122 * If we see either, and we're in multidrop mode, try to use
123 * the SDPS *ENV extension.
125 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
126 ctl->server.sdps = TRUE;
127 #endif /* SDPS_ENABLE */
129 switch (ctl->server.protocol) {
131 ok = gen_transact(sock, "USER %s", ctl->remotename);
135 * CompuServe has changed its RPA behavior. Used to be they didn't
136 * accept PASS, but I'm told this changed in mid-November 1997.
138 if (strstr(greeting, "csi.com")
139 && (start = strchr(ctl->remotename, '@'))
140 && !strcmp("@compuserve.com", start))
142 /* temporary fix to get back out of cleartext authentication */
143 gen_transact(sock, "PASS %s", "dummypass");
145 /* AUTH command should return a list of available mechanisms */
146 if (gen_transact(sock, "AUTH") == 0)
149 flag has_rpa = FALSE;
151 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
153 if (buffer[0] == '.')
155 if (strncasecmp(buffer, "rpa", 3) == 0)
158 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
159 ctl->password, sock))
165 #endif /* RPA_ENABLE */
168 /* see RFC1938: A One-Time Password System */
169 if (challenge = strstr(lastok, "otp-")) {
170 char response[OPIE_RESPONSE_MAX+1];
173 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
174 if ((i == -2) && !run.poll_interval) {
175 char secret[OPIE_SECRET_MAX+1];
176 fprintf(stderr, _("Secret pass phrase: "));
177 if (opiereadpass(secret, sizeof(secret), 0))
178 i = opiegenerator(challenge, secret, response);
179 memset(secret, 0, sizeof(secret));
187 ok = gen_transact(sock, "PASS %s", response);
192 /* ordinary validation, no one-time password or RPA */
193 ok = gen_transact(sock, "PASS %s", ctl->password);
197 /* build MD5 digest from greeting timestamp + password */
198 /* find start of timestamp */
199 for (start = greeting; *start != 0 && *start != '<'; start++)
203 _("Required APOP timestamp not found in greeting\n"));
207 /* find end of timestamp */
208 for (end = start; *end != 0 && *end != '>'; end++)
210 if (*end == 0 || end == start + 1) {
212 _("Timestamp syntax error in greeting\n"));
218 /* copy timestamp and password into digestion buffer */
219 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
221 strcat(msg,ctl->password);
223 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
225 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
229 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
230 ok = gen_transact(sock, "RPOP %s", ctl->password);
234 report(stderr, _("Undefined protocol request in POP3_auth\n"));
240 /* maybe we detected a lock-busy condition? */
241 if (ok == PS_LOCKBUSY)
242 report(stderr, _("lock busy! Is another session active?\n"));
248 * Empirical experience shows some server/OS combinations
249 * may need a brief pause even after any lockfiles on the
250 * server are released, to give the server time to finish
251 * copying back very large mailfolders from the temp-file...
252 * this is only ever an issue with extremely large mailboxes.
254 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
256 /* we're peek-capable if use of TOP is enabled */
257 peek_capable = !(ctl->fetchall || ctl->keep);
264 pop3_gettopid( int sock, int num , char *id)
268 char buf [POPBUFSIZE+1];
269 sprintf( buf, "TOP %d 1", num );
270 if( (ok = gen_transact(sock, buf ) ) != 0 )
273 while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
276 if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
278 /* prevent stack overflows */
280 sscanf( buf+12, "%s", id);
287 pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
289 /* This approach tries to get the message headers from the
290 * remote hosts and compares the message-id to the already known
292 * + if the first message containes a new id, all messages on
293 * the server will be new
294 * + if the first is known, try to estimate the last known message
295 * on the server and check. If this works you know the total number
296 * of messages to get.
297 * + Otherwise run a binary search to determine the last known message
299 int ok, nolinear = 0;
300 int first_nr, list_len, try_id, try_nr, add_id;
304 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
307 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
308 /* the first message is unknown -> all messages are new */
313 /* check where we expect the latest known message */
314 list_len = count_list( &ctl->oldsaved );
315 try_id = list_len - first_nr; /* -1 + 1 */
317 if( try_id <= *countp ) {
318 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
321 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
326 if( try_nr != list_len -1 ) {
327 /* some messages inbetween have been deleted... */
331 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
333 for( ; add_id; add_id >>= 1 ) {
335 if( try_id - add_id <= 1 ) {
342 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
344 try_nr = str_nr_in_list(&ctl->oldsaved, id);
351 _("Messages inserted into list on server. Cannot handle this.\n"));
356 /* the first try_id messages are known -> copy them to the newsaved list */
357 for( num = first_nr; num < list_len; num++ )
359 struct idlist *new = save_str(&ctl->newsaved,
360 str_from_nr_list(&ctl->oldsaved, num),
362 new->val.status.num = num - first_nr + 1;
366 free_str_list(&ctl->oldsaved);
371 *newp = *countp - try_id;
375 static int pop3_getrange(int sock,
378 int *countp, int *newp, int *bytes)
379 /* get range of messages to be fetched */
382 char buf [POPBUFSIZE+1];
384 pop3_phase = PHASE_GETRANGE;
386 /* Ensure that the new list is properly empty */
387 ctl->newsaved = (struct idlist *)NULL;
390 /* Alain Knaff suggests this, but it's not RFC standard */
392 if ((ok = gen_transact(sock, "MBOX %s", folder)))
396 /* get the total message count */
397 gen_send(sock, "STAT");
398 ok = pop3_ok(sock, buf);
400 sscanf(buf,"%d %d", countp, bytes);
405 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
406 * We work as hard as possible to hide this ugliness, but it makes
407 * counting new messages intrinsically quadratic in the worst case.
411 if (*countp > 0 && !ctl->fetchall)
415 if (!ctl->server.uidl) {
416 gen_send(sock, "LAST");
417 ok = pop3_ok(sock, buf);
422 if (sscanf(buf, "%d", &last) == 0)
424 report(stderr, _("protocol error\n"));
427 *newp = (*countp - last);
431 /* grab the mailbox's UID list */
432 if ((ok = gen_transact(sock, "UIDL")) != 0)
434 /* don't worry, yet! do it the slow way */
435 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
437 report(stderr, _("protocol error while fetching UIDLs\n"));
446 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
450 else if (sscanf(buf, "%d %s", &num, id) == 2)
454 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
455 new->val.status.num = num;
457 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
458 new->val.status.mark = UID_SEEN;
459 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
472 static int pop3_getsizes(int sock, int count, int *sizes)
473 /* capture the sizes of all messages */
477 /* pop3_phase = PHASE_GETSIZES */
479 if ((ok = gen_transact(sock, "LIST")) != 0)
483 char buf [POPBUFSIZE+1];
485 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
491 else if (sscanf(buf, "%d %d", &num, &size) == 2)
492 sizes[num - 1] = size;
499 static int pop3_is_old(int sock, struct query *ctl, int num)
500 /* is the given message old? */
503 return (num <= last);
505 return (str_in_list(&ctl->oldsaved,
506 str_find(&ctl->newsaved, num), FALSE));
511 * We could use this to fetch headers only as we do for IMAP. The trouble
512 * is that there's no way to fetch the body only. So the following RETR
513 * would have to re-fetch the header. Enough messages have longer headers
514 * than bodies to make this a net loss.
516 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
517 /* request headers of nth message */
520 char buf[POPBUFSIZE+1];
522 /* pop3_phase = PHASE_FETCH */
524 gen_send(sock, "TOP %d 0", number);
525 if ((ok = pop3_ok(sock, buf)) != 0)
528 *lenp = -1; /* we got sizes from the LIST response */
534 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
535 /* request nth message */
538 char buf[POPBUFSIZE+1];
540 /* pop3_phase = PHASE_FETCH */
544 * See http://www.demon.net/services/mail/sdps-tech.html
545 * for a description of what we're parsing here.
547 if (ctl->server.sdps)
551 sdps_envfrom = (char *)NULL;
552 sdps_envto = (char *)NULL;
553 gen_send(sock, "*ENV %d", number);
555 if (gen_recv(sock, buf, sizeof(buf)))
562 /* No need to wrap envelope from address */
563 sdps_envfrom = xmalloc(strlen(buf)+1);
564 strcpy(sdps_envfrom,buf);
567 /* Wrap address with To: <> so nxtaddr() likes it */
568 sdps_envto = xmalloc(strlen(buf)+7);
569 sprintf(sdps_envto,"To: <%s>",buf);
573 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
575 #endif /* SDPS_ENABLE */
578 * Though the POP RFCs don't document this fact, on almost every
579 * POP3 server I know of messages are marked "seen" only at the
580 * time the OK response to a RETR is issued.
582 * This means we can use TOP to fetch the message without setting its
583 * seen flag. This is good! It means that if the protocol exchange
584 * craps out during the message, it will still be marked `unseen' on
585 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
586 * reported to mark messages seen on a TOP fetch.)
588 * However...*don't* do this if we're using keep to suppress deletion!
589 * In that case, marking the seen flag is the only way to prevent the
590 * message from being re-fetched on subsequent runs.
592 * Also use RETR if fetchall is on. This gives us a workaround
593 * for servers like usa.net's that bungle TOP. It's pretty
594 * harmless because fetchall guarantees that any message dropped
595 * by an interrupted RETR will be picked up on the next poll of the
598 * We take advantage here of the fact that, according to all the
599 * POP RFCs, "if the number of lines requested by the POP3 client
600 * is greater than than the number of lines in the body, then the
601 * POP3 server sends the entire message.").
603 * The line count passed (99999999) is the maximum value CompuServe will
604 * accept; it's much lower than the natural value 2147483646 (the maximum
605 * twos-complement signed 32-bit integer minus 1) */
606 if (ctl->keep || ctl->fetchall)
607 gen_send(sock, "RETR %d", number);
609 gen_send(sock, "TOP %d 99999999", number);
610 if ((ok = pop3_ok(sock, buf)) != 0)
613 *lenp = -1; /* we got sizes from the LIST response */
618 static int pop3_delete(int sock, struct query *ctl, int number)
619 /* delete a given message */
621 /* actually, mark for deletion -- doesn't happen until QUIT time */
622 return(gen_transact(sock, "DELE %d", number));
625 static int pop3_logout(int sock, struct query *ctl)
626 /* send logout command */
630 /* pop3_phase = PHASE_LOGOUT */
632 ok = gen_transact(sock, "QUIT");
639 const static struct method pop3 =
641 "POP3", /* Post Office Protocol v3 */
643 "pop3", /* standard POP3 port */
645 110, /* standard POP3 port */
647 FALSE, /* this is not a tagged protocol */
648 TRUE, /* this uses a message delimiter */
649 pop3_ok, /* parse command response */
650 NULL, /* no password canonicalization */
651 pop3_getauth, /* get authorization */
652 pop3_getrange, /* query range of messages */
653 pop3_getsizes, /* we can get a list of sizes */
654 pop3_is_old, /* how do we tell a message is old? */
655 pop3_fetch, /* request given message */
656 NULL, /* no way to fetch body alone */
657 NULL, /* no message trailer */
658 pop3_delete, /* how to delete a message */
659 pop3_logout, /* log out, we're done */
660 FALSE, /* no, we can't re-poll */
663 int doPOP3 (struct query *ctl)
664 /* retrieve messages using POP3 */
667 if (ctl->mailboxes->id) {
668 fprintf(stderr,_("Option --remote is not supported with POP3\n"));
672 peek_capable = !ctl->fetchall;
673 return(do_protocol(ctl, &pop3));
675 #endif /* POP3_ENABLE */
677 /* pop3.c ends here */