2 * pop3.c -- POP3 protocol methods
4 * For license terms, see the file COPYING in this directory.
12 #if defined(HAVE_UNISTD_H)
15 #if defined(STDC_HEADERS)
19 #include "fetchmail.h"
26 #ifndef strstr /* glibc-2.1 declares this as a macro */
27 extern char *strstr(); /* needed on sysV68 R3V7.1. */
30 static int pop3_phase;
31 #define PHASE_GETAUTH 0
32 #define PHASE_GETRANGE 1
33 #define PHASE_GETSIZES 2
35 #define PHASE_LOGOUT 4
38 static flag sdps_enable = FALSE;
40 #endif /* SDPS_ENABLE */
43 static char lastok[POPBUFSIZE+1];
46 int pop3_ok (int sock, char *argbuf)
47 /* parse command response */
50 char buf [POPBUFSIZE+1];
53 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
56 if (*bufp == '+' || *bufp == '-')
61 while (isalpha(*bufp))
67 if (strcmp(buf,"+OK") == 0)
74 else if (strncmp(buf,"-ERR", 4) == 0)
76 if (pop3_phase > PHASE_GETAUTH)
79 * We're checking for "lock busy", "unable to lock",
80 * "already locked" etc. here. This indicates that we
81 * have to wait for the server to clean up before we
84 * PS_LOCKBUSY check empirically verified with two recent
85 * versions the Berkeley popper; QPOP (version 2.2) and
86 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
88 else if (strstr(bufp,"lock")||strstr(bufp,"Lock")||strstr(bufp,"LOCK"))
105 int pop3_getauth(int sock, struct query *ctl, char *greeting)
106 /* apply for connection authorization */
115 pop3_phase = PHASE_GETAUTH;
119 * This needs to catch both demon.co.uk and demon.net.
120 * If we see either, and we're in multidrop mode, try to use
121 * the SDPS *ENV extension.
123 sdps_enable = (MULTIDROP(ctl) && strstr(greeting, "demon."));
125 * Use SDPS if configured, regardless of the greeting string
126 * returned from the POP server. (Users accessing demon by a
127 * POP3 proxy may need this)
129 if (ctl->server.sdps)
130 sdps_enable = ctl->server.sdps;
131 #endif /* SDPS_ENABLE */
133 switch (ctl->server.protocol) {
135 ok = gen_transact(sock, "USER %s", ctl->remotename);
139 * CompuServe has changed its RPA behavior. Used to be they didn't
140 * accept PASS, but I'm told this changed in mid-November 1997.
142 if (strstr(greeting, "csi.com")
143 && (start = strchr(ctl->remotename, '@'))
144 && !strcmp("@compuserve.com", start))
146 /* temporary fix to get back out of cleartext authentication */
147 gen_transact(sock, "PASS %s", "dummypass");
149 /* AUTH command should return a list of available mechanisms */
150 if (gen_transact(sock, "AUTH") == 0)
153 flag has_rpa = FALSE;
155 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
157 if (buffer[0] == '.')
159 if (strncasecmp(buffer, "rpa", 3) == 0)
162 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
163 ctl->password, sock))
169 #endif /* RPA_ENABLE */
172 /* see RFC1938: A One-Time Password System */
173 if (challenge = strstr(lastok, "otp-")) {
174 char response[OPIE_RESPONSE_MAX+1];
177 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
178 if ((i == -2) && !run.poll_interval) {
179 char secret[OPIE_SECRET_MAX+1];
180 fprintf(stderr, "Secret pass phrase: ");
181 if (opiereadpass(secret, sizeof(secret), 0))
182 i = opiegenerator(challenge, secret, response);
183 memset(secret, 0, sizeof(secret));
191 ok = gen_transact(sock, "PASS %s", response);
196 /* ordinary validation, no one-time password or RPA */
197 ok = gen_transact(sock, "PASS %s", ctl->password);
201 /* build MD5 digest from greeting timestamp + password */
202 /* find start of timestamp */
203 for (start = greeting; *start != 0 && *start != '<'; start++)
206 error(0, -1, "Required APOP timestamp not found in greeting");
210 /* find end of timestamp */
211 for (end = start; *end != 0 && *end != '>'; end++)
213 if (*end == 0 || end == start + 1) {
214 error(0, -1, "Timestamp syntax error in greeting");
220 /* copy timestamp and password into digestion buffer */
221 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
223 strcat(msg,ctl->password);
225 strcpy(ctl->digest, MD5Digest(msg));
227 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
231 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
232 ok = gen_transact(sock, "RPOP %s", ctl->password);
236 error(0, 0, "Undefined protocol request in POP3_auth");
242 /* maybe we detected a lock-busy condition? */
243 if (ok == PS_LOCKBUSY)
244 error(0, 0, "lock busy! Is another session active?");
250 * Empirical experience shows some server/OS combinations
251 * may need a brief pause even after any lockfiles on the
252 * server are released, to give the server time to finish
253 * copying back very large mailfolders from the temp-file...
254 * this is only ever an issue with extremely large mailboxes.
256 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
258 /* we're peek-capable if use of TOP is enabled */
259 peek_capable = !(ctl->fetchall || ctl->keep);
266 pop3_gettopid( int sock, int num , char *id)
270 char buf [POPBUFSIZE+1];
271 sprintf( buf, "TOP %d 1", num );
272 if( (ok = gen_transact(sock, buf ) ) != 0 )
275 while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
278 if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
280 /* prevent stack overflows */
282 sscanf( buf+12, "%s", id);
289 pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
291 /* This approach tries to get the message headers from the
292 * remote hosts and compares the message-id to the already known
294 * + if the first message containes a new id, all messages on
295 * the server will be new
296 * + if the first is known, try to estimate the last known message
297 * on the server and check. If this works you know the total number
298 * of messages to get.
299 * + Otherwise run a binary search to determine the last known message
301 int ok, nolinear = 0;
302 int first_nr, list_len, try_id, try_nr, add_id;
306 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
309 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
310 /* the first message is unknown -> all messages are new */
315 /* check where we expect the latest known message */
316 list_len = count_list( &ctl->oldsaved );
317 try_id = list_len - first_nr; /* -1 + 1 */
319 if( try_id <= *countp ) {
320 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
323 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
328 if( try_nr != list_len -1 ) {
329 /* some messages inbetween have been deleted... */
333 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
335 for( ; add_id; add_id >>= 1 ) {
337 if( try_id - add_id <= 1 ) {
344 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
346 try_nr = str_nr_in_list(&ctl->oldsaved, id);
352 error(0,0,"Messages inserted into list on server. "
353 "Cannot handle this.");
358 /* the first try_id messages are known -> copy them to the newsaved list */
359 for( num = first_nr; num < list_len; num++ )
361 struct idlist *new = save_str(&ctl->newsaved,
362 str_from_nr_list(&ctl->oldsaved, num),
364 new->val.status.num = num - first_nr + 1;
368 free_str_list(&ctl->oldsaved);
373 *newp = *countp - try_id;
377 static int pop3_getrange(int sock,
380 int *countp, int *newp, int *bytes)
381 /* get range of messages to be fetched */
384 char buf [POPBUFSIZE+1];
386 pop3_phase = PHASE_GETRANGE;
388 /* Ensure that the new list is properly empty */
389 ctl->newsaved = (struct idlist *)NULL;
392 /* Alain Knaff suggests this, but it's not RFC standard */
394 if ((ok = gen_transact(sock, "MBOX %s", folder)))
398 /* get the total message count */
399 gen_send(sock, "STAT");
400 ok = pop3_ok(sock, buf);
402 sscanf(buf,"%d %d", countp, bytes);
407 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
408 * We work as hard as possible to hide this ugliness, but it makes
409 * counting new messages intrinsically quadratic in the worst case.
413 if (*countp > 0 && !ctl->fetchall)
417 if (!ctl->server.uidl) {
418 gen_send(sock, "LAST");
419 ok = pop3_ok(sock, buf);
424 if (sscanf(buf, "%d", &last) == 0)
426 error(0, 0, "protocol error");
429 *newp = (*countp - last);
433 /* grab the mailbox's UID list */
434 if ((ok = gen_transact(sock, "UIDL")) != 0)
436 /* don't worry, yet! do it the slow way */
437 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
439 error(0, 0, "protocol error while fetching UIDLs");
448 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
452 else if (sscanf(buf, "%d %s", &num, id) == 2)
456 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
457 new->val.status.num = num;
459 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
460 new->val.status.mark = UID_SEEN;
461 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
474 static int pop3_getsizes(int sock, int count, int *sizes)
475 /* capture the sizes of all messages */
479 /* pop3_phase = PHASE_GETSIZES */
481 if ((ok = gen_transact(sock, "LIST")) != 0)
485 char buf [POPBUFSIZE+1];
487 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
493 else if (sscanf(buf, "%d %d", &num, &size) == 2)
494 sizes[num - 1] = size;
501 static int pop3_is_old(int sock, struct query *ctl, int num)
502 /* is the given message old? */
505 return (num <= last);
507 return (str_in_list(&ctl->oldsaved,
508 str_find(&ctl->newsaved, num), FALSE));
513 * We could use this to fetch headers only as we do for IMAP. The trouble
514 * is that there's no way to fetch the body only. So the following RETR
515 * would have to re-fetch the header. Enough messages have longer headers
516 * than bodies to make this a net loss.
518 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
519 /* request headers of nth message */
522 char buf[POPBUFSIZE+1];
524 /* pop3_phase = PHASE_FETCH */
526 gen_send(sock, "TOP %d 0", number);
527 if ((ok = pop3_ok(sock, buf)) != 0)
530 *lenp = -1; /* we got sizes from the LIST response */
536 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
537 /* request nth message */
540 char buf[POPBUFSIZE+1];
542 /* pop3_phase = PHASE_FETCH */
546 * See http://www.demon.net/services/mail/sdps-tech.html
547 * for a description of what we're parsing here.
553 sdps_envto = (char *)NULL;
554 gen_send(sock, "*ENV %d", number);
556 if (gen_recv(sock, buf, sizeof(buf)))
563 /* Wrap address with To: <> so nxtaddr() likes it */
564 sdps_envto = malloc(strlen(buf)+7);
565 sprintf(sdps_envto,"To: <%s>",buf);
570 #endif /* SDPS_ENABLE */
573 * Though the POP RFCs don't document this fact, on every POP3 server
574 * I know of messages are marked "seen" only at the time the OK
575 * response to a RETR is issued.
577 * This means we can use TOP to fetch the message without setting its
578 * seen flag. This is good! It means that if the protocol exchange
579 * craps out during the message, it will still be marked `unseen' on
582 * However...*don't* do this if we're using keep to suppress deletion!
583 * In that case, marking the seen flag is the only way to prevent the
584 * message from being re-fetched on subsequent runs.
586 * Also use RETR if fetchall is on. This gives us a workaround
587 * for servers like usa.net's that bungle TOP. It's pretty
588 * harmless because fetchall guarantees that any message dropped
589 * by an interrupted RETR will be picked up on the next poll of the
592 * We take advantage here of the fact that, according to all the
593 * POP RFCs, "if the number of lines requested by the POP3 client
594 * is greater than than the number of lines in the body, then the
595 * POP3 server sends the entire message.").
597 * The line count passed (99999999) is the maximum value CompuServe will
598 * accept; it's much lower than the natural value 2147483646 (the maximum
599 * twos-complement signed 32-bit integer minus 1)
601 if (ctl->keep || ctl->fetchall)
602 gen_send(sock, "RETR %d", number);
604 gen_send(sock, "TOP %d 99999999", number);
605 if ((ok = pop3_ok(sock, buf)) != 0)
608 *lenp = -1; /* we got sizes from the LIST response */
613 static int pop3_delete(int sock, struct query *ctl, int number)
614 /* delete a given message */
616 /* actually, mark for deletion -- doesn't happen until QUIT time */
617 return(gen_transact(sock, "DELE %d", number));
620 static int pop3_logout(int sock, struct query *ctl)
621 /* send logout command */
625 /* pop3_phase = PHASE_LOGOUT */
627 ok = gen_transact(sock, "QUIT");
634 const static struct method pop3 =
636 "POP3", /* Post Office Protocol v3 */
638 "pop3", /* standard POP3 port */
640 110, /* standard POP3 port */
642 FALSE, /* this is not a tagged protocol */
643 TRUE, /* this uses a message delimiter */
644 pop3_ok, /* parse command response */
645 NULL, /* no password canonicalization */
646 pop3_getauth, /* get authorization */
647 pop3_getrange, /* query range of messages */
648 pop3_getsizes, /* we can get a list of sizes */
649 pop3_is_old, /* how do we tell a message is old? */
650 pop3_fetch, /* request given message */
651 NULL, /* no way to fetch body alone */
652 NULL, /* no message trailer */
653 pop3_delete, /* how to delete a message */
654 pop3_logout, /* log out, we're done */
655 FALSE, /* no, we can't re-poll */
658 int doPOP3 (struct query *ctl)
659 /* retrieve messages using POP3 */
662 if (ctl->mailboxes->id) {
663 fprintf(stderr,"Option --remote is not supported with POP3\n");
667 peek_capable = FALSE;
668 return(do_protocol(ctl, &pop3));
670 #endif /* POP3_ENABLE */
672 /* pop3.c ends here */