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);
619 /* cut off C string at first POSIX space */
620 static void trim(char *s) {
621 s += strcspn(s, POSIX_space);
625 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
629 char buf [POPBUFSIZE+1];
630 snprintf(buf, sizeof(buf), "TOP %d 1", num);
631 if ((ok = gen_transact(sock, buf )) != 0)
634 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
638 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
641 p += strspn(p, POSIX_space);
642 strlcpy(id, p, idsize);
649 /** Parse the UID response (leading +OK must have been
650 * stripped off) in buf, store the number in gotnum, and store the ID
651 * into the caller-provided buffer "id" of size "idsize".
652 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
653 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
658 /* skip leading blanks ourselves */
660 i += strspn(i, POSIX_space);
662 *gotnum = strtoul(i, &j, 10);
663 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
664 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
667 j += strspn(j, POSIX_space);
668 strlcpy(id, j, idsize);
673 /** request UIDL for single message \a num and stuff the result into the
674 * buffer \a id which can hold \a idsize bytes */
675 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
678 char buf [POPBUFSIZE+1];
679 unsigned long gotnum;
681 gen_send(sock, "UIDL %d", num);
682 if ((ok = pop3_ok(sock, buf)) != 0)
684 if ((ok = parseuid(buf, &gotnum, id, idsize)))
687 report(stderr, GT_("Server responded with UID for wrong message.\n"));
693 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
696 unsigned int first_nr, last_nr, try_nr;
701 while (first_nr < last_nr - 1)
705 try_nr = (first_nr + last_nr) / 2;
706 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
708 if ((new = str_in_list(&ctl->oldsaved, id, FALSE)))
710 flag mark = new->val.status.mark;
711 if (mark == UID_DELETED || mark == UID_EXPUNGED)
713 if (outlevel >= O_VERBOSE)
714 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
715 /* just mark it as seen now! */
716 new->val.status.mark = mark = UID_SEEN;
719 /* narrow the search region! */
720 if (mark == UID_UNSEEN)
722 if (outlevel >= O_DEBUG)
723 report(stdout, GT_("%u is unseen\n"), try_nr);
729 /* save the number */
730 new->val.status.num = try_nr;
734 if (outlevel >= O_DEBUG)
735 report(stdout, GT_("%u is unseen\n"), try_nr);
739 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
740 new->val.status.num = try_nr;
743 if (outlevel >= O_DEBUG && last_nr <= count)
744 report(stdout, GT_("%u is first unseen\n"), last_nr);
747 *newp = count - first_nr;
752 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
754 /* This approach tries to get the message headers from the
755 * remote hosts and compares the message-id to the already known
757 * + if the first message containes a new id, all messages on
758 * the server will be new
759 * + if the first is known, try to estimate the last known message
760 * on the server and check. If this works you know the total number
761 * of messages to get.
762 * + Otherwise run a binary search to determine the last known message
764 int ok, nolinear = 0;
765 int first_nr, list_len, try_id, try_nr, add_id;
769 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
772 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
773 /* the first message is unknown -> all messages are new */
778 /* check where we expect the latest known message */
779 list_len = count_list( &ctl->oldsaved );
780 try_id = list_len - first_nr; /* -1 + 1 */
782 if( try_id <= *countp ) {
783 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
786 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
791 if( try_nr != list_len -1 ) {
792 /* some messages inbetween have been deleted... */
796 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
798 for( ; add_id; add_id >>= 1 ) {
800 if( try_id - add_id <= 1 ) {
807 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
809 try_nr = str_nr_in_list(&ctl->oldsaved, id);
816 GT_("Messages inserted into list on server. Cannot handle this.\n"));
821 /* the first try_id messages are known -> copy them to the newsaved list */
822 for( num = first_nr; num < list_len; num++ )
824 struct idlist *new = save_str(&ctl->newsaved,
825 str_from_nr_list(&ctl->oldsaved, num),
827 new->val.status.num = num - first_nr + 1;
831 free_str_list(&ctl->oldsaved);
836 *newp = *countp - try_id;
840 static int pop3_getrange(int sock,
843 int *countp, int *newp, int *bytes)
844 /* get range of messages to be fetched */
847 char buf [POPBUFSIZE+1];
849 /* Ensure that the new list is properly empty */
850 ctl->newsaved = (struct idlist *)NULL;
853 /* Alain Knaff suggests this, but it's not RFC standard */
855 if ((ok = gen_transact(sock, "MBOX %s", folder)))
859 /* get the total message count */
860 gen_send(sock, "STAT");
861 ok = pop3_ok(sock, buf);
863 sscanf(buf,"%d %d", countp, bytes);
868 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
869 * We work as hard as possible to hide this ugliness, but it makes
870 * counting new messages intrinsically quadratic in the worst case.
874 if (*countp > 0 && !ctl->fetchall)
879 /* should we do fast uidl this time? */
880 fastuidl = ctl->fastuidl;
881 if (*countp > 7 && /* linear search is better if there are few mails! */
882 !ctl->flush && /* with flush, it is safer to disable fastuidl */
883 NUM_NONZERO (fastuidl))
888 dofastuidl = ctl->fastuidlcount != 0;
893 if (!ctl->server.uidl) {
894 gen_send(sock, "LAST");
895 ok = pop3_ok(sock, buf);
900 if (sscanf(buf, "%d", &last) == 0)
902 report(stderr, GT_("protocol error\n"));
905 *newp = (*countp - last);
910 return(pop3_fastuidl( sock, ctl, *countp, newp));
911 /* grab the mailbox's UID list */
912 if ((ok = gen_transact(sock, "UIDL")) != 0)
914 /* don't worry, yet! do it the slow way */
915 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
917 report(stderr, GT_("protocol error while fetching UIDLs\n"));
926 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
931 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
933 struct idlist *old, *new;
935 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
936 new->val.status.num = unum;
938 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
940 flag mark = old->val.status.mark;
941 if (mark == UID_DELETED || mark == UID_EXPUNGED)
943 /* XXX FIXME: switch 3 occurrences from
944 * (int)unum or (unsigned int)unum to
945 * remove the cast and use %lu - not now
946 * though, time for new release */
947 if (outlevel >= O_VERBOSE)
948 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
949 /* just mark it as seen now! */
950 old->val.status.mark = mark = UID_SEEN;
952 new->val.status.mark = mark;
953 if (mark == UID_UNSEEN)
956 if (outlevel >= O_DEBUG)
957 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
963 if (outlevel >= O_DEBUG)
964 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
965 /* add it to oldsaved also! In case, we do not
966 * swap the lists (say, due to socket error),
967 * the same mail will not be downloaded again.
969 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
970 old->val.status.num = unum;
982 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
983 /* capture the size of message #first */
986 char buf [POPBUFSIZE+1];
987 unsigned int num, size;
989 for (i = first; i <= last; i++) {
990 gen_send(sock, "LIST %d", i);
991 if ((ok = pop3_ok(sock, buf)) != 0)
993 if (sscanf(buf, "%u %u", &num, &size) == 2) {
995 sizes[i - first] = size;
997 /* warn about possible attempt to induce buffer overrun
999 * we expect server reply message number and requested
1000 * message number to match */
1001 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1007 static int pop3_getsizes(int sock, int count, int *sizes)
1008 /* capture the sizes of all messages */
1012 if ((ok = gen_transact(sock, "LIST")) != 0)
1016 char buf [POPBUFSIZE+1];
1018 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1020 unsigned int num, size;
1024 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1025 if (num > 0 && num <= count)
1026 sizes[num - 1] = size;
1028 /* warn about possible attempt to induce buffer overrun */
1029 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1037 static int pop3_is_old(int sock, struct query *ctl, int num)
1038 /* is the given message old? */
1042 return (num <= last);
1043 else if (dofastuidl)
1050 /* in fast uidl, we manipulate the old list only! */
1052 if ((new = id_find(&ctl->oldsaved, num)))
1054 /* we already have the id! */
1055 return(new->val.status.mark != UID_UNSEEN);
1058 /* get the uidl first! */
1059 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1062 if ((new = str_in_list(&ctl->oldsaved, id, FALSE))) {
1063 /* we already have the id! */
1064 new->val.status.num = num;
1065 return(new->val.status.mark != UID_UNSEEN);
1069 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1070 new->val.status.num = num;
1074 return ((new = id_find(&ctl->newsaved, num)) != NULL &&
1075 new->val.status.mark != UID_UNSEEN);
1080 * We could use this to fetch headers only as we do for IMAP. The trouble
1081 * is that there's no way to fetch the body only. So the following RETR
1082 * would have to re-fetch the header. Enough messages have longer headers
1083 * than bodies to make this a net loss.
1085 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1086 /* request headers of nth message */
1089 char buf[POPBUFSIZE+1];
1091 gen_send(sock, "TOP %d 0", number);
1092 if ((ok = pop3_ok(sock, buf)) != 0)
1095 *lenp = -1; /* we got sizes from the LIST response */
1101 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1102 /* request nth message */
1105 char buf[POPBUFSIZE+1];
1109 * See http://www.demon.net/services/mail/sdps-tech.html
1110 * for a description of what we're parsing here.
1112 if (ctl->server.sdps)
1116 sdps_envfrom = (char *)NULL;
1117 sdps_envto = (char *)NULL;
1118 gen_send(sock, "*ENV %d", number);
1120 if (gen_recv(sock, buf, sizeof(buf)))
1125 switch (linecount) {
1127 /* No need to wrap envelope from address */
1128 sdps_envfrom = xmalloc(strlen(buf)+1);
1129 strcpy(sdps_envfrom,buf);
1132 /* Wrap address with To: <> so nxtaddr() likes it */
1133 sdps_envto = xmalloc(strlen(buf)+7);
1134 sprintf(sdps_envto,"To: <%s>",buf);
1138 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1140 #endif /* SDPS_ENABLE */
1143 * Though the POP RFCs don't document this fact, on almost every
1144 * POP3 server I know of messages are marked "seen" only at the
1145 * time the OK response to a RETR is issued.
1147 * This means we can use TOP to fetch the message without setting its
1148 * seen flag. This is good! It means that if the protocol exchange
1149 * craps out during the message, it will still be marked `unseen' on
1150 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1151 * reported to mark messages seen on a TOP fetch.)
1153 * However...*don't* do this if we're using keep to suppress deletion!
1154 * In that case, marking the seen flag is the only way to prevent the
1155 * message from being re-fetched on subsequent runs.
1157 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1158 * This gives us a workaround for servers like usa.net's that bungle
1159 * TOP. It's pretty harmless because fetchall guarantees that any
1160 * message dropped by an interrupted RETR will be picked up on the
1161 * next poll of the site.
1163 * We take advantage here of the fact that, according to all the
1164 * POP RFCs, "if the number of lines requested by the POP3 client
1165 * is greater than than the number of lines in the body, then the
1166 * POP3 server sends the entire message.").
1168 * The line count passed (99999999) is the maximum value CompuServe will
1169 * accept; it's much lower than the natural value 2147483646 (the maximum
1170 * twos-complement signed 32-bit integer minus 1) */
1172 gen_send(sock, "RETR %d", number);
1174 gen_send(sock, "TOP %d 99999999", number);
1175 if ((ok = pop3_ok(sock, buf)) != 0)
1178 *lenp = -1; /* we got sizes from the LIST response */
1183 static void mark_uid_seen(struct query *ctl, int number)
1184 /* Tell the UID code we've seen this. */
1188 if ((sdp = id_find(&ctl->newsaved, number)))
1189 sdp->val.status.mark = UID_SEEN;
1190 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1191 * (say, due to socket error), the same mail will not be downloaded
1194 if ((sdp = id_find(&ctl->oldsaved, number)))
1195 sdp->val.status.mark = UID_SEEN;
1198 static int pop3_delete(int sock, struct query *ctl, int number)
1199 /* delete a given message */
1202 mark_uid_seen(ctl, number);
1203 /* actually, mark for deletion -- doesn't happen until QUIT time */
1204 ok = gen_transact(sock, "DELE %d", number);
1205 if (ok != PS_SUCCESS)
1207 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1211 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1212 /* mark a given message as seen */
1214 mark_uid_seen(ctl, number);
1218 static int pop3_logout(int sock, struct query *ctl)
1219 /* send logout command */
1225 * We used to do this in case the server marks messages deleted when seen.
1226 * (Yes, this has been reported, in the MercuryP/NLM server.
1227 * It's even legal under RFC 1939 (section 8) as a site policy.)
1228 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1229 * "Running 'fetchmail -F -v' and checking the logs, I found out
1230 * that fetchmail did in fact flush my mailbox properly, but sent
1231 * a RSET just before sending QUIT to log off. This caused the
1232 * POP3 server to undo/forget about the previous DELEs, resetting
1233 * my mailbox to its original (ie. unflushed) state. The
1234 * ~/.fetchids file did get flushed though, so the next time
1235 * fetchmail was run it saw all the old messages as new ones ..."
1238 gen_transact(sock, "RSET");
1239 #endif /* __UNUSED__ */
1241 ok = gen_transact(sock, "QUIT");
1248 static const struct method pop3 =
1250 "POP3", /* Post Office Protocol v3 */
1251 "pop3", /* standard POP3 port */
1252 "pop3s", /* ssl POP3 port */
1253 FALSE, /* this is not a tagged protocol */
1254 TRUE, /* this uses a message delimiter */
1255 pop3_ok, /* parse command response */
1256 pop3_getauth, /* get authorization */
1257 pop3_getrange, /* query range of messages */
1258 pop3_getsizes, /* we can get a list of sizes */
1259 pop3_getpartialsizes, /* we can get the size of 1 mail */
1260 pop3_is_old, /* how do we tell a message is old? */
1261 pop3_fetch, /* request given message */
1262 NULL, /* no way to fetch body alone */
1263 NULL, /* no message trailer */
1264 pop3_delete, /* how to delete a message */
1265 pop3_mark_seen, /* how to mark a message as seen */
1266 NULL, /* no action at end of mailbox */
1267 pop3_logout, /* log out, we're done */
1268 FALSE, /* no, we can't re-poll */
1271 int doPOP3 (struct query *ctl)
1272 /* retrieve messages using POP3 */
1275 if (ctl->mailboxes->id) {
1276 fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
1280 set_peek_capable(ctl); /* XXX FIXME: is this needed or do we always
1281 call this from pop3_getauth anyways? */
1282 return(do_protocol(ctl, &pop3));
1284 #endif /* POP3_ENABLE */
1286 /* pop3.c ends here */