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 */
33 #endif /* SDPS_ENABLE */
36 static char lastok[POPBUFSIZE+1];
37 #endif /* OPIE_ENABLE */
39 /* these variables are shared between the CAPA probe and the authenticator */
41 flag has_gssapi = FALSE;
42 #endif /* defined(GSSAPI) */
43 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
44 flag has_kerberos = FALSE;
45 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
46 static flag has_cram = FALSE;
49 #endif /* OPIE_ENABLE */
51 static flag has_ssl = FALSE;
52 #endif /* SSL_ENABLE */
57 static tSmbNtlmAuthRequest request;
58 static tSmbNtlmAuthChallenge challenge;
59 static tSmbNtlmAuthResponse response;
62 * NTLM support by Grant Edwards.
64 * Handle MS-Exchange NTLM authentication method. This is the same
65 * as the NTLM auth used by Samba for SMB related services. We just
66 * encode the packets in base64 instead of sending them out via a
69 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
72 static int do_pop3_ntlm(int sock, struct query *ctl)
77 gen_send(sock, "AUTH MSN");
79 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
85 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
87 if (outlevel >= O_DEBUG)
88 dumpSmbNtlmAuthRequest(stdout, &request);
90 memset(msgbuf,0,sizeof msgbuf);
91 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
93 if (outlevel >= O_MONITOR)
94 report(stdout, "POP3> %s\n", msgbuf);
96 strcat(msgbuf,"\r\n");
97 SockWrite (sock, msgbuf, strlen (msgbuf));
99 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
102 len = from64tobits ((unsigned char*)&challenge, msgbuf, sizeof(msgbuf));
104 if (outlevel >= O_DEBUG)
105 dumpSmbNtlmAuthChallenge(stdout, &challenge);
107 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
109 if (outlevel >= O_DEBUG)
110 dumpSmbNtlmAuthResponse(stdout, &response);
112 memset(msgbuf,0,sizeof msgbuf);
113 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
115 if (outlevel >= O_MONITOR)
116 report(stdout, "POP3> %s\n", msgbuf);
118 strcat(msgbuf,"\r\n");
119 SockWrite (sock, msgbuf, strlen (msgbuf));
121 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
124 if (strstr (msgbuf, "OK"))
132 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
134 static int pop3_ok (int sock, char *argbuf)
135 /* parse command response */
138 char buf [POPBUFSIZE+1];
141 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
143 if (*bufp == '+' || *bufp == '-')
148 while (isalpha((unsigned char)*bufp))
154 if (strcmp(buf,"+OK") == 0)
157 strcpy(lastok, bufp);
158 #endif /* OPIE_ENABLE */
161 else if (strncmp(buf,"-ERR", 4) == 0)
163 if (stage == STAGE_FETCH)
165 else if (stage > STAGE_GETAUTH)
168 * We're checking for "lock busy", "unable to lock",
169 * "already locked", "wait a few minutes" etc. here.
170 * This indicates that we have to wait for the server to
171 * unwedge itself before we can poll again.
173 * PS_LOCKBUSY check empirically verified with two recent
174 * versions of the Berkeley popper; QPOP (version 2.2) and
175 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
176 * These are caught by the case-indifferent "lock" check.
177 * The "wait" catches "mail storage services unavailable,
178 * wait a few minutes and try again" on the InterMail server.
180 * If these aren't picked up on correctly, fetchmail will
181 * think there is an authentication failure and wedge the
182 * connection in order to prevent futile polls.
186 else if (strstr(bufp,"lock")
187 || strstr(bufp,"Lock")
188 || strstr(bufp,"LOCK")
189 || strstr(bufp,"wait")
190 /* these are blessed by RFC 2449 */
191 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
193 else if ((strstr(bufp,"Service")
194 || strstr(bufp,"service"))
195 && (strstr(bufp,"unavailable")))
200 * We always want to pass the user lock-busy messages, because
201 * they're red flags. Other stuff (like AUTH failures on non-
202 * RFC1734 servers) only if we're debugging.
204 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
205 report(stderr, "%s\n", bufp);
210 #if POPBUFSIZE > MSGBUFSIZE
211 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
222 static int capa_probe(int sock)
223 /* probe the capabilities of the remote server */
229 #endif /* defined(GSSAPI) */
230 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
231 has_kerberos = FALSE;
232 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
236 #endif /* OPIE_ENABLE */
238 ok = gen_transact(sock, "CAPA");
239 if (ok == PS_SUCCESS)
243 /* determine what authentication methods we have available */
244 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
249 if (strstr(buffer, "STLS"))
251 #endif /* SSL_ENABLE */
253 if (strstr(buffer, "GSSAPI"))
255 #endif /* defined(GSSAPI) */
256 #if defined(KERBEROS_V4)
257 if (strstr(buffer, "KERBEROS_V4"))
259 #endif /* defined(KERBEROS_V4) */
261 if (strstr(buffer, "X-OTP"))
263 #endif /* OPIE_ENABLE */
264 if (strstr(buffer, "CRAM-MD5"))
271 static void set_peek_capable(struct query *ctl)
273 /* we're peek-capable means that the use of TOP is enabled,
274 * see pop3_fetch for details - short story, we can use TOP if
275 * we have a means of reliably tracking which mail we need to
276 * refetch should the connection abort in the middle.
277 * fetchall forces RETR, as does keep without UIDL */
278 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
281 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
282 /* apply for connection authorization */
289 #endif /* OPIE_ENABLE */
291 flag did_stls = FALSE;
292 #endif /* SSL_ENABLE */
296 #endif /* defined(GSSAPI) */
297 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
298 has_kerberos = FALSE;
299 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
303 #endif /* OPIE_ENABLE */
306 #endif /* SSL_ENABLE */
308 if (ctl->server.authenticate == A_SSH) {
314 * This needs to catch both demon.co.uk and demon.net.
315 * If we see either, and we're in multidrop mode, try to use
316 * the SDPS *ENV extension.
318 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
319 ctl->server.sdps = TRUE;
320 #endif /* SDPS_ENABLE */
322 /* MSN servers require the use of NTLM (MSN) authentication */
323 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
324 ctl->server.authenticate == A_NTLM)
326 if (!do_pop3_ntlm(sock, ctl))
337 switch (ctl->server.protocol) {
340 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
341 if (strstr(ctl->remotename, "@compuserve.com"))
343 /* AUTH command should return a list of available mechanisms */
344 if (gen_transact(sock, "AUTH") == 0)
347 flag has_rpa = FALSE;
349 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
353 if (strncasecmp(buffer, "rpa", 3) == 0)
356 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
357 ctl->password, sock))
363 #endif /* RPA_ENABLE */
366 * CAPA command may return a list including available
367 * authentication mechanisms. if it doesn't, no harm done, we
368 * just fall back to a plain login. Note that this code
369 * latches the server's authentication type, so that in daemon mode
370 * the CAPA check only needs to be done once at start of run.
372 * If CAPA fails, then force the authentication method to PASSORD
373 * and repoll immediately.
375 * These authentication methods are blessed by RFC1734,
376 * describing the POP3 AUTHentication command.
378 if ((ctl->server.authenticate == A_ANY) ||
379 (ctl->server.authenticate == A_GSSAPI) ||
380 (ctl->server.authenticate == A_KERBEROS_V4) ||
381 (ctl->server.authenticate == A_OTP) ||
382 (ctl->server.authenticate == A_CRAM_MD5))
384 if ((ok = capa_probe(sock)) != PS_SUCCESS)
385 /* we are in STAGE_GETAUTH! */
386 if (ok == PS_AUTHFAIL ||
387 /* Some servers directly close the socket. However, if we
388 * have already authenticated before, then a previous CAPA
389 * must have succeeded. In that case, treat this as a
390 * genuine socket error and do not change the auth method.
392 (ok == PS_SOCKET && !ctl->wehaveauthed))
394 ctl->server.authenticate = A_PASSWORD;
395 /* repoll immediately */
404 && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
408 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
409 ok = gen_transact(sock, "STLS");
411 /* We use "tls1" instead of ctl->sslproto, as we want STLS,
412 * not other SSL protocols
414 if (ok == PS_SUCCESS &&
415 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
417 if (!ctl->sslproto && !ctl->wehaveauthed)
419 ctl->sslproto = xstrdup("");
420 /* repoll immediately */
424 GT_("SSL connection failed.\n"));
430 * RFC 2595 says this:
432 * "Once TLS has been started, the client MUST discard cached
433 * information about server capabilities and SHOULD re-issue the
434 * CAPABILITY command. This is necessary to protect against
435 * man-in-the-middle attacks which alter the capabilities list prior
436 * to STARTTLS. The server MAY advertise different capabilities
441 #endif /* SSL_ENABLE */
444 * OK, we have an authentication type now.
446 #if defined(KERBEROS_V4)
448 * Servers doing KPOP have to go through a dummy login sequence
449 * rather than doing SASL.
453 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
454 #else /* INET6_ENABLE */
455 ctl->server.port != KPOP_PORT
456 #endif /* INET6_ENABLE */
457 && (ctl->server.authenticate == A_KERBEROS_V4
458 || ctl->server.authenticate == A_KERBEROS_V5
459 || ctl->server.authenticate == A_ANY))
461 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
462 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
465 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
469 (ctl->server.authenticate == A_GSSAPI ||
470 ctl->server.authenticate == A_ANY))
472 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
473 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
476 #endif /* defined(GSSAPI) */
480 (ctl->server.authenticate == A_OTP ||
481 ctl->server.authenticate == A_ANY))
483 ok = do_otp(sock, "AUTH", ctl);
484 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
487 #endif /* OPIE_ENABLE */
489 if (ctl->server.authenticate == A_CRAM_MD5 ||
490 (has_cram && ctl->server.authenticate == A_ANY))
492 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
493 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
497 /* ordinary validation, no one-time password or RPA */
498 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
502 /* see RFC1938: A One-Time Password System */
503 if ((challenge = strstr(lastok, "otp-"))) {
504 char response[OPIE_RESPONSE_MAX+1];
507 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
508 if ((i == -2) && !run.poll_interval) {
509 char secret[OPIE_SECRET_MAX+1];
510 fprintf(stderr, GT_("Secret pass phrase: "));
511 if (opiereadpass(secret, sizeof(secret), 0))
512 i = opiegenerator(challenge, secret, response);
513 memset(secret, 0, sizeof(secret));
521 ok = gen_transact(sock, "PASS %s", response);
524 #endif /* OPIE_ENABLE */
526 strcpy(shroud, ctl->password);
527 ok = gen_transact(sock, "PASS %s", ctl->password);
530 /* this is for servers which claim to support TLS, but actually
532 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
534 ctl->sslproto = xstrdup("");
535 /* repoll immediately */
542 /* build MD5 digest from greeting timestamp + password */
543 /* find start of timestamp */
544 for (start = greeting; *start != 0 && *start != '<'; start++)
548 GT_("Required APOP timestamp not found in greeting\n"));
552 /* find end of timestamp */
553 for (end = start; *end != 0 && *end != '>'; end++)
555 if (*end == 0 || end == start + 1) {
557 GT_("Timestamp syntax error in greeting\n"));
563 /* copy timestamp and password into digestion buffer */
564 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
566 strcat(msg,ctl->password);
568 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
570 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
574 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
575 ok = gen_transact(sock, "RPOP %s", ctl->password);
579 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
585 /* maybe we detected a lock-busy condition? */
586 if (ok == PS_LOCKBUSY)
587 report(stderr, GT_("lock busy! Is another session active?\n"));
592 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
593 * accepted by Matthias Andree.
595 * Rationale: the server must have locked the spool before returning +OK;
596 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
599 * Empirical experience shows some server/OS combinations
600 * may need a brief pause even after any lockfiles on the
601 * server are released, to give the server time to finish
602 * copying back very large mailfolders from the temp-file...
603 * this is only ever an issue with extremely large mailboxes.
605 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
608 set_peek_capable(ctl);
614 /* cut off C string at first POSIX space */
615 static void trim(char *s) {
616 s += strcspn(s, POSIX_space);
620 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
624 char buf [POPBUFSIZE+1];
625 snprintf(buf, sizeof(buf), "TOP %d 1", num);
626 if ((ok = gen_transact(sock, buf )) != 0)
629 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
633 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
636 p += strspn(p, POSIX_space);
637 strlcpy(id, p, idsize);
644 /** Parse the UID response (leading +OK must have been
645 * stripped off) in buf, store the number in gotnum, and store the ID
646 * into the caller-provided buffer "id" of size "idsize".
647 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
648 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
653 /* skip leading blanks ourselves */
654 i = buf + strspn(i, POSIX_space);
656 *gotnum = strtoul(i, &j, 10);
657 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
658 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
661 j += strspn(j, POSIX_space);
662 strlcpy(id, j, idsize);
667 static int pop3_getuidl(int sock, int num , char *id, size_t idsize)
670 char buf [POPBUFSIZE+1];
671 unsigned long gotnum;
673 gen_send(sock, "UIDL %d", num);
674 if ((ok = pop3_ok(sock, buf)) != 0)
676 if ((ok = parseuid(buf, &gotnum, id, idsize)))
679 report(stderr, GT_("Server responded with UID for wrong message.\n"));
685 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
688 unsigned int first_nr, last_nr, try_nr;
693 while (first_nr < last_nr - 1)
697 try_nr = (first_nr + last_nr) / 2;
698 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
700 if ((new = str_in_list(&ctl->oldsaved, id, FALSE)))
702 flag mark = new->val.status.mark;
703 if (mark == UID_DELETED || mark == UID_EXPUNGED)
705 if (outlevel >= O_VERBOSE)
706 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
707 /* just mark it as seen now! */
708 new->val.status.mark = mark = UID_SEEN;
711 /* narrow the search region! */
712 if (mark == UID_UNSEEN)
714 if (outlevel >= O_DEBUG)
715 report(stdout, GT_("%u is unseen\n"), try_nr);
721 /* save the number */
722 new->val.status.num = try_nr;
726 if (outlevel >= O_DEBUG)
727 report(stdout, GT_("%u is unseen\n"), try_nr);
731 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
732 new->val.status.num = try_nr;
735 if (outlevel >= O_DEBUG && last_nr <= count)
736 report(stdout, GT_("%u is first unseen\n"), last_nr);
739 *newp = count - first_nr;
744 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
746 /* This approach tries to get the message headers from the
747 * remote hosts and compares the message-id to the already known
749 * + if the first message containes a new id, all messages on
750 * the server will be new
751 * + if the first is known, try to estimate the last known message
752 * on the server and check. If this works you know the total number
753 * of messages to get.
754 * + Otherwise run a binary search to determine the last known message
756 int ok, nolinear = 0;
757 int first_nr, list_len, try_id, try_nr, add_id;
761 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
764 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
765 /* the first message is unknown -> all messages are new */
770 /* check where we expect the latest known message */
771 list_len = count_list( &ctl->oldsaved );
772 try_id = list_len - first_nr; /* -1 + 1 */
774 if( try_id <= *countp ) {
775 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
778 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
783 if( try_nr != list_len -1 ) {
784 /* some messages inbetween have been deleted... */
788 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
790 for( ; add_id; add_id >>= 1 ) {
792 if( try_id - add_id <= 1 ) {
799 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
801 try_nr = str_nr_in_list(&ctl->oldsaved, id);
808 GT_("Messages inserted into list on server. Cannot handle this.\n"));
813 /* the first try_id messages are known -> copy them to the newsaved list */
814 for( num = first_nr; num < list_len; num++ )
816 struct idlist *new = save_str(&ctl->newsaved,
817 str_from_nr_list(&ctl->oldsaved, num),
819 new->val.status.num = num - first_nr + 1;
823 free_str_list(&ctl->oldsaved);
828 *newp = *countp - try_id;
832 static int pop3_getrange(int sock,
835 int *countp, int *newp, int *bytes)
836 /* get range of messages to be fetched */
839 char buf [POPBUFSIZE+1];
841 /* Ensure that the new list is properly empty */
842 ctl->newsaved = (struct idlist *)NULL;
845 /* Alain Knaff suggests this, but it's not RFC standard */
847 if ((ok = gen_transact(sock, "MBOX %s", folder)))
851 /* get the total message count */
852 gen_send(sock, "STAT");
853 ok = pop3_ok(sock, buf);
855 sscanf(buf,"%d %d", countp, bytes);
860 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
861 * We work as hard as possible to hide this ugliness, but it makes
862 * counting new messages intrinsically quadratic in the worst case.
866 if (*countp > 0 && !ctl->fetchall)
871 /* should we do fast uidl this time? */
872 fastuidl = ctl->fastuidl;
873 if (*countp > 7 && /* linear search is better if there are few mails! */
874 !ctl->flush && /* with flush, it is safer to disable fastuidl */
875 NUM_NONZERO (fastuidl))
880 dofastuidl = ctl->fastuidlcount != 0;
885 if (!ctl->server.uidl) {
886 gen_send(sock, "LAST");
887 ok = pop3_ok(sock, buf);
892 if (sscanf(buf, "%d", &last) == 0)
894 report(stderr, GT_("protocol error\n"));
897 *newp = (*countp - last);
902 return(pop3_fastuidl( sock, ctl, *countp, newp));
903 /* grab the mailbox's UID list */
904 if ((ok = gen_transact(sock, "UIDL")) != 0)
906 /* don't worry, yet! do it the slow way */
907 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
909 report(stderr, GT_("protocol error while fetching UIDLs\n"));
918 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
923 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
925 struct idlist *old, *new;
927 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
928 new->val.status.num = unum;
930 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
932 flag mark = old->val.status.mark;
933 if (mark == UID_DELETED || mark == UID_EXPUNGED)
935 /* XXX FIXME: switch 3 occurrences from
936 * (int)unum or (unsigned int)unum to
937 * remove the cast and use %lu - not now
938 * though, time for new release */
939 if (outlevel >= O_VERBOSE)
940 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
941 /* just mark it as seen now! */
942 old->val.status.mark = mark = UID_SEEN;
944 new->val.status.mark = mark;
945 if (mark == UID_UNSEEN)
948 if (outlevel >= O_DEBUG)
949 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
955 if (outlevel >= O_DEBUG)
956 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
957 /* add it to oldsaved also! In case, we do not
958 * swap the lists (say, due to socket error),
959 * the same mail will not be downloaded again.
961 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
962 old->val.status.num = unum;
973 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
974 /* capture the size of message #first */
977 char buf [POPBUFSIZE+1];
978 unsigned int num, size;
980 for (i = first; i <= last; i++) {
981 gen_send(sock, "LIST %d", i);
982 if ((ok = pop3_ok(sock, buf)) != 0)
984 if (sscanf(buf, "%u %u", &num, &size) == 2) {
986 sizes[i - first] = size;
988 /* warn about possible attempt to induce buffer overrun
990 * we expect server reply message number and requested
991 * message number to match */
992 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
998 static int pop3_getsizes(int sock, int count, int *sizes)
999 /* capture the sizes of all messages */
1003 if ((ok = gen_transact(sock, "LIST")) != 0)
1007 char buf [POPBUFSIZE+1];
1009 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1011 unsigned int num, size;
1015 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1016 if (num > 0 && num <= count)
1017 sizes[num - 1] = size;
1019 /* warn about possible attempt to induce buffer overrun */
1020 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1028 static int pop3_is_old(int sock, struct query *ctl, int num)
1029 /* is the given message old? */
1033 return (num <= last);
1034 else if (dofastuidl)
1041 /* in fast uidl, we manipulate the old list only! */
1043 if ((new = id_find(&ctl->oldsaved, num)))
1045 /* we already have the id! */
1046 return(new->val.status.mark != UID_UNSEEN);
1049 /* get the uidl first! */
1050 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1053 if ((new = str_in_list(&ctl->oldsaved, id, FALSE))) {
1054 /* we already have the id! */
1055 new->val.status.num = num;
1056 return(new->val.status.mark != UID_UNSEEN);
1060 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1061 new->val.status.num = num;
1065 return ((new = id_find(&ctl->newsaved, num)) != NULL &&
1066 new->val.status.mark != UID_UNSEEN);
1071 * We could use this to fetch headers only as we do for IMAP. The trouble
1072 * is that there's no way to fetch the body only. So the following RETR
1073 * would have to re-fetch the header. Enough messages have longer headers
1074 * than bodies to make this a net loss.
1076 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1077 /* request headers of nth message */
1080 char buf[POPBUFSIZE+1];
1082 gen_send(sock, "TOP %d 0", number);
1083 if ((ok = pop3_ok(sock, buf)) != 0)
1086 *lenp = -1; /* we got sizes from the LIST response */
1092 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1093 /* request nth message */
1096 char buf[POPBUFSIZE+1];
1100 * See http://www.demon.net/services/mail/sdps-tech.html
1101 * for a description of what we're parsing here.
1103 if (ctl->server.sdps)
1107 sdps_envfrom = (char *)NULL;
1108 sdps_envto = (char *)NULL;
1109 gen_send(sock, "*ENV %d", number);
1111 if (gen_recv(sock, buf, sizeof(buf)))
1116 switch (linecount) {
1118 /* No need to wrap envelope from address */
1119 sdps_envfrom = xmalloc(strlen(buf)+1);
1120 strcpy(sdps_envfrom,buf);
1123 /* Wrap address with To: <> so nxtaddr() likes it */
1124 sdps_envto = xmalloc(strlen(buf)+7);
1125 sprintf(sdps_envto,"To: <%s>",buf);
1129 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1131 #endif /* SDPS_ENABLE */
1134 * Though the POP RFCs don't document this fact, on almost every
1135 * POP3 server I know of messages are marked "seen" only at the
1136 * time the OK response to a RETR is issued.
1138 * This means we can use TOP to fetch the message without setting its
1139 * seen flag. This is good! It means that if the protocol exchange
1140 * craps out during the message, it will still be marked `unseen' on
1141 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1142 * reported to mark messages seen on a TOP fetch.)
1144 * However...*don't* do this if we're using keep to suppress deletion!
1145 * In that case, marking the seen flag is the only way to prevent the
1146 * message from being re-fetched on subsequent runs.
1148 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1149 * This gives us a workaround for servers like usa.net's that bungle
1150 * TOP. It's pretty harmless because fetchall guarantees that any
1151 * message dropped by an interrupted RETR will be picked up on the
1152 * next poll of the site.
1154 * We take advantage here of the fact that, according to all the
1155 * POP RFCs, "if the number of lines requested by the POP3 client
1156 * is greater than than the number of lines in the body, then the
1157 * POP3 server sends the entire message.").
1159 * The line count passed (99999999) is the maximum value CompuServe will
1160 * accept; it's much lower than the natural value 2147483646 (the maximum
1161 * twos-complement signed 32-bit integer minus 1) */
1163 gen_send(sock, "RETR %d", number);
1165 gen_send(sock, "TOP %d 99999999", number);
1166 if ((ok = pop3_ok(sock, buf)) != 0)
1169 *lenp = -1; /* we got sizes from the LIST response */
1174 static void mark_uid_seen(struct query *ctl, int number)
1175 /* Tell the UID code we've seen this. */
1179 if ((sdp = id_find(&ctl->newsaved, number)))
1180 sdp->val.status.mark = UID_SEEN;
1181 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1182 * (say, due to socket error), the same mail will not be downloaded
1185 if ((sdp = id_find(&ctl->oldsaved, number)))
1186 sdp->val.status.mark = UID_SEEN;
1189 static int pop3_delete(int sock, struct query *ctl, int number)
1190 /* delete a given message */
1193 mark_uid_seen(ctl, number);
1194 /* actually, mark for deletion -- doesn't happen until QUIT time */
1195 ok = gen_transact(sock, "DELE %d", number);
1196 if (ok != PS_SUCCESS)
1198 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1202 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1203 /* mark a given message as seen */
1205 mark_uid_seen(ctl, number);
1209 static int pop3_logout(int sock, struct query *ctl)
1210 /* send logout command */
1216 * We used to do this in case the server marks messages deleted when seen.
1217 * (Yes, this has been reported, in the MercuryP/NLM server.
1218 * It's even legal under RFC 1939 (section 8) as a site policy.)
1219 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1220 * "Running 'fetchmail -F -v' and checking the logs, I found out
1221 * that fetchmail did in fact flush my mailbox properly, but sent
1222 * a RSET just before sending QUIT to log off. This caused the
1223 * POP3 server to undo/forget about the previous DELEs, resetting
1224 * my mailbox to its original (ie. unflushed) state. The
1225 * ~/.fetchids file did get flushed though, so the next time
1226 * fetchmail was run it saw all the old messages as new ones ..."
1229 gen_transact(sock, "RSET");
1230 #endif /* __UNUSED__ */
1232 ok = gen_transact(sock, "QUIT");
1239 static const struct method pop3 =
1241 "POP3", /* Post Office Protocol v3 */
1243 "pop3", /* standard POP3 port */
1244 "pop3s", /* ssl POP3 port */
1245 #else /* INET6_ENABLE */
1246 110, /* standard POP3 port */
1247 995, /* ssl POP3 port */
1248 #endif /* INET6_ENABLE */
1249 FALSE, /* this is not a tagged protocol */
1250 TRUE, /* this uses a message delimiter */
1251 pop3_ok, /* parse command response */
1252 pop3_getauth, /* get authorization */
1253 pop3_getrange, /* query range of messages */
1254 pop3_getsizes, /* we can get a list of sizes */
1255 pop3_getpartialsizes, /* we can get the size of 1 mail */
1256 pop3_is_old, /* how do we tell a message is old? */
1257 pop3_fetch, /* request given message */
1258 NULL, /* no way to fetch body alone */
1259 NULL, /* no message trailer */
1260 pop3_delete, /* how to delete a message */
1261 pop3_mark_seen, /* how to mark a message as seen */
1262 pop3_logout, /* log out, we're done */
1263 FALSE, /* no, we can't re-poll */
1266 int doPOP3 (struct query *ctl)
1267 /* retrieve messages using POP3 */
1270 if (ctl->mailboxes->id) {
1271 fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
1275 set_peek_capable(ctl); /* XXX FIXME: is this needed or do we always
1276 call this from pop3_getauth anyways? */
1277 return(do_protocol(ctl, &pop3));
1279 #endif /* POP3_ENABLE */
1281 /* pop3.c ends here */