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. */
31 #define PHASE_GETAUTH 0
32 #define PHASE_GETRANGE 1
33 #define PHASE_GETSIZES 2
35 #define PHASE_LOGOUT 4
39 static char lastok[POPBUFSIZE+1];
42 int pop3_ok (int sock, char *argbuf)
43 /* parse command response */
46 char buf [POPBUFSIZE+1];
49 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
52 if (*bufp == '+' || *bufp == '-')
57 while (isalpha(*bufp))
63 if (strcmp(buf,"+OK") == 0)
70 else if (strcmp(buf,"-ERR") == 0)
72 if (phase > PHASE_GETAUTH)
75 * We're checking for "lock busy", "unable to lock",
76 * "already locked" etc. here. This indicates that we
77 * have to wait for the server to clean up before we
80 * PS_LOCKBUSY check empirically verified with two recent
81 * versions the Berkeley popper; QPOP (version 2.2) and
82 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
84 else if (strstr(bufp,"lock")||strstr(bufp,"Lock")||strstr(bufp,"LOCK"))
101 int pop3_getauth(int sock, struct query *ctl, char *greeting)
102 /* apply for connection authorization */
111 phase = PHASE_GETAUTH;
113 switch (ctl->server.protocol) {
115 ok = gen_transact(sock, "USER %s", ctl->remotename);
119 * CompuServe has changed its RPA behavior. Used to be they didn't
120 * accept PASS, but I'm told this changed in mid-November 1997.
122 if (strstr(greeting, "csi.com"))
124 /* temporary fix to get back out of cleartext authentication */
125 gen_transact(sock, "PASS %s", "dummypass");
127 /* AUTH command should return a list of available mechanisms */
128 if (gen_transact(sock, "AUTH") == 0)
131 flag has_rpa = FALSE;
133 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
135 if (buffer[0] == '.')
137 if (strncasecmp(buffer, "rpa", 3) == 0)
140 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
141 ctl->password, sock))
147 #endif /* RPA_ENABLE */
150 /* see RFC1938: A One-Time Password System */
151 if (challenge = strstr(lastok, "otp-")) {
152 char response[OPIE_RESPONSE_MAX+1];
155 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
156 if ((i == -2) && (cmd_daemon == -1)) {
157 char secret[OPIE_SECRET_MAX+1];
158 fprintf(stderr, "Secret pass phrase: ");
159 if (opiereadpass(secret, sizeof(secret), 0))
160 i = opiegenerator(challenge, secret, response);
161 memset(secret, 0, sizeof(secret));
169 ok = gen_transact(sock, "PASS %s", response);
174 /* ordinary validation, no one-time password or RPA */
175 ok = gen_transact(sock, "PASS %s", ctl->password);
179 /* build MD5 digest from greeting timestamp + password */
180 /* find start of timestamp */
181 for (start = greeting; *start != 0 && *start != '<'; start++)
184 error(0, -1, "Required APOP timestamp not found in greeting");
188 /* find end of timestamp */
189 for (end = start; *end != 0 && *end != '>'; end++)
191 if (*end == 0 || end == start + 1) {
192 error(0, -1, "Timestamp syntax error in greeting");
198 /* copy timestamp and password into digestion buffer */
199 msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
201 strcat(msg,ctl->password);
203 strcpy(ctl->digest, MD5Digest(msg));
206 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
210 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
211 ok = gen_transact(sock, "RPOP %s", ctl->password);
215 error(0, 0, "Undefined protocol request in POP3_auth");
221 /* maybe we detected a lock-busy condition? */
222 if (ok == PS_LOCKBUSY)
223 error(0, 0, "lock busy! Is another session active?");
229 * Empirical experience shows some server/OS combinations
230 * may need a brief pause even after any lockfiles on the
231 * server are released, to give the server time to finish
232 * copying back very large mailfolders from the temp-file...
233 * this is only ever an issue with extremely large mailboxes.
235 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
237 /* we're peek-capable if use of TOP is enabled */
238 peek_capable = !(ctl->fetchall || ctl->keep);
245 pop3_gettopid( int sock, int num , char *id)
249 char buf [POPBUFSIZE+1];
250 sprintf( buf, "TOP %d 1", num );
251 if( (ok = gen_transact(sock, buf ) ) != 0 )
254 while((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
257 if( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
259 /* prevent stack overflows */
261 sscanf( buf+12, "%s", id);
268 pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
270 /* This approach tries to get the message headers from the
271 * remote hosts and compares the message-id to the already known
273 * + if the first message containes a new id, all messages on
274 * the server will be new
275 * + if the first is known, try to estimate the last known message
276 * on the server and check. If this works you know the total number
277 * of messages to get.
278 * + Otherwise run a binary search to determine the last known message
280 int ok, nolinear = 0;
281 int first_nr, list_len, try_id, try_nr, add_id;
285 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
288 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
289 /* the first message is unknown -> all messages are new */
294 /* check where we expect the latest known message */
295 list_len = count_list( &ctl->oldsaved );
296 try_id = list_len - first_nr; /* -1 + 1 */
298 if( try_id <= *countp ) {
299 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
302 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
307 if( try_nr != list_len -1 ) {
308 /* some messages inbetween have been deleted... */
312 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
314 for( ; add_id; add_id >>= 1 ) {
316 if( try_id - add_id <= 1 ) {
323 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
325 try_nr = str_nr_in_list(&ctl->oldsaved, id);
331 error(0,0,"Messages inserted into list on server. "
332 "Cannot handle this.");
337 /* the first try_id messages are known -> copy them to the newsaved list */
338 for( num = first_nr; num < list_len; num++ )
340 struct idlist *new = save_str(&ctl->newsaved,
341 str_from_nr_list(&ctl->oldsaved, num),
343 new->val.status.num = num - first_nr + 1;
347 free_str_list(&ctl->oldsaved);
352 *newp = *countp - try_id;
356 static int pop3_getrange(int sock,
359 int *countp, int *newp, int *bytes)
360 /* get range of messages to be fetched */
363 char buf [POPBUFSIZE+1];
365 phase = PHASE_GETRANGE;
367 /* Ensure that the new list is properly empty */
368 ctl->newsaved = (struct idlist *)NULL;
371 /* Alain Knaff suggests this, but it's not RFC standard */
373 if ((ok = gen_transact(sock, "MBOX %s", folder)))
377 /* get the total message count */
378 gen_send(sock, "STAT");
379 ok = pop3_ok(sock, buf);
381 sscanf(buf,"%d %d", countp, bytes);
386 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
387 * We work as hard as possible to hide this ugliness, but it makes
388 * counting new messages intrinsically quadratic in the worst case.
392 if (*countp > 0 && !ctl->fetchall)
396 if (!ctl->server.uidl) {
397 gen_send(sock, "LAST");
398 ok = pop3_ok(sock, buf);
403 if (sscanf(buf, "%d", &last) == 0)
405 error(0, 0, "protocol error");
408 *newp = (*countp - last);
412 /* grab the mailbox's UID list */
413 if ((ok = gen_transact(sock, "UIDL")) != 0)
415 /* don't worry, yet! do it the slow way */
416 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
418 error(0, 0, "protocol error while fetching UIDLs");
427 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
431 else if (sscanf(buf, "%d %s", &num, id) == 2)
435 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
436 new->val.status.num = num;
438 if (str_in_list(&ctl->oldsaved, id, FALSE)) {
439 new->val.status.mark = UID_SEEN;
440 str_set_mark(&ctl->oldsaved, id, UID_SEEN);
453 static int pop3_getsizes(int sock, int count, int *sizes)
454 /* capture the sizes of all messages */
458 /* phase = PHASE_GETSIZES */
460 if ((ok = gen_transact(sock, "LIST")) != 0)
464 char buf [POPBUFSIZE+1];
466 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
472 else if (sscanf(buf, "%d %d", &num, &size) == 2)
473 sizes[num - 1] = size;
480 static int pop3_is_old(int sock, struct query *ctl, int num)
481 /* is the given message old? */
484 return (num <= last);
486 return (str_in_list(&ctl->oldsaved,
487 str_find(&ctl->newsaved, num), FALSE));
492 * We could use this to fetch headers only as we do for IMAP. The trouble
493 * is that there's no way to fetch the body only. So the following RETR
494 * would have to re-fetch the header. Enough messages have longer headers
495 * than bodies to make this a net loss.
497 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
498 /* request headers of nth message */
501 char buf[POPBUFSIZE+1];
503 /* phase = PHASE_FETCH */
505 gen_send(sock, "TOP %d 0", number);
506 if ((ok = pop3_ok(sock, buf)) != 0)
509 *lenp = -1; /* we got sizes from the LIST response */
515 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
516 /* request nth message */
519 char buf[POPBUFSIZE+1];
521 /* phase = PHASE_FETCH */
524 * Though the POP RFCs don't document this fact, on every POP3 server
525 * I know of messages are marked "seen" only at the time the OK
526 * response to a RETR is issued.
528 * This means we can use TOP to fetch the message without setting its
529 * seen flag. This is good! It means that if the protocol exchange
530 * craps out during the message, it will still be marked `unseen' on
533 * However...*don't* do this if we're using keep to suppress deletion!
534 * In that case, marking the seen flag is the only way to prevent the
535 * message from being re-fetched on subsequent runs.
537 * Also use RETR if fetchall is on. This gives us a workaround
538 * for servers like usa.net's that bungle TOP. It's pretty
539 * harmless because fetchall guarantees that any message dropped
540 * by an interrupted RETR will be picked up on the next poll of the
543 * We take advantage here of the fact that, according to all the
544 * POP RFCs, "if the number of lines requested by the POP3 client
545 * is greater than than the number of lines in the body, then the
546 * POP3 server sends the entire message.").
548 * The line count passed (99999999) is the maximum value CompuServe will
549 * accept; it's much lower than the natural value 2147483646 (the maximum
550 * twos-complement signed 32-bit integer minus 1)
552 if (ctl->keep || ctl->fetchall)
553 gen_send(sock, "RETR %d", number);
555 gen_send(sock, "TOP %d 99999999", number);
556 if ((ok = pop3_ok(sock, buf)) != 0)
559 *lenp = -1; /* we got sizes from the LIST response */
564 static int pop3_delete(int sock, struct query *ctl, int number)
565 /* delete a given message */
567 /* actually, mark for deletion -- doesn't happen until QUIT time */
568 return(gen_transact(sock, "DELE %d", number));
571 static int pop3_logout(int sock, struct query *ctl)
572 /* send logout command */
576 /* phase = PHASE_LOGOUT */
578 ok = gen_transact(sock, "QUIT");
585 const static struct method pop3 =
587 "POP3", /* Post Office Protocol v3 */
589 "pop3", /* standard POP3 port */
591 110, /* standard POP3 port */
593 FALSE, /* this is not a tagged protocol */
594 TRUE, /* this uses a message delimiter */
595 pop3_ok, /* parse command response */
596 NULL, /* no password canonicalization */
597 pop3_getauth, /* get authorization */
598 pop3_getrange, /* query range of messages */
599 pop3_getsizes, /* we can get a list of sizes */
600 pop3_is_old, /* how do we tell a message is old? */
601 pop3_fetch, /* request given message */
602 NULL, /* no way to fetch body alone */
603 NULL, /* no message trailer */
604 pop3_delete, /* how to delete a message */
605 pop3_logout, /* log out, we're done */
606 FALSE, /* no, we can't re-poll */
609 int doPOP3 (struct query *ctl)
610 /* retrieve messages using POP3 */
613 if (ctl->mailboxes->id) {
614 fprintf(stderr,"Option --remote is not supported with POP3\n");
618 peek_capable = FALSE;
619 return(do_protocol(ctl, &pop3));
621 #endif /* POP3_ENABLE */
623 /* pop3.c ends here */