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
40 static flag sdps_enable = FALSE;
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, 0, 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 sdps_enable = (MULTIDROP(ctl) && strstr(greeting, "demon."));
127 * Use SDPS if configured, regardless of the greeting string
128 * returned from the POP server. (Users accessing demon by a
129 * POP3 proxy may need this)
131 if (ctl->server.sdps)
132 sdps_enable = ctl->server.sdps;
133 #endif /* SDPS_ENABLE */
135 switch (ctl->server.protocol) {
137 ok = gen_transact(sock, "USER %s", ctl->remotename);
141 * CompuServe has changed its RPA behavior. Used to be they didn't
142 * accept PASS, but I'm told this changed in mid-November 1997.
144 if (strstr(greeting, "csi.com")
145 && (start = strchr(ctl->remotename, '@'))
146 && !strcmp("@compuserve.com", start))
148 /* temporary fix to get back out of cleartext authentication */
149 gen_transact(sock, "PASS %s", "dummypass");
151 /* AUTH command should return a list of available mechanisms */
152 if (gen_transact(sock, "AUTH") == 0)
155 flag has_rpa = FALSE;
157 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
159 if (buffer[0] == '.')
161 if (strncasecmp(buffer, "rpa", 3) == 0)
164 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
165 ctl->password, sock))
171 #endif /* RPA_ENABLE */
174 /* see RFC1938: A One-Time Password System */
175 if (challenge = strstr(lastok, "otp-")) {
176 char response[OPIE_RESPONSE_MAX+1];
179 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
180 if ((i == -2) && !run.poll_interval) {
181 char secret[OPIE_SECRET_MAX+1];
182 fprintf(stderr, _("Secret pass phrase: "));
183 if (opiereadpass(secret, sizeof(secret), 0))
184 i = opiegenerator(challenge, secret, response);
185 memset(secret, 0, sizeof(secret));
193 ok = gen_transact(sock, "PASS %s", response);
198 /* ordinary validation, no one-time password or RPA */
199 ok = gen_transact(sock, "PASS %s", ctl->password);
203 /* build MD5 digest from greeting timestamp + password */
204 /* find start of timestamp */
205 for (start = greeting; *start != 0 && *start != '<'; start++)
208 report(stderr, 0, _("Required APOP timestamp not found in greeting"));
212 /* find end of timestamp */
213 for (end = start; *end != 0 && *end != '>'; end++)
215 if (*end == 0 || end == start + 1) {
216 report(stderr, 0, _("Timestamp syntax error in greeting"));
222 /* copy timestamp and password into digestion buffer */
223 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
225 strcat(msg,ctl->password);
227 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
229 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
233 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
234 ok = gen_transact(sock, "RPOP %s", ctl->password);
238 report(stderr, 0, _("Undefined protocol request in POP3_auth"));
244 /* maybe we detected a lock-busy condition? */
245 if (ok == PS_LOCKBUSY)
246 report(stderr, 0, _("lock busy! Is another session active?"));
252 * Empirical experience shows some server/OS combinations
253 * may need a brief pause even after any lockfiles on the
254 * server are released, to give the server time to finish
255 * copying back very large mailfolders from the temp-file...
256 * this is only ever an issue with extremely large mailboxes.
258 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
260 /* we're peek-capable if use of TOP is enabled */
261 peek_capable = !(ctl->fetchall || ctl->keep);
268 pop3_gettopid( int sock, int num , char *id)
272 char buf [POPBUFSIZE+1];
273 sprintf( buf, "TOP %d 1", num );
274 if( (ok = gen_transact(sock, buf ) ) != 0 )
277 while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
280 if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
282 /* prevent stack overflows */
284 sscanf( buf+12, "%s", id);
291 pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
293 /* This approach tries to get the message headers from the
294 * remote hosts and compares the message-id to the already known
296 * + if the first message containes a new id, all messages on
297 * the server will be new
298 * + if the first is known, try to estimate the last known message
299 * on the server and check. If this works you know the total number
300 * of messages to get.
301 * + Otherwise run a binary search to determine the last known message
303 int ok, nolinear = 0;
304 int first_nr, list_len, try_id, try_nr, add_id;
308 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
311 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
312 /* the first message is unknown -> all messages are new */
317 /* check where we expect the latest known message */
318 list_len = count_list( &ctl->oldsaved );
319 try_id = list_len - first_nr; /* -1 + 1 */
321 if( try_id <= *countp ) {
322 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
325 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
330 if( try_nr != list_len -1 ) {
331 /* some messages inbetween have been deleted... */
335 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
337 for( ; add_id; add_id >>= 1 ) {
339 if( try_id - add_id <= 1 ) {
346 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
348 try_nr = str_nr_in_list(&ctl->oldsaved, id);
355 _("Messages inserted into list on server. Cannot handle this."));
360 /* the first try_id messages are known -> copy them to the newsaved list */
361 for( num = first_nr; num < list_len; num++ )
363 struct idlist *new = save_str(&ctl->newsaved,
364 str_from_nr_list(&ctl->oldsaved, num),
366 new->val.status.num = num - first_nr + 1;
370 free_str_list(&ctl->oldsaved);
375 *newp = *countp - try_id;
379 static int pop3_getrange(int sock,
382 int *countp, int *newp, int *bytes)
383 /* get range of messages to be fetched */
386 char buf [POPBUFSIZE+1];
388 pop3_phase = PHASE_GETRANGE;
390 /* Ensure that the new list is properly empty */
391 ctl->newsaved = (struct idlist *)NULL;
394 /* Alain Knaff suggests this, but it's not RFC standard */
396 if ((ok = gen_transact(sock, "MBOX %s", folder)))
400 /* get the total message count */
401 gen_send(sock, "STAT");
402 ok = pop3_ok(sock, buf);
404 sscanf(buf,"%d %d", countp, bytes);
409 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
410 * We work as hard as possible to hide this ugliness, but it makes
411 * counting new messages intrinsically quadratic in the worst case.
415 if (*countp > 0 && !ctl->fetchall)
419 if (!ctl->server.uidl) {
420 gen_send(sock, "LAST");
421 ok = pop3_ok(sock, buf);
426 if (sscanf(buf, "%d", &last) == 0)
428 report(stderr, 0, _("protocol error"));
431 *newp = (*countp - last);
435 /* grab the mailbox's UID list */
436 if ((ok = gen_transact(sock, "UIDL")) != 0)
438 /* don't worry, yet! do it the slow way */
439 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
441 report(stderr, 0, _("protocol error while fetching UIDLs"));
450 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
454 else if (sscanf(buf, "%d %s", &num, id) == 2)
458 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
459 new->val.status.num = num;
461 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
462 new->val.status.mark = UID_SEEN;
463 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
476 static int pop3_getsizes(int sock, int count, int *sizes)
477 /* capture the sizes of all messages */
481 /* pop3_phase = PHASE_GETSIZES */
483 if ((ok = gen_transact(sock, "LIST")) != 0)
487 char buf [POPBUFSIZE+1];
489 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
495 else if (sscanf(buf, "%d %d", &num, &size) == 2)
496 sizes[num - 1] = size;
503 static int pop3_is_old(int sock, struct query *ctl, int num)
504 /* is the given message old? */
507 return (num <= last);
509 return (str_in_list(&ctl->oldsaved,
510 str_find(&ctl->newsaved, num), FALSE));
515 * We could use this to fetch headers only as we do for IMAP. The trouble
516 * is that there's no way to fetch the body only. So the following RETR
517 * would have to re-fetch the header. Enough messages have longer headers
518 * than bodies to make this a net loss.
520 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
521 /* request headers of nth message */
524 char buf[POPBUFSIZE+1];
526 /* pop3_phase = PHASE_FETCH */
528 gen_send(sock, "TOP %d 0", number);
529 if ((ok = pop3_ok(sock, buf)) != 0)
532 *lenp = -1; /* we got sizes from the LIST response */
538 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
539 /* request nth message */
542 char buf[POPBUFSIZE+1];
544 /* pop3_phase = PHASE_FETCH */
548 * See http://www.demon.net/services/mail/sdps-tech.html
549 * for a description of what we're parsing here.
555 sdps_envto = (char *)NULL;
556 gen_send(sock, "*ENV %d", number);
558 if (gen_recv(sock, buf, sizeof(buf)))
565 /* Wrap address with To: <> so nxtaddr() likes it */
566 sdps_envto = xmalloc(strlen(buf)+7);
567 sprintf(sdps_envto,"To: <%s>",buf);
570 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
572 #endif /* SDPS_ENABLE */
575 * Though the POP RFCs don't document this fact, on every POP3 server
576 * I know of messages are marked "seen" only at the time the OK
577 * response to a RETR is issued.
579 * This means we can use TOP to fetch the message without setting its
580 * seen flag. This is good! It means that if the protocol exchange
581 * craps out during the message, it will still be marked `unseen' on
584 * However...*don't* do this if we're using keep to suppress deletion!
585 * In that case, marking the seen flag is the only way to prevent the
586 * message from being re-fetched on subsequent runs.
588 * Also use RETR if fetchall is on. This gives us a workaround
589 * for servers like usa.net's that bungle TOP. It's pretty
590 * harmless because fetchall guarantees that any message dropped
591 * by an interrupted RETR will be picked up on the next poll of the
594 * We take advantage here of the fact that, according to all the
595 * POP RFCs, "if the number of lines requested by the POP3 client
596 * is greater than than the number of lines in the body, then the
597 * POP3 server sends the entire message.").
599 * The line count passed (99999999) is the maximum value CompuServe will
600 * accept; it's much lower than the natural value 2147483646 (the maximum
601 * twos-complement signed 32-bit integer minus 1)
603 if (ctl->keep || ctl->fetchall)
604 gen_send(sock, "RETR %d", number);
606 gen_send(sock, "TOP %d 99999999", number);
607 if ((ok = pop3_ok(sock, buf)) != 0)
610 *lenp = -1; /* we got sizes from the LIST response */
615 static int pop3_delete(int sock, struct query *ctl, int number)
616 /* delete a given message */
618 /* actually, mark for deletion -- doesn't happen until QUIT time */
619 return(gen_transact(sock, "DELE %d", number));
622 static int pop3_logout(int sock, struct query *ctl)
623 /* send logout command */
627 /* pop3_phase = PHASE_LOGOUT */
629 ok = gen_transact(sock, "QUIT");
636 const static struct method pop3 =
638 "POP3", /* Post Office Protocol v3 */
640 "pop3", /* standard POP3 port */
642 110, /* standard POP3 port */
644 FALSE, /* this is not a tagged protocol */
645 TRUE, /* this uses a message delimiter */
646 pop3_ok, /* parse command response */
647 NULL, /* no password canonicalization */
648 pop3_getauth, /* get authorization */
649 pop3_getrange, /* query range of messages */
650 pop3_getsizes, /* we can get a list of sizes */
651 pop3_is_old, /* how do we tell a message is old? */
652 pop3_fetch, /* request given message */
653 NULL, /* no way to fetch body alone */
654 NULL, /* no message trailer */
655 pop3_delete, /* how to delete a message */
656 pop3_logout, /* log out, we're done */
657 FALSE, /* no, we can't re-poll */
660 int doPOP3 (struct query *ctl)
661 /* retrieve messages using POP3 */
664 if (ctl->mailboxes->id) {
665 fprintf(stderr,_("Option --remote is not supported with POP3\n"));
669 peek_capable = !ctl->fetchall;
670 return(do_protocol(ctl, &pop3));
672 #endif /* POP3_ENABLE */
674 /* pop3.c ends here */