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 if (ctl->server.authenticate == A_SSH) {
322 * This needs to catch both demon.co.uk and demon.net.
323 * If we see either, and we're in multidrop mode, try to use
324 * the SDPS *ENV extension.
326 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
327 ctl->server.sdps = TRUE;
328 #endif /* SDPS_ENABLE */
331 /* MSN servers require the use of NTLM (MSN) authentication */
332 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
333 ctl->server.authenticate == A_MSN)
334 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
335 if (ctl->server.authenticate == A_NTLM)
336 return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
338 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
341 GT_("Required NTLM capability not compiled into fetchmail\n"));
345 switch (ctl->server.protocol) {
348 /* XXX FIXME: AUTH probing (RFC1734) should become global */
349 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
350 if (strstr(ctl->remotename, "@compuserve.com"))
352 /* AUTH command should return a list of available mechanisms */
353 if (gen_transact(sock, "AUTH") == 0)
356 flag has_rpa = FALSE;
358 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
362 if (strncasecmp(buffer, "rpa", 3) == 0)
365 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
366 ctl->password, sock))
372 #endif /* RPA_ENABLE */
375 * CAPA command may return a list including available
376 * authentication mechanisms. if it doesn't, no harm done, we
377 * just fall back to a plain login. Note that this code
378 * latches the server's authentication type, so that in daemon mode
379 * the CAPA check only needs to be done once at start of run.
381 * If CAPA fails, then force the authentication method to PASSORD
382 * and repoll immediately.
384 * These authentication methods are blessed by RFC1734,
385 * describing the POP3 AUTHentication command.
387 if ((ctl->server.authenticate == A_ANY) ||
388 (ctl->server.authenticate == A_GSSAPI) ||
389 (ctl->server.authenticate == A_KERBEROS_V4) ||
390 (ctl->server.authenticate == A_OTP) ||
391 (ctl->server.authenticate == A_CRAM_MD5))
393 if ((ok = capa_probe(sock)) != PS_SUCCESS)
394 /* we are in STAGE_GETAUTH! */
395 if (ok == PS_AUTHFAIL ||
396 /* Some servers directly close the socket. However, if we
397 * have already authenticated before, then a previous CAPA
398 * must have succeeded. In that case, treat this as a
399 * genuine socket error and do not change the auth method.
401 (ok == PS_SOCKET && !ctl->wehaveauthed))
403 ctl->server.authenticate = A_PASSWORD;
404 /* repoll immediately */
413 && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
417 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
418 ok = gen_transact(sock, "STLS");
420 /* We use "tls1" instead of ctl->sslproto, as we want STLS,
421 * not other SSL protocols
423 if (ok == PS_SUCCESS &&
424 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
426 if (!ctl->sslproto && !ctl->wehaveauthed)
428 ctl->sslproto = xstrdup("");
429 /* repoll immediately */
433 GT_("SSL connection failed.\n"));
439 * RFC 2595 says this:
441 * "Once TLS has been started, the client MUST discard cached
442 * information about server capabilities and SHOULD re-issue the
443 * CAPABILITY command. This is necessary to protect against
444 * man-in-the-middle attacks which alter the capabilities list prior
445 * to STARTTLS. The server MAY advertise different capabilities
450 #endif /* SSL_ENABLE */
453 * OK, we have an authentication type now.
455 #if defined(KERBEROS_V4)
457 * Servers doing KPOP have to go through a dummy login sequence
458 * rather than doing SASL.
461 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
462 && (ctl->server.authenticate == A_KERBEROS_V4
463 || ctl->server.authenticate == A_KERBEROS_V5
464 || ctl->server.authenticate == A_ANY))
466 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
467 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
470 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
474 (ctl->server.authenticate == A_GSSAPI ||
475 ctl->server.authenticate == A_ANY))
477 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
478 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
481 #endif /* defined(GSSAPI) */
485 (ctl->server.authenticate == A_OTP ||
486 ctl->server.authenticate == A_ANY))
488 ok = do_otp(sock, "AUTH", ctl);
489 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
492 #endif /* OPIE_ENABLE */
494 if (ctl->server.authenticate == A_CRAM_MD5 ||
495 (has_cram && ctl->server.authenticate == A_ANY))
497 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
498 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
502 /* ordinary validation, no one-time password or RPA */
503 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
507 /* see RFC1938: A One-Time Password System */
508 if ((challenge = strstr(lastok, "otp-"))) {
509 char response[OPIE_RESPONSE_MAX+1];
512 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
513 if ((i == -2) && !run.poll_interval) {
514 char secret[OPIE_SECRET_MAX+1];
515 fprintf(stderr, GT_("Secret pass phrase: "));
516 if (opiereadpass(secret, sizeof(secret), 0))
517 i = opiegenerator(challenge, secret, response);
518 memset(secret, 0, sizeof(secret));
526 ok = gen_transact(sock, "PASS %s", response);
529 #endif /* OPIE_ENABLE */
531 strlcpy(shroud, ctl->password, sizeof(shroud));
532 ok = gen_transact(sock, "PASS %s", ctl->password);
535 /* this is for servers which claim to support TLS, but actually
537 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
539 ctl->sslproto = xstrdup("");
540 /* repoll immediately */
547 /* build MD5 digest from greeting timestamp + password */
548 /* find start of timestamp */
549 for (start = greeting; *start != 0 && *start != '<'; start++)
553 GT_("Required APOP timestamp not found in greeting\n"));
557 /* find end of timestamp */
558 for (end = start; *end != 0 && *end != '>'; end++)
560 if (*end == 0 || end == start + 1) {
562 GT_("Timestamp syntax error in greeting\n"));
568 /* copy timestamp and password into digestion buffer */
569 msg = xmalloc((end-start+1) + strlen(ctl->password) + 1);
571 strcat(msg,ctl->password);
572 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
575 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
579 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
580 ok = gen_transact(sock, "RPOP %s", ctl->password);
584 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
590 /* maybe we detected a lock-busy condition? */
591 if (ok == PS_LOCKBUSY)
592 report(stderr, GT_("lock busy! Is another session active?\n"));
597 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
598 * accepted by Matthias Andree.
600 * Rationale: the server must have locked the spool before returning +OK;
601 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
604 * Empirical experience shows some server/OS combinations
605 * may need a brief pause even after any lockfiles on the
606 * server are released, to give the server time to finish
607 * copying back very large mailfolders from the temp-file...
608 * this is only ever an issue with extremely large mailboxes.
610 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
613 set_peek_capable(ctl);
614 /* comcast's Maillennium POP3/PROXY is full of bugs and truncates
615 * TOP replies after c. 80 kByte, so disable TOP. */
616 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
617 report(stdout, GT_("Warning: Maillennium POP3/PROXY server found, using RETR command.\n"));
625 /* cut off C string at first POSIX space */
626 static void trim(char *s) {
627 s += strcspn(s, POSIX_space);
631 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
635 char buf [POPBUFSIZE+1];
636 snprintf(buf, sizeof(buf), "TOP %d 1", num);
637 if ((ok = gen_transact(sock, buf )) != 0)
640 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
644 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
647 p += strspn(p, POSIX_space);
648 strlcpy(id, p, idsize);
655 /** Parse the UID response (leading +OK must have been
656 * stripped off) in buf, store the number in gotnum, and store the ID
657 * into the caller-provided buffer "id" of size "idsize".
658 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
659 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
664 /* skip leading blanks ourselves */
666 i += strspn(i, POSIX_space);
668 *gotnum = strtoul(i, &j, 10);
669 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
670 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
673 j += strspn(j, POSIX_space);
674 strlcpy(id, j, idsize);
679 /** request UIDL for single message \a num and stuff the result into the
680 * buffer \a id which can hold \a idsize bytes */
681 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
684 char buf [POPBUFSIZE+1];
685 unsigned long gotnum;
687 gen_send(sock, "UIDL %d", num);
688 if ((ok = pop3_ok(sock, buf)) != 0)
690 if ((ok = parseuid(buf, &gotnum, id, idsize)))
693 report(stderr, GT_("Server responded with UID for wrong message.\n"));
699 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
702 unsigned int first_nr, last_nr, try_nr;
707 while (first_nr < last_nr - 1)
711 try_nr = (first_nr + last_nr) / 2;
712 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
714 if ((new = str_in_list(&ctl->oldsaved, id, FALSE)))
716 flag mark = new->val.status.mark;
717 if (mark == UID_DELETED || mark == UID_EXPUNGED)
719 if (outlevel >= O_VERBOSE)
720 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
721 /* just mark it as seen now! */
722 new->val.status.mark = mark = UID_SEEN;
725 /* narrow the search region! */
726 if (mark == UID_UNSEEN)
728 if (outlevel >= O_DEBUG)
729 report(stdout, GT_("%u is unseen\n"), try_nr);
735 /* save the number */
736 new->val.status.num = try_nr;
740 if (outlevel >= O_DEBUG)
741 report(stdout, GT_("%u is unseen\n"), try_nr);
745 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
746 new->val.status.num = try_nr;
749 if (outlevel >= O_DEBUG && last_nr <= count)
750 report(stdout, GT_("%u is first unseen\n"), last_nr);
753 *newp = count - first_nr;
758 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
760 /* This approach tries to get the message headers from the
761 * remote hosts and compares the message-id to the already known
763 * + if the first message containes a new id, all messages on
764 * the server will be new
765 * + if the first is known, try to estimate the last known message
766 * on the server and check. If this works you know the total number
767 * of messages to get.
768 * + Otherwise run a binary search to determine the last known message
770 int ok, nolinear = 0;
771 int first_nr, list_len, try_id, try_nr, add_id;
775 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
778 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
779 /* the first message is unknown -> all messages are new */
784 /* check where we expect the latest known message */
785 list_len = count_list( &ctl->oldsaved );
786 try_id = list_len - first_nr; /* -1 + 1 */
788 if( try_id <= *countp ) {
789 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
792 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
797 if( try_nr != list_len -1 ) {
798 /* some messages inbetween have been deleted... */
802 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
804 for( ; add_id; add_id >>= 1 ) {
806 if( try_id - add_id <= 1 ) {
813 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
815 try_nr = str_nr_in_list(&ctl->oldsaved, id);
822 GT_("Messages inserted into list on server. Cannot handle this.\n"));
827 /* the first try_id messages are known -> copy them to the newsaved list */
828 for( num = first_nr; num < list_len; num++ )
830 struct idlist *new = save_str(&ctl->newsaved,
831 str_from_nr_list(&ctl->oldsaved, num),
833 new->val.status.num = num - first_nr + 1;
837 free_str_list(&ctl->oldsaved);
842 *newp = *countp - try_id;
846 static int pop3_getrange(int sock,
849 int *countp, int *newp, int *bytes)
850 /* get range of messages to be fetched */
853 char buf [POPBUFSIZE+1];
855 /* Ensure that the new list is properly empty */
856 ctl->newsaved = (struct idlist *)NULL;
859 /* Alain Knaff suggests this, but it's not RFC standard */
861 if ((ok = gen_transact(sock, "MBOX %s", folder)))
865 /* get the total message count */
866 gen_send(sock, "STAT");
867 ok = pop3_ok(sock, buf);
869 sscanf(buf,"%d %d", countp, bytes);
874 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
875 * We work as hard as possible to hide this ugliness, but it makes
876 * counting new messages intrinsically quadratic in the worst case.
880 if (*countp > 0 && !ctl->fetchall)
885 /* should we do fast uidl this time? */
886 fastuidl = ctl->fastuidl;
887 if (*countp > 7 && /* linear search is better if there are few mails! */
888 !ctl->flush && /* with flush, it is safer to disable fastuidl */
889 NUM_NONZERO (fastuidl))
894 dofastuidl = ctl->fastuidlcount != 0;
899 if (!ctl->server.uidl) {
900 gen_send(sock, "LAST");
901 ok = pop3_ok(sock, buf);
906 if (sscanf(buf, "%d", &last) == 0)
908 report(stderr, GT_("protocol error\n"));
911 *newp = (*countp - last);
916 return(pop3_fastuidl( sock, ctl, *countp, newp));
917 /* grab the mailbox's UID list */
918 if ((ok = gen_transact(sock, "UIDL")) != 0)
920 /* don't worry, yet! do it the slow way */
921 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
923 report(stderr, GT_("protocol error while fetching UIDLs\n"));
932 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
937 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
939 struct idlist *old, *new;
941 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
942 new->val.status.num = unum;
944 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
946 flag mark = old->val.status.mark;
947 if (mark == UID_DELETED || mark == UID_EXPUNGED)
949 /* XXX FIXME: switch 3 occurrences from
950 * (int)unum or (unsigned int)unum to
951 * remove the cast and use %lu - not now
952 * though, time for new release */
953 if (outlevel >= O_VERBOSE)
954 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
955 /* just mark it as seen now! */
956 old->val.status.mark = mark = UID_SEEN;
958 new->val.status.mark = mark;
959 if (mark == UID_UNSEEN)
962 if (outlevel >= O_DEBUG)
963 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
969 if (outlevel >= O_DEBUG)
970 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
971 /* add it to oldsaved also! In case, we do not
972 * swap the lists (say, due to socket error),
973 * the same mail will not be downloaded again.
975 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
976 old->val.status.num = unum;
988 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
989 /* capture the size of message #first */
992 char buf [POPBUFSIZE+1];
993 unsigned int num, size;
995 for (i = first; i <= last; i++) {
996 gen_send(sock, "LIST %d", i);
997 if ((ok = pop3_ok(sock, buf)) != 0)
999 if (sscanf(buf, "%u %u", &num, &size) == 2) {
1001 sizes[i - first] = size;
1003 /* warn about possible attempt to induce buffer overrun
1005 * we expect server reply message number and requested
1006 * message number to match */
1007 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1013 static int pop3_getsizes(int sock, int count, int *sizes)
1014 /* capture the sizes of all messages */
1018 if ((ok = gen_transact(sock, "LIST")) != 0)
1022 char buf [POPBUFSIZE+1];
1024 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1026 unsigned int num, size;
1030 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1031 if (num > 0 && num <= count)
1032 sizes[num - 1] = size;
1034 /* warn about possible attempt to induce buffer overrun */
1035 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1043 static int pop3_is_old(int sock, struct query *ctl, int num)
1044 /* is the given message old? */
1048 return (num <= last);
1049 else if (dofastuidl)
1056 /* in fast uidl, we manipulate the old list only! */
1058 if ((new = id_find(&ctl->oldsaved, num)))
1060 /* we already have the id! */
1061 return(new->val.status.mark != UID_UNSEEN);
1064 /* get the uidl first! */
1065 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1068 if ((new = str_in_list(&ctl->oldsaved, id, FALSE))) {
1069 /* we already have the id! */
1070 new->val.status.num = num;
1071 return(new->val.status.mark != UID_UNSEEN);
1075 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1076 new->val.status.num = num;
1080 return ((new = id_find(&ctl->newsaved, num)) != NULL &&
1081 new->val.status.mark != UID_UNSEEN);
1086 * We could use this to fetch headers only as we do for IMAP. The trouble
1087 * is that there's no way to fetch the body only. So the following RETR
1088 * would have to re-fetch the header. Enough messages have longer headers
1089 * than bodies to make this a net loss.
1091 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1092 /* request headers of nth message */
1095 char buf[POPBUFSIZE+1];
1097 gen_send(sock, "TOP %d 0", number);
1098 if ((ok = pop3_ok(sock, buf)) != 0)
1101 *lenp = -1; /* we got sizes from the LIST response */
1107 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1108 /* request nth message */
1111 char buf[POPBUFSIZE+1];
1115 * See http://www.demon.net/services/mail/sdps-tech.html
1116 * for a description of what we're parsing here.
1118 if (ctl->server.sdps)
1122 sdps_envfrom = (char *)NULL;
1123 sdps_envto = (char *)NULL;
1124 gen_send(sock, "*ENV %d", number);
1126 if (gen_recv(sock, buf, sizeof(buf)))
1131 switch (linecount) {
1133 /* No need to wrap envelope from address */
1134 sdps_envfrom = xmalloc(strlen(buf)+1);
1135 strcpy(sdps_envfrom,buf);
1138 /* Wrap address with To: <> so nxtaddr() likes it */
1139 sdps_envto = xmalloc(strlen(buf)+7);
1140 sprintf(sdps_envto,"To: <%s>",buf);
1144 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1146 #endif /* SDPS_ENABLE */
1149 * Though the POP RFCs don't document this fact, on almost every
1150 * POP3 server I know of messages are marked "seen" only at the
1151 * time the OK response to a RETR is issued.
1153 * This means we can use TOP to fetch the message without setting its
1154 * seen flag. This is good! It means that if the protocol exchange
1155 * craps out during the message, it will still be marked `unseen' on
1156 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1157 * reported to mark messages seen on a TOP fetch.)
1159 * However...*don't* do this if we're using keep to suppress deletion!
1160 * In that case, marking the seen flag is the only way to prevent the
1161 * message from being re-fetched on subsequent runs.
1163 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1164 * This gives us a workaround for servers like usa.net's that bungle
1165 * TOP. It's pretty harmless because fetchall guarantees that any
1166 * message dropped by an interrupted RETR will be picked up on the
1167 * next poll of the site.
1169 * We take advantage here of the fact that, according to all the
1170 * POP RFCs, "if the number of lines requested by the POP3 client
1171 * is greater than than the number of lines in the body, then the
1172 * POP3 server sends the entire message.").
1174 * The line count passed (99999999) is the maximum value CompuServe will
1175 * accept; it's much lower than the natural value 2147483646 (the maximum
1176 * twos-complement signed 32-bit integer minus 1) */
1178 gen_send(sock, "RETR %d", number);
1180 gen_send(sock, "TOP %d 99999999", number);
1181 if ((ok = pop3_ok(sock, buf)) != 0)
1184 *lenp = -1; /* we got sizes from the LIST response */
1189 static void mark_uid_seen(struct query *ctl, int number)
1190 /* Tell the UID code we've seen this. */
1194 if ((sdp = id_find(&ctl->newsaved, number)))
1195 sdp->val.status.mark = UID_SEEN;
1196 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1197 * (say, due to socket error), the same mail will not be downloaded
1200 if ((sdp = id_find(&ctl->oldsaved, number)))
1201 sdp->val.status.mark = UID_SEEN;
1204 static int pop3_delete(int sock, struct query *ctl, int number)
1205 /* delete a given message */
1208 mark_uid_seen(ctl, number);
1209 /* actually, mark for deletion -- doesn't happen until QUIT time */
1210 ok = gen_transact(sock, "DELE %d", number);
1211 if (ok != PS_SUCCESS)
1213 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1217 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1218 /* mark a given message as seen */
1220 mark_uid_seen(ctl, number);
1224 static int pop3_logout(int sock, struct query *ctl)
1225 /* send logout command */
1231 * We used to do this in case the server marks messages deleted when seen.
1232 * (Yes, this has been reported, in the MercuryP/NLM server.
1233 * It's even legal under RFC 1939 (section 8) as a site policy.)
1234 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1235 * "Running 'fetchmail -F -v' and checking the logs, I found out
1236 * that fetchmail did in fact flush my mailbox properly, but sent
1237 * a RSET just before sending QUIT to log off. This caused the
1238 * POP3 server to undo/forget about the previous DELEs, resetting
1239 * my mailbox to its original (ie. unflushed) state. The
1240 * ~/.fetchids file did get flushed though, so the next time
1241 * fetchmail was run it saw all the old messages as new ones ..."
1244 gen_transact(sock, "RSET");
1245 #endif /* __UNUSED__ */
1247 ok = gen_transact(sock, "QUIT");
1254 static const struct method pop3 =
1256 "POP3", /* Post Office Protocol v3 */
1257 "pop3", /* standard POP3 port */
1258 "pop3s", /* ssl POP3 port */
1259 FALSE, /* this is not a tagged protocol */
1260 TRUE, /* this uses a message delimiter */
1261 pop3_ok, /* parse command response */
1262 pop3_getauth, /* get authorization */
1263 pop3_getrange, /* query range of messages */
1264 pop3_getsizes, /* we can get a list of sizes */
1265 pop3_getpartialsizes, /* we can get the size of 1 mail */
1266 pop3_is_old, /* how do we tell a message is old? */
1267 pop3_fetch, /* request given message */
1268 NULL, /* no way to fetch body alone */
1269 NULL, /* no message trailer */
1270 pop3_delete, /* how to delete a message */
1271 pop3_mark_seen, /* how to mark a message as seen */
1272 NULL, /* no action at end of mailbox */
1273 pop3_logout, /* log out, we're done */
1274 FALSE, /* no, we can't re-poll */
1277 int doPOP3 (struct query *ctl)
1278 /* retrieve messages using POP3 */
1281 if (ctl->mailboxes->id) {
1282 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1286 set_peek_capable(ctl); /* XXX FIXME: is this needed or do we always
1287 call this from pop3_getauth anyways? */
1288 return(do_protocol(ctl, &pop3));
1290 #endif /* POP3_ENABLE */
1292 /* pop3.c ends here */