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)
21 #include "fetchmail.h"
27 #endif /* OPIE_ENABLE */
29 /* global variables: please reinitialize them explicitly for proper
30 * working in daemon mode */
32 /* TODO: session variables to be initialized before server greeting */
34 static char lastok[POPBUFSIZE+1];
35 #endif /* OPIE_ENABLE */
37 /* session variables initialized in capa_probe() or pop3_getauth() */
39 flag has_gssapi = FALSE;
40 #endif /* defined(GSSAPI) */
41 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
42 flag has_kerberos = FALSE;
43 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
44 static flag has_cram = FALSE;
47 #endif /* OPIE_ENABLE */
49 static flag has_ssl = FALSE;
50 #endif /* SSL_ENABLE */
52 /* mailbox variables initialized in pop3_getrange() */
55 /* mail variables initialized in pop3_fetch() */
59 #endif /* SDPS_ENABLE */
65 * NTLM support by Grant Edwards.
67 * Handle MS-Exchange NTLM authentication method. This is the same
68 * as the NTLM auth used by Samba for SMB related services. We just
69 * encode the packets in base64 instead of sending them out via a
72 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
75 static int do_pop3_ntlm(int sock, struct query *ctl,
76 int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
78 tSmbNtlmAuthRequest request;
79 tSmbNtlmAuthChallenge challenge;
80 tSmbNtlmAuthResponse response;
85 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
87 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
93 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
95 if (outlevel >= O_DEBUG)
96 dumpSmbNtlmAuthRequest(stdout, &request);
98 memset(msgbuf,0,sizeof msgbuf);
99 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
101 if (outlevel >= O_MONITOR)
102 report(stdout, "POP3> %s\n", msgbuf);
104 strcat(msgbuf,"\r\n");
105 SockWrite (sock, msgbuf, strlen (msgbuf));
107 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
110 len = from64tobits ((unsigned char*)&challenge, msgbuf, sizeof(msgbuf));
112 if (outlevel >= O_DEBUG)
113 dumpSmbNtlmAuthChallenge(stdout, &challenge);
115 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
117 if (outlevel >= O_DEBUG)
118 dumpSmbNtlmAuthResponse(stdout, &response);
120 memset(msgbuf,0,sizeof msgbuf);
121 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
123 if (outlevel >= O_MONITOR)
124 report(stdout, "POP3> %s\n", msgbuf);
126 strcat(msgbuf,"\r\n");
127 SockWrite (sock, msgbuf, strlen (msgbuf));
129 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
132 if (strstr (msgbuf, "OK"))
140 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
142 static int pop3_ok (int sock, char *argbuf)
143 /* parse command response */
146 char buf [POPBUFSIZE+1];
149 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
151 if (*bufp == '+' || *bufp == '-')
156 while (isalpha((unsigned char)*bufp))
162 if (strcmp(buf,"+OK") == 0)
165 strcpy(lastok, bufp);
166 #endif /* OPIE_ENABLE */
169 else if (strncmp(buf,"-ERR", 4) == 0)
171 if (stage == STAGE_FETCH)
173 else if (stage > STAGE_GETAUTH)
176 * We're checking for "lock busy", "unable to lock",
177 * "already locked", "wait a few minutes" etc. here.
178 * This indicates that we have to wait for the server to
179 * unwedge itself before we can poll again.
181 * PS_LOCKBUSY check empirically verified with two recent
182 * versions of the Berkeley popper; QPOP (version 2.2) and
183 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
184 * These are caught by the case-indifferent "lock" check.
185 * The "wait" catches "mail storage services unavailable,
186 * wait a few minutes and try again" on the InterMail server.
188 * If these aren't picked up on correctly, fetchmail will
189 * think there is an authentication failure and wedge the
190 * connection in order to prevent futile polls.
194 else if (strstr(bufp,"lock")
195 || strstr(bufp,"Lock")
196 || strstr(bufp,"LOCK")
197 || strstr(bufp,"wait")
198 /* these are blessed by RFC 2449 */
199 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
201 else if ((strstr(bufp,"Service")
202 || strstr(bufp,"service"))
203 && (strstr(bufp,"unavailable")))
208 * We always want to pass the user lock-busy messages, because
209 * they're red flags. Other stuff (like AUTH failures on non-
210 * RFC1734 servers) only if we're debugging.
212 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
213 report(stderr, "%s\n", bufp);
218 #if POPBUFSIZE > MSGBUFSIZE
219 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
230 static int capa_probe(int sock)
231 /* probe the capabilities of the remote server */
237 #endif /* defined(GSSAPI) */
238 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
239 has_kerberos = FALSE;
240 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
244 #endif /* OPIE_ENABLE */
246 ok = gen_transact(sock, "CAPA");
247 if (ok == PS_SUCCESS)
251 /* determine what authentication methods we have available */
252 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
257 if (strstr(buffer, "STLS"))
259 #endif /* SSL_ENABLE */
261 if (strstr(buffer, "GSSAPI"))
263 #endif /* defined(GSSAPI) */
264 #if defined(KERBEROS_V4)
265 if (strstr(buffer, "KERBEROS_V4"))
267 #endif /* defined(KERBEROS_V4) */
269 if (strstr(buffer, "X-OTP"))
271 #endif /* OPIE_ENABLE */
272 if (strstr(buffer, "CRAM-MD5"))
279 static void set_peek_capable(struct query *ctl)
281 /* we're peek-capable means that the use of TOP is enabled,
282 * see pop3_fetch for details - short story, we can use TOP if
283 * we have a means of reliably tracking which mail we need to
284 * refetch should the connection abort in the middle.
285 * fetchall forces RETR, as does keep without UIDL */
286 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
289 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
290 /* apply for connection authorization */
297 #endif /* OPIE_ENABLE */
299 flag did_stls = FALSE;
300 #endif /* SSL_ENABLE */
304 #endif /* defined(GSSAPI) */
305 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
306 has_kerberos = FALSE;
307 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
311 #endif /* OPIE_ENABLE */
314 #endif /* SSL_ENABLE */
316 /* Set this up before authentication quits early. */
317 set_peek_capable(ctl);
319 * The "Maillennium POP3/PROXY server" deliberately truncates
320 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
321 * disable TOP. Comcast once spewed marketing babble to the extent
322 * of protecting Outlook -- pretty overzealous to break a protocol
323 * for that that Microsoft could have read, too. Comcast aren't
324 * alone in using this software though.
325 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
326 * (Thanks to Ed Wilts for reminding me of that.)
328 * The warning is printed once per server, until fetchmail exits.
329 * It will be suppressed when --fetchall or other circumstances make
330 * us use RETR anyhow.
334 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
335 if ((ctl->server.workarounds & WKA_TOP) == 0) {
336 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
337 ctl->server.workarounds |= WKA_TOP;
341 if (ctl->server.authenticate == A_SSH) {
347 * This needs to catch both demon.co.uk and demon.net.
348 * If we see either, and we're in multidrop mode, try to use
349 * the SDPS *ENV extension.
351 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
352 ctl->server.sdps = TRUE;
353 #endif /* SDPS_ENABLE */
356 /* MSN servers require the use of NTLM (MSN) authentication */
357 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
358 ctl->server.authenticate == A_MSN)
359 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
360 if (ctl->server.authenticate == A_NTLM)
361 return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
363 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
366 GT_("Required NTLM capability not compiled into fetchmail\n"));
370 switch (ctl->server.protocol) {
373 /* XXX FIXME: AUTH probing (RFC1734) should become global */
374 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
375 if (strstr(ctl->remotename, "@compuserve.com"))
377 /* AUTH command should return a list of available mechanisms */
378 if (gen_transact(sock, "AUTH") == 0)
381 flag has_rpa = FALSE;
383 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
387 if (strncasecmp(buffer, "rpa", 3) == 0)
390 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
391 ctl->password, sock))
397 #endif /* RPA_ENABLE */
400 * CAPA command may return a list including available
401 * authentication mechanisms. if it doesn't, no harm done, we
402 * just fall back to a plain login. Note that this code
403 * latches the server's authentication type, so that in daemon mode
404 * the CAPA check only needs to be done once at start of run.
406 * If CAPA fails, then force the authentication method to PASSORD
407 * and repoll immediately.
409 * These authentication methods are blessed by RFC1734,
410 * describing the POP3 AUTHentication command.
412 if ((ctl->server.authenticate == A_ANY) ||
413 (ctl->server.authenticate == A_GSSAPI) ||
414 (ctl->server.authenticate == A_KERBEROS_V4) ||
415 (ctl->server.authenticate == A_OTP) ||
416 (ctl->server.authenticate == A_CRAM_MD5))
418 if ((ok = capa_probe(sock)) != PS_SUCCESS)
419 /* we are in STAGE_GETAUTH! */
420 if (ok == PS_AUTHFAIL ||
421 /* Some servers directly close the socket. However, if we
422 * have already authenticated before, then a previous CAPA
423 * must have succeeded. In that case, treat this as a
424 * genuine socket error and do not change the auth method.
426 (ok == PS_SOCKET && !ctl->wehaveauthed))
428 ctl->server.authenticate = A_PASSWORD;
429 /* repoll immediately */
438 && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
442 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
443 ok = gen_transact(sock, "STLS");
445 /* We use "tls1" instead of ctl->sslproto, as we want STLS,
446 * not other SSL protocols
448 if (ok == PS_SUCCESS &&
449 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
451 if (!ctl->sslproto && !ctl->wehaveauthed)
453 ctl->sslproto = xstrdup("");
454 /* repoll immediately */
458 GT_("SSL connection failed.\n"));
464 * RFC 2595 says this:
466 * "Once TLS has been started, the client MUST discard cached
467 * information about server capabilities and SHOULD re-issue the
468 * CAPABILITY command. This is necessary to protect against
469 * man-in-the-middle attacks which alter the capabilities list prior
470 * to STARTTLS. The server MAY advertise different capabilities
475 #endif /* SSL_ENABLE */
478 * OK, we have an authentication type now.
480 #if defined(KERBEROS_V4)
482 * Servers doing KPOP have to go through a dummy login sequence
483 * rather than doing SASL.
486 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
487 && (ctl->server.authenticate == A_KERBEROS_V4
488 || ctl->server.authenticate == A_KERBEROS_V5
489 || ctl->server.authenticate == A_ANY))
491 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
492 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
495 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
499 (ctl->server.authenticate == A_GSSAPI ||
500 ctl->server.authenticate == A_ANY))
502 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
503 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
506 #endif /* defined(GSSAPI) */
510 (ctl->server.authenticate == A_OTP ||
511 ctl->server.authenticate == A_ANY))
513 ok = do_otp(sock, "AUTH", ctl);
514 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
517 #endif /* OPIE_ENABLE */
519 if (ctl->server.authenticate == A_CRAM_MD5 ||
520 (has_cram && ctl->server.authenticate == A_ANY))
522 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
523 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
527 /* ordinary validation, no one-time password or RPA */
528 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
532 /* see RFC1938: A One-Time Password System */
533 if ((challenge = strstr(lastok, "otp-"))) {
534 char response[OPIE_RESPONSE_MAX+1];
537 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
538 if ((i == -2) && !run.poll_interval) {
539 char secret[OPIE_SECRET_MAX+1];
540 fprintf(stderr, GT_("Secret pass phrase: "));
541 if (opiereadpass(secret, sizeof(secret), 0))
542 i = opiegenerator(challenge, secret, response);
543 memset(secret, 0, sizeof(secret));
551 ok = gen_transact(sock, "PASS %s", response);
554 #endif /* OPIE_ENABLE */
556 strlcpy(shroud, ctl->password, sizeof(shroud));
557 ok = gen_transact(sock, "PASS %s", ctl->password);
560 /* this is for servers which claim to support TLS, but actually
562 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
564 ctl->sslproto = xstrdup("");
565 /* repoll immediately */
572 /* build MD5 digest from greeting timestamp + password */
573 /* find start of timestamp */
574 for (start = greeting; *start != 0 && *start != '<'; start++)
578 GT_("Required APOP timestamp not found in greeting\n"));
582 /* find end of timestamp */
583 for (end = start; *end != 0 && *end != '>'; end++)
585 if (*end == 0 || end == start + 1) {
587 GT_("Timestamp syntax error in greeting\n"));
593 /* copy timestamp and password into digestion buffer */
594 msg = xmalloc((end-start+1) + strlen(ctl->password) + 1);
596 strcat(msg,ctl->password);
597 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
600 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
604 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
605 ok = gen_transact(sock, "RPOP %s", ctl->password);
609 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
615 /* maybe we detected a lock-busy condition? */
616 if (ok == PS_LOCKBUSY)
617 report(stderr, GT_("lock busy! Is another session active?\n"));
622 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
623 * accepted by Matthias Andree.
625 * Rationale: the server must have locked the spool before returning +OK;
626 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
629 * Empirical experience shows some server/OS combinations
630 * may need a brief pause even after any lockfiles on the
631 * server are released, to give the server time to finish
632 * copying back very large mailfolders from the temp-file...
633 * this is only ever an issue with extremely large mailboxes.
635 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
642 /* cut off C string at first POSIX space */
643 static void trim(char *s) {
644 s += strcspn(s, POSIX_space);
648 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
652 char buf [POPBUFSIZE+1];
653 snprintf(buf, sizeof(buf), "TOP %d 1", num);
654 if ((ok = gen_transact(sock, buf )) != 0)
657 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
661 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
664 p += strspn(p, POSIX_space);
665 strlcpy(id, p, idsize);
672 /** Parse the UID response (leading +OK must have been
673 * stripped off) in buf, store the number in gotnum, and store the ID
674 * into the caller-provided buffer "id" of size "idsize".
675 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
676 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
681 /* skip leading blanks ourselves */
683 i += strspn(i, POSIX_space);
685 *gotnum = strtoul(i, &j, 10);
686 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
687 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
690 j += strspn(j, POSIX_space);
691 strlcpy(id, j, idsize);
696 /** request UIDL for single message \a num and stuff the result into the
697 * buffer \a id which can hold \a idsize bytes */
698 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
701 char buf [POPBUFSIZE+1];
702 unsigned long gotnum;
704 gen_send(sock, "UIDL %d", num);
705 if ((ok = pop3_ok(sock, buf)) != 0)
707 if ((ok = parseuid(buf, &gotnum, id, idsize)))
710 report(stderr, GT_("Server responded with UID for wrong message.\n"));
716 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
719 unsigned int first_nr, last_nr, try_nr;
724 while (first_nr < last_nr - 1)
728 try_nr = (first_nr + last_nr) / 2;
729 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
731 if ((new = str_in_list(&ctl->oldsaved, id, FALSE)))
733 flag mark = new->val.status.mark;
734 if (mark == UID_DELETED || mark == UID_EXPUNGED)
736 if (outlevel >= O_VERBOSE)
737 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
738 /* just mark it as seen now! */
739 new->val.status.mark = mark = UID_SEEN;
742 /* narrow the search region! */
743 if (mark == UID_UNSEEN)
745 if (outlevel >= O_DEBUG)
746 report(stdout, GT_("%u is unseen\n"), try_nr);
752 /* save the number */
753 new->val.status.num = try_nr;
757 if (outlevel >= O_DEBUG)
758 report(stdout, GT_("%u is unseen\n"), try_nr);
762 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
763 new->val.status.num = try_nr;
766 if (outlevel >= O_DEBUG && last_nr <= count)
767 report(stdout, GT_("%u is first unseen\n"), last_nr);
770 *newp = count - first_nr;
775 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
777 /* This approach tries to get the message headers from the
778 * remote hosts and compares the message-id to the already known
780 * + if the first message containes a new id, all messages on
781 * the server will be new
782 * + if the first is known, try to estimate the last known message
783 * on the server and check. If this works you know the total number
784 * of messages to get.
785 * + Otherwise run a binary search to determine the last known message
787 int ok, nolinear = 0;
788 int first_nr, list_len, try_id, try_nr, add_id;
792 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
795 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
796 /* the first message is unknown -> all messages are new */
801 /* check where we expect the latest known message */
802 list_len = count_list( &ctl->oldsaved );
803 try_id = list_len - first_nr; /* -1 + 1 */
805 if( try_id <= *countp ) {
806 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
809 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
814 if( try_nr != list_len -1 ) {
815 /* some messages inbetween have been deleted... */
819 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
821 for( ; add_id; add_id >>= 1 ) {
823 if( try_id - add_id <= 1 ) {
830 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
832 try_nr = str_nr_in_list(&ctl->oldsaved, id);
839 GT_("Messages inserted into list on server. Cannot handle this.\n"));
844 /* the first try_id messages are known -> copy them to the newsaved list */
845 for( num = first_nr; num < list_len; num++ )
847 struct idlist *new = save_str(&ctl->newsaved,
848 str_from_nr_list(&ctl->oldsaved, num),
850 new->val.status.num = num - first_nr + 1;
854 free_str_list(&ctl->oldsaved);
859 *newp = *countp - try_id;
863 static int pop3_getrange(int sock,
866 int *countp, int *newp, int *bytes)
867 /* get range of messages to be fetched */
870 char buf [POPBUFSIZE+1];
872 /* Ensure that the new list is properly empty */
873 ctl->newsaved = (struct idlist *)NULL;
876 /* Alain Knaff suggests this, but it's not RFC standard */
878 if ((ok = gen_transact(sock, "MBOX %s", folder)))
882 /* get the total message count */
883 gen_send(sock, "STAT");
884 ok = pop3_ok(sock, buf);
886 sscanf(buf,"%d %d", countp, bytes);
891 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
892 * We work as hard as possible to hide this ugliness, but it makes
893 * counting new messages intrinsically quadratic in the worst case.
897 if (*countp > 0 && !ctl->fetchall)
902 /* should we do fast uidl this time? */
903 fastuidl = ctl->fastuidl;
904 if (*countp > 7 && /* linear search is better if there are few mails! */
905 !ctl->flush && /* with flush, it is safer to disable fastuidl */
906 NUM_NONZERO (fastuidl))
911 dofastuidl = ctl->fastuidlcount != 0;
916 if (!ctl->server.uidl) {
917 gen_send(sock, "LAST");
918 ok = pop3_ok(sock, buf);
923 if (sscanf(buf, "%d", &last) == 0)
925 report(stderr, GT_("protocol error\n"));
928 *newp = (*countp - last);
933 return(pop3_fastuidl( sock, ctl, *countp, newp));
934 /* grab the mailbox's UID list */
935 if ((ok = gen_transact(sock, "UIDL")) != 0)
937 /* don't worry, yet! do it the slow way */
938 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
940 report(stderr, GT_("protocol error while fetching UIDLs\n"));
949 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
954 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
956 struct idlist *old, *new;
958 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
959 new->val.status.num = unum;
961 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
963 flag mark = old->val.status.mark;
964 if (mark == UID_DELETED || mark == UID_EXPUNGED)
966 /* XXX FIXME: switch 3 occurrences from
967 * (int)unum or (unsigned int)unum to
968 * remove the cast and use %lu - not now
969 * though, time for new release */
970 if (outlevel >= O_VERBOSE)
971 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
972 /* just mark it as seen now! */
973 old->val.status.mark = mark = UID_SEEN;
975 new->val.status.mark = mark;
976 if (mark == UID_UNSEEN)
979 if (outlevel >= O_DEBUG)
980 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
986 if (outlevel >= O_DEBUG)
987 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
988 /* add it to oldsaved also! In case, we do not
989 * swap the lists (say, due to socket error),
990 * the same mail will not be downloaded again.
992 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
993 old->val.status.num = unum;
1005 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1006 /* capture the size of message #first */
1009 char buf [POPBUFSIZE+1];
1010 unsigned int num, size;
1012 for (i = first; i <= last; i++) {
1013 gen_send(sock, "LIST %d", i);
1014 if ((ok = pop3_ok(sock, buf)) != 0)
1016 if (sscanf(buf, "%u %u", &num, &size) == 2) {
1018 sizes[i - first] = size;
1020 /* warn about possible attempt to induce buffer overrun
1022 * we expect server reply message number and requested
1023 * message number to match */
1024 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1030 static int pop3_getsizes(int sock, int count, int *sizes)
1031 /* capture the sizes of all messages */
1035 if ((ok = gen_transact(sock, "LIST")) != 0)
1039 char buf [POPBUFSIZE+1];
1041 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1043 unsigned int num, size;
1047 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1048 if (num > 0 && num <= count)
1049 sizes[num - 1] = size;
1051 /* warn about possible attempt to induce buffer overrun */
1052 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1060 static int pop3_is_old(int sock, struct query *ctl, int num)
1061 /* is the given message old? */
1065 return (num <= last);
1066 else if (dofastuidl)
1073 /* in fast uidl, we manipulate the old list only! */
1075 if ((new = id_find(&ctl->oldsaved, num)))
1077 /* we already have the id! */
1078 return(new->val.status.mark != UID_UNSEEN);
1081 /* get the uidl first! */
1082 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1085 if ((new = str_in_list(&ctl->oldsaved, id, FALSE))) {
1086 /* we already have the id! */
1087 new->val.status.num = num;
1088 return(new->val.status.mark != UID_UNSEEN);
1092 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1093 new->val.status.num = num;
1097 return ((new = id_find(&ctl->newsaved, num)) != NULL &&
1098 new->val.status.mark != UID_UNSEEN);
1103 * We could use this to fetch headers only as we do for IMAP. The trouble
1104 * is that there's no way to fetch the body only. So the following RETR
1105 * would have to re-fetch the header. Enough messages have longer headers
1106 * than bodies to make this a net loss.
1108 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1109 /* request headers of nth message */
1112 char buf[POPBUFSIZE+1];
1114 gen_send(sock, "TOP %d 0", number);
1115 if ((ok = pop3_ok(sock, buf)) != 0)
1118 *lenp = -1; /* we got sizes from the LIST response */
1124 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1125 /* request nth message */
1128 char buf[POPBUFSIZE+1];
1132 * See http://www.demon.net/services/mail/sdps-tech.html
1133 * for a description of what we're parsing here.
1135 if (ctl->server.sdps)
1139 sdps_envfrom = (char *)NULL;
1140 sdps_envto = (char *)NULL;
1141 gen_send(sock, "*ENV %d", number);
1143 if (gen_recv(sock, buf, sizeof(buf)))
1148 switch (linecount) {
1150 /* No need to wrap envelope from address */
1151 sdps_envfrom = xmalloc(strlen(buf)+1);
1152 strcpy(sdps_envfrom,buf);
1155 /* Wrap address with To: <> so nxtaddr() likes it */
1156 sdps_envto = xmalloc(strlen(buf)+7);
1157 sprintf(sdps_envto,"To: <%s>",buf);
1161 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1163 #endif /* SDPS_ENABLE */
1166 * Though the POP RFCs don't document this fact, on almost every
1167 * POP3 server I know of messages are marked "seen" only at the
1168 * time the OK response to a RETR is issued.
1170 * This means we can use TOP to fetch the message without setting its
1171 * seen flag. This is good! It means that if the protocol exchange
1172 * craps out during the message, it will still be marked `unseen' on
1173 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1174 * reported to mark messages seen on a TOP fetch.)
1176 * However...*don't* do this if we're using keep to suppress deletion!
1177 * In that case, marking the seen flag is the only way to prevent the
1178 * message from being re-fetched on subsequent runs.
1180 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1181 * This gives us a workaround for servers like usa.net's that bungle
1182 * TOP. It's pretty harmless because fetchall guarantees that any
1183 * message dropped by an interrupted RETR will be picked up on the
1184 * next poll of the site.
1186 * We take advantage here of the fact that, according to all the
1187 * POP RFCs, "if the number of lines requested by the POP3 client
1188 * is greater than than the number of lines in the body, then the
1189 * POP3 server sends the entire message.").
1191 * The line count passed (99999999) is the maximum value CompuServe will
1192 * accept; it's much lower than the natural value 2147483646 (the maximum
1193 * twos-complement signed 32-bit integer minus 1) */
1195 gen_send(sock, "RETR %d", number);
1197 gen_send(sock, "TOP %d 99999999", number);
1198 if ((ok = pop3_ok(sock, buf)) != 0)
1201 *lenp = -1; /* we got sizes from the LIST response */
1206 static void mark_uid_seen(struct query *ctl, int number)
1207 /* Tell the UID code we've seen this. */
1211 if ((sdp = id_find(&ctl->newsaved, number)))
1212 sdp->val.status.mark = UID_SEEN;
1213 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1214 * (say, due to socket error), the same mail will not be downloaded
1217 if ((sdp = id_find(&ctl->oldsaved, number)))
1218 sdp->val.status.mark = UID_SEEN;
1221 static int pop3_delete(int sock, struct query *ctl, int number)
1222 /* delete a given message */
1225 mark_uid_seen(ctl, number);
1226 /* actually, mark for deletion -- doesn't happen until QUIT time */
1227 ok = gen_transact(sock, "DELE %d", number);
1228 if (ok != PS_SUCCESS)
1230 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1234 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1235 /* mark a given message as seen */
1237 mark_uid_seen(ctl, number);
1241 static int pop3_logout(int sock, struct query *ctl)
1242 /* send logout command */
1248 * We used to do this in case the server marks messages deleted when seen.
1249 * (Yes, this has been reported, in the MercuryP/NLM server.
1250 * It's even legal under RFC 1939 (section 8) as a site policy.)
1251 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1252 * "Running 'fetchmail -F -v' and checking the logs, I found out
1253 * that fetchmail did in fact flush my mailbox properly, but sent
1254 * a RSET just before sending QUIT to log off. This caused the
1255 * POP3 server to undo/forget about the previous DELEs, resetting
1256 * my mailbox to its original (ie. unflushed) state. The
1257 * ~/.fetchids file did get flushed though, so the next time
1258 * fetchmail was run it saw all the old messages as new ones ..."
1261 gen_transact(sock, "RSET");
1262 #endif /* __UNUSED__ */
1264 ok = gen_transact(sock, "QUIT");
1271 static const struct method pop3 =
1273 "POP3", /* Post Office Protocol v3 */
1274 "pop3", /* standard POP3 port */
1275 "pop3s", /* ssl POP3 port */
1276 FALSE, /* this is not a tagged protocol */
1277 TRUE, /* this uses a message delimiter */
1278 pop3_ok, /* parse command response */
1279 pop3_getauth, /* get authorization */
1280 pop3_getrange, /* query range of messages */
1281 pop3_getsizes, /* we can get a list of sizes */
1282 pop3_getpartialsizes, /* we can get the size of 1 mail */
1283 pop3_is_old, /* how do we tell a message is old? */
1284 pop3_fetch, /* request given message */
1285 NULL, /* no way to fetch body alone */
1286 NULL, /* no message trailer */
1287 pop3_delete, /* how to delete a message */
1288 pop3_mark_seen, /* how to mark a message as seen */
1289 NULL, /* no action at end of mailbox */
1290 pop3_logout, /* log out, we're done */
1291 FALSE, /* no, we can't re-poll */
1294 int doPOP3 (struct query *ctl)
1295 /* retrieve messages using POP3 */
1298 if (ctl->mailboxes->id) {
1299 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1304 return(do_protocol(ctl, &pop3));
1306 #endif /* POP3_ENABLE */
1308 /* pop3.c ends here */