2 * pop3.c -- POP3 protocol methods
4 * For license terms, see the file COPYING in this directory.
6 * i18n by Arnaldo Carvalho de Melo <acme@conectiva.com.br> 7-Nov-1998
14 #if defined(HAVE_UNISTD_H)
17 #if defined(STDC_HEADERS)
21 #include "fetchmail.h"
29 #ifndef strstr /* glibc-2.1 declares this as a macro */
30 extern char *strstr(); /* needed on sysV68 R3V7.1. */
33 static int pop3_phase;
34 #define PHASE_GETAUTH 0
35 #define PHASE_GETRANGE 1
36 #define PHASE_GETSIZES 2
38 #define PHASE_LOGOUT 4
41 static flag sdps_enable = FALSE;
43 #endif /* SDPS_ENABLE */
46 static char lastok[POPBUFSIZE+1];
49 int pop3_ok (int sock, char *argbuf)
50 /* parse command response */
53 char buf [POPBUFSIZE+1];
56 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
59 if (*bufp == '+' || *bufp == '-')
64 while (isalpha(*bufp))
70 if (strcmp(buf,"+OK") == 0)
77 else if (strncmp(buf,"-ERR", 4) == 0)
79 if (pop3_phase > PHASE_GETAUTH)
82 * We're checking for "lock busy", "unable to lock",
83 * "already locked" etc. here. This indicates that we
84 * have to wait for the server to clean up before we
87 * PS_LOCKBUSY check empirically verified with two recent
88 * versions the Berkeley popper; QPOP (version 2.2) and
89 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
91 else if (strstr(bufp,"lock")||strstr(bufp,"Lock")||strstr(bufp,"LOCK"))
108 int pop3_getauth(int sock, struct query *ctl, char *greeting)
109 /* apply for connection authorization */
118 pop3_phase = PHASE_GETAUTH;
122 * This needs to catch both demon.co.uk and demon.net.
123 * If we see either, and we're in multidrop mode, try to use
124 * the SDPS *ENV extension.
126 sdps_enable = (MULTIDROP(ctl) && strstr(greeting, "demon."));
128 * Use SDPS if configured, regardless of the greeting string
129 * returned from the POP server. (Users accessing demon by a
130 * POP3 proxy may need this)
132 if (ctl->server.sdps)
133 sdps_enable = ctl->server.sdps;
134 #endif /* SDPS_ENABLE */
136 switch (ctl->server.protocol) {
138 ok = gen_transact(sock, "USER %s", ctl->remotename);
142 * CompuServe has changed its RPA behavior. Used to be they didn't
143 * accept PASS, but I'm told this changed in mid-November 1997.
145 if (strstr(greeting, "csi.com")
146 && (start = strchr(ctl->remotename, '@'))
147 && !strcmp("@compuserve.com", start))
149 /* temporary fix to get back out of cleartext authentication */
150 gen_transact(sock, "PASS %s", "dummypass");
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)
160 if (buffer[0] == '.')
162 if (strncasecmp(buffer, "rpa", 3) == 0)
165 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
166 ctl->password, sock))
172 #endif /* RPA_ENABLE */
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);
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++)
209 error(0, -1, _("Required APOP timestamp not found in greeting"));
213 /* find end of timestamp */
214 for (end = start; *end != 0 && *end != '>'; end++)
216 if (*end == 0 || end == start + 1) {
217 error(0, -1, _("Timestamp syntax error in greeting"));
223 /* copy timestamp and password into digestion buffer */
224 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
226 strcat(msg,ctl->password);
228 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
230 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
234 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
235 ok = gen_transact(sock, "RPOP %s", ctl->password);
239 error(0, 0, _("Undefined protocol request in POP3_auth"));
245 /* maybe we detected a lock-busy condition? */
246 if (ok == PS_LOCKBUSY)
247 error(0, 0, _("lock busy! Is another session active?"));
253 * Empirical experience shows some server/OS combinations
254 * may need a brief pause even after any lockfiles on the
255 * server are released, to give the server time to finish
256 * copying back very large mailfolders from the temp-file...
257 * this is only ever an issue with extremely large mailboxes.
259 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
261 /* we're peek-capable if use of TOP is enabled */
262 peek_capable = !(ctl->fetchall || ctl->keep);
269 pop3_gettopid( int sock, int num , char *id)
273 char buf [POPBUFSIZE+1];
274 sprintf( buf, "TOP %d 1", num );
275 if( (ok = gen_transact(sock, buf ) ) != 0 )
278 while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
281 if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
283 /* prevent stack overflows */
285 sscanf( buf+12, "%s", id);
292 pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
294 /* This approach tries to get the message headers from the
295 * remote hosts and compares the message-id to the already known
297 * + if the first message containes a new id, all messages on
298 * the server will be new
299 * + if the first is known, try to estimate the last known message
300 * on the server and check. If this works you know the total number
301 * of messages to get.
302 * + Otherwise run a binary search to determine the last known message
304 int ok, nolinear = 0;
305 int first_nr, list_len, try_id, try_nr, add_id;
309 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
312 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
313 /* the first message is unknown -> all messages are new */
318 /* check where we expect the latest known message */
319 list_len = count_list( &ctl->oldsaved );
320 try_id = list_len - first_nr; /* -1 + 1 */
322 if( try_id <= *countp ) {
323 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
326 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
331 if( try_nr != list_len -1 ) {
332 /* some messages inbetween have been deleted... */
336 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
338 for( ; add_id; add_id >>= 1 ) {
340 if( try_id - add_id <= 1 ) {
347 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
349 try_nr = str_nr_in_list(&ctl->oldsaved, id);
355 error(0,0,_("Messages inserted into list on server. "
356 "Cannot handle this."));
361 /* the first try_id messages are known -> copy them to the newsaved list */
362 for( num = first_nr; num < list_len; num++ )
364 struct idlist *new = save_str(&ctl->newsaved,
365 str_from_nr_list(&ctl->oldsaved, num),
367 new->val.status.num = num - first_nr + 1;
371 free_str_list(&ctl->oldsaved);
376 *newp = *countp - try_id;
380 static int pop3_getrange(int sock,
383 int *countp, int *newp, int *bytes)
384 /* get range of messages to be fetched */
387 char buf [POPBUFSIZE+1];
389 pop3_phase = PHASE_GETRANGE;
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 error(0, 0, _("protocol error"));
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 error(0, 0, _("protocol error while fetching UIDLs"));
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 /* pop3_phase = PHASE_GETSIZES */
484 if ((ok = gen_transact(sock, "LIST")) != 0)
488 char buf [POPBUFSIZE+1];
490 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
496 else if (sscanf(buf, "%d %d", &num, &size) == 2)
497 sizes[num - 1] = size;
504 static int pop3_is_old(int sock, struct query *ctl, int num)
505 /* is the given message old? */
508 return (num <= last);
510 return (str_in_list(&ctl->oldsaved,
511 str_find(&ctl->newsaved, num), FALSE));
516 * We could use this to fetch headers only as we do for IMAP. The trouble
517 * is that there's no way to fetch the body only. So the following RETR
518 * would have to re-fetch the header. Enough messages have longer headers
519 * than bodies to make this a net loss.
521 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
522 /* request headers of nth message */
525 char buf[POPBUFSIZE+1];
527 /* pop3_phase = PHASE_FETCH */
529 gen_send(sock, "TOP %d 0", number);
530 if ((ok = pop3_ok(sock, buf)) != 0)
533 *lenp = -1; /* we got sizes from the LIST response */
539 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
540 /* request nth message */
543 char buf[POPBUFSIZE+1];
545 /* pop3_phase = PHASE_FETCH */
549 * See http://www.demon.net/services/mail/sdps-tech.html
550 * for a description of what we're parsing here.
556 sdps_envto = (char *)NULL;
557 gen_send(sock, "*ENV %d", number);
559 if (gen_recv(sock, buf, sizeof(buf)))
566 /* Wrap address with To: <> so nxtaddr() likes it */
567 sdps_envto = xmalloc(strlen(buf)+7);
568 sprintf(sdps_envto,"To: <%s>",buf);
573 #endif /* SDPS_ENABLE */
576 * Though the POP RFCs don't document this fact, on every POP3 server
577 * I know of messages are marked "seen" only at the time the OK
578 * response to a RETR is issued.
580 * This means we can use TOP to fetch the message without setting its
581 * seen flag. This is good! It means that if the protocol exchange
582 * craps out during the message, it will still be marked `unseen' on
585 * However...*don't* do this if we're using keep to suppress deletion!
586 * In that case, marking the seen flag is the only way to prevent the
587 * message from being re-fetched on subsequent runs.
589 * Also use RETR if fetchall is on. This gives us a workaround
590 * for servers like usa.net's that bungle TOP. It's pretty
591 * harmless because fetchall guarantees that any message dropped
592 * by an interrupted RETR will be picked up on the next poll of the
595 * We take advantage here of the fact that, according to all the
596 * POP RFCs, "if the number of lines requested by the POP3 client
597 * is greater than than the number of lines in the body, then the
598 * POP3 server sends the entire message.").
600 * The line count passed (99999999) is the maximum value CompuServe will
601 * accept; it's much lower than the natural value 2147483646 (the maximum
602 * twos-complement signed 32-bit integer minus 1)
604 if (ctl->keep || ctl->fetchall)
605 gen_send(sock, "RETR %d", number);
607 gen_send(sock, "TOP %d 99999999", number);
608 if ((ok = pop3_ok(sock, buf)) != 0)
611 *lenp = -1; /* we got sizes from the LIST response */
616 static int pop3_delete(int sock, struct query *ctl, int number)
617 /* delete a given message */
619 /* actually, mark for deletion -- doesn't happen until QUIT time */
620 return(gen_transact(sock, "DELE %d", number));
623 static int pop3_logout(int sock, struct query *ctl)
624 /* send logout command */
628 /* pop3_phase = PHASE_LOGOUT */
630 ok = gen_transact(sock, "QUIT");
637 const static struct method pop3 =
639 "POP3", /* Post Office Protocol v3 */
641 "pop3", /* standard POP3 port */
643 110, /* standard POP3 port */
645 FALSE, /* this is not a tagged protocol */
646 TRUE, /* this uses a message delimiter */
647 pop3_ok, /* parse command response */
648 NULL, /* no password canonicalization */
649 pop3_getauth, /* get authorization */
650 pop3_getrange, /* query range of messages */
651 pop3_getsizes, /* we can get a list of sizes */
652 pop3_is_old, /* how do we tell a message is old? */
653 pop3_fetch, /* request given message */
654 NULL, /* no way to fetch body alone */
655 NULL, /* no message trailer */
656 pop3_delete, /* how to delete a message */
657 pop3_logout, /* log out, we're done */
658 FALSE, /* no, we can't re-poll */
661 int doPOP3 (struct query *ctl)
662 /* retrieve messages using POP3 */
665 if (ctl->mailboxes->id) {
666 fprintf(stderr,_("Option --remote is not supported with POP3\n"));
670 peek_capable = !ctl->fetchall;
671 return(do_protocol(ctl, &pop3));
673 #endif /* POP3_ENABLE */
675 /* pop3.c ends here */