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)
20 #include "fetchmail.h"
26 #endif /* OPIE_ENABLE */
28 #ifndef strstr /* glibc-2.1 declares this as a macro */
29 extern char *strstr(); /* needed on sysV68 R3V7.1. */
36 #endif /* SDPS_ENABLE */
39 static char lastok[POPBUFSIZE+1];
40 #endif /* OPIE_ENABLE */
42 /* these variables are shared between the CAPA probe and the authenticator */
44 flag has_gssapi = FALSE;
45 #endif /* defined(GSSAPI) */
46 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
47 flag has_kerberos = FALSE;
48 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
49 flag has_cram = FALSE;
52 #endif /* OPIE_ENABLE */
55 #endif /* SSL_ENABLE */
60 static tSmbNtlmAuthRequest request;
61 static tSmbNtlmAuthChallenge challenge;
62 static tSmbNtlmAuthResponse response;
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)
80 gen_send(sock, "AUTH MSN");
82 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
88 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
90 if (outlevel >= O_DEBUG)
91 dumpSmbNtlmAuthRequest(stdout, &request);
93 memset(msgbuf,0,sizeof msgbuf);
94 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
96 if (outlevel >= O_MONITOR)
97 report(stdout, "POP3> %s\n", msgbuf);
99 strcat(msgbuf,"\r\n");
100 SockWrite (sock, msgbuf, strlen (msgbuf));
102 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
105 len = from64tobits ((unsigned char*)&challenge, msgbuf, sizeof(msgbuf));
107 if (outlevel >= O_DEBUG)
108 dumpSmbNtlmAuthChallenge(stdout, &challenge);
110 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
112 if (outlevel >= O_DEBUG)
113 dumpSmbNtlmAuthResponse(stdout, &response);
115 memset(msgbuf,0,sizeof msgbuf);
116 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
118 if (outlevel >= O_MONITOR)
119 report(stdout, "POP3> %s\n", msgbuf);
121 strcat(msgbuf,"\r\n");
122 SockWrite (sock, msgbuf, strlen (msgbuf));
124 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
127 if (strstr (msgbuf, "OK"))
135 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
137 static int pop3_ok (int sock, char *argbuf)
138 /* parse command response */
141 char buf [POPBUFSIZE+1];
144 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
146 if (*bufp == '+' || *bufp == '-')
151 while (isalpha(*bufp))
157 if (strcmp(buf,"+OK") == 0)
160 strcpy(lastok, bufp);
161 #endif /* OPIE_ENABLE */
164 else if (strncmp(buf,"-ERR", 4) == 0)
166 if (stage == STAGE_FETCH)
168 else if (stage > STAGE_GETAUTH)
171 * We're checking for "lock busy", "unable to lock",
172 * "already locked", "wait a few minutes" etc. here.
173 * This indicates that we have to wait for the server to
174 * unwedge itself before we can poll again.
176 * PS_LOCKBUSY check empirically verified with two recent
177 * versions of the Berkeley popper; QPOP (version 2.2) and
178 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
179 * These are caught by the case-indifferent "lock" check.
180 * The "wait" catches "mail storage services unavailable,
181 * wait a few minutes and try again" on the InterMail server.
183 * If these aren't picked up on correctly, fetchmail will
184 * think there is an authentication failure and wedge the
185 * connection in order to prevent futile polls.
189 else if (strstr(bufp,"lock")
190 || strstr(bufp,"Lock")
191 || strstr(bufp,"LOCK")
192 || strstr(bufp,"wait")
193 /* these are blessed by RFC 2449 */
194 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
196 else if ((strstr(bufp,"Service")
197 || strstr(bufp,"service"))
198 && (strstr(bufp,"unavailable")))
203 * We always want to pass the user lock-busy messages, because
204 * they're red flags. Other stuff (like AUTH failures on non-
205 * RFC1734 servers) only if we're debugging.
207 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
208 report(stderr, "%s\n", bufp);
222 static int capa_probe(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 int pop3_getauth(int sock, struct query *ctl, char *greeting)
272 /* apply for connection authorization */
279 #endif /* OPIE_ENABLE */
281 flag did_stls = FALSE;
282 #endif /* SSL_ENABLE */
286 #endif /* defined(GSSAPI) */
287 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
288 has_kerberos = FALSE;
289 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
293 #endif /* OPIE_ENABLE */
296 #endif /* SSL_ENABLE */
298 if (ctl->server.authenticate == A_SSH) {
304 * This needs to catch both demon.co.uk and demon.net.
305 * If we see either, and we're in multidrop mode, try to use
306 * the SDPS *ENV extension.
308 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
309 ctl->server.sdps = TRUE;
310 #endif /* SDPS_ENABLE */
312 /* MSN servers require the use of NTLM (MSN) authentication */
313 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
314 ctl->server.authenticate == A_NTLM)
316 if (!do_pop3_ntlm(sock, ctl))
327 switch (ctl->server.protocol) {
330 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
331 if (strstr(ctl->remotename, "@compuserve.com"))
333 /* AUTH command should return a list of available mechanisms */
334 if (gen_transact(sock, "AUTH") == 0)
337 flag has_rpa = FALSE;
339 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
343 if (strncasecmp(buffer, "rpa", 3) == 0)
346 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
347 ctl->password, sock))
353 #endif /* RPA_ENABLE */
356 * CAPA command may return a list including available
357 * authentication mechanisms. if it doesn't, no harm done, we
358 * just fall back to a plain login. Note that this code
359 * latches the server's authentication type, so that in daemon mode
360 * the CAPA check only needs to be done once at start of run.
362 * If CAPA fails, then force the authentication method to PASSORD
363 * and repoll immediately.
365 * These authentication methods are blessed by RFC1734,
366 * describing the POP3 AUTHentication command.
368 if (ctl->server.authenticate == A_ANY)
370 if ((ok = capa_probe(sock)) != PS_SUCCESS)
371 /* we are in STAGE_GETAUTH! */
372 if (ok == PS_AUTHFAIL ||
373 /* Some servers directly close the socket. However, if we
374 * have already authenticated before, then a previous CAPA
375 * must have succeeded. In that case, treat this as a
376 * genuine socket error and do not change the auth method.
378 (ok == PS_SOCKET && !ctl->wehaveauthed))
380 ctl->server.authenticate = A_PASSWORD;
381 /* repoll immediately */
390 && (!ctl->sslproto || !strcmp(ctl->sslproto,"tls1")))
394 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
395 ok = gen_transact(sock, "STLS");
397 /* We use "tls1" instead of ctl->sslproto, as we want STLS,
398 * not other SSL protocols
400 if (ok == PS_SUCCESS &&
401 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
403 if (!ctl->sslproto && !ctl->wehaveauthed)
405 ctl->sslproto = xstrdup("");
406 /* repoll immediately */
410 GT_("SSL connection failed.\n"));
416 * RFC 2595 says this:
418 * "Once TLS has been started, the client MUST discard cached
419 * information about server capabilities and SHOULD re-issue the
420 * CAPABILITY command. This is necessary to protect against
421 * man-in-the-middle attacks which alter the capabilities list prior
422 * to STARTTLS. The server MAY advertise different capabilities
427 #endif /* SSL_ENABLE */
430 * OK, we have an authentication type now.
432 #if defined(KERBEROS_V4)
434 * Servers doing KPOP have to go through a dummy login sequence
435 * rather than doing SASL.
439 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
440 #else /* INET6_ENABLE */
441 ctl->server.port != KPOP_PORT
442 #endif /* INET6_ENABLE */
443 && (ctl->server.authenticate == A_KERBEROS_V4
444 || ctl->server.authenticate == A_KERBEROS_V5
445 || ctl->server.authenticate == A_ANY))
447 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
448 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
451 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
455 (ctl->server.authenticate == A_GSSAPI ||
456 ctl->server.authenticate == A_ANY))
458 ok = do_gssauth(sock,"AUTH",ctl->server.truename,ctl->remotename);
459 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
462 #endif /* defined(GSSAPI) */
466 (ctl->server.authenticate == A_OTP ||
467 ctl->server.authenticate == A_ANY))
469 ok = do_otp(sock, "AUTH", ctl);
470 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
473 #endif /* OPIE_ENABLE */
475 if (ctl->server.authenticate == A_CRAM_MD5 ||
476 (has_cram && ctl->server.authenticate == A_ANY))
478 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
479 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
483 /* ordinary validation, no one-time password or RPA */
484 gen_transact(sock, "USER %s", ctl->remotename);
487 /* see RFC1938: A One-Time Password System */
488 if (challenge = strstr(lastok, "otp-")) {
489 char response[OPIE_RESPONSE_MAX+1];
492 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
493 if ((i == -2) && !run.poll_interval) {
494 char secret[OPIE_SECRET_MAX+1];
495 fprintf(stderr, GT_("Secret pass phrase: "));
496 if (opiereadpass(secret, sizeof(secret), 0))
497 i = opiegenerator(challenge, secret, response);
498 memset(secret, 0, sizeof(secret));
506 ok = gen_transact(sock, "PASS %s", response);
509 #endif /* OPIE_ENABLE */
511 strcpy(shroud, ctl->password);
512 ok = gen_transact(sock, "PASS %s", ctl->password);
515 /* this is for servers which claim to support TLS, but actually
517 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
519 ctl->sslproto = xstrdup("");
520 /* repoll immediately */
527 /* build MD5 digest from greeting timestamp + password */
528 /* find start of timestamp */
529 for (start = greeting; *start != 0 && *start != '<'; start++)
533 GT_("Required APOP timestamp not found in greeting\n"));
537 /* find end of timestamp */
538 for (end = start; *end != 0 && *end != '>'; end++)
540 if (*end == 0 || end == start + 1) {
542 GT_("Timestamp syntax error in greeting\n"));
548 /* copy timestamp and password into digestion buffer */
549 xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
551 strcat(msg,ctl->password);
553 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
555 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
559 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
560 ok = gen_transact(sock, "RPOP %s", ctl->password);
564 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
570 /* maybe we detected a lock-busy condition? */
571 if (ok == PS_LOCKBUSY)
572 report(stderr, GT_("lock busy! Is another session active?\n"));
578 * Empirical experience shows some server/OS combinations
579 * may need a brief pause even after any lockfiles on the
580 * server are released, to give the server time to finish
581 * copying back very large mailfolders from the temp-file...
582 * this is only ever an issue with extremely large mailboxes.
584 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
586 /* we're peek-capable if use of TOP is enabled */
587 peek_capable = !(ctl->fetchall || ctl->keep);
593 static int pop3_gettopid( int sock, int num , char *id)
597 char buf [POPBUFSIZE+1];
598 sprintf( buf, "TOP %d 1", num );
599 if ((ok = gen_transact(sock, buf )) != 0)
602 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
606 if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
608 /* prevent stack overflows */
610 sscanf( buf+12, "%s", id);
616 static int pop3_getuidl( int sock, int num , char *id)
619 char buf [POPBUFSIZE+1];
620 gen_send(sock, "UIDL %d", num);
621 if ((ok = pop3_ok(sock, buf)) != 0)
623 if (sscanf(buf, "%d %s", &num, id) != 2)
628 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
631 unsigned int first_nr, last_nr, try_nr;
636 while (first_nr < last_nr - 1)
640 try_nr = (first_nr + last_nr) / 2;
641 if( (ok = pop3_getuidl( sock, try_nr, id )) != 0 )
643 if ((new = str_in_list(&ctl->oldsaved, id, FALSE)))
645 flag mark = new->val.status.mark;
646 if (mark == UID_DELETED || mark == UID_EXPUNGED)
648 if (outlevel >= O_VERBOSE)
649 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
650 /* just mark it as seen now! */
651 new->val.status.mark = mark = UID_SEEN;
654 /* narrow the search region! */
655 if (mark == UID_UNSEEN)
657 if (outlevel >= O_DEBUG)
658 report(stdout, GT_("%u is unseen\n"), try_nr);
664 /* save the number */
665 new->val.status.num = try_nr;
669 if (outlevel >= O_DEBUG)
670 report(stdout, GT_("%u is unseen\n"), try_nr);
674 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
675 new->val.status.num = try_nr;
678 if (outlevel >= O_DEBUG && last_nr <= count)
679 report(stdout, GT_("%u is first unseen\n"), last_nr);
682 *newp = count - first_nr;
687 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
689 /* This approach tries to get the message headers from the
690 * remote hosts and compares the message-id to the already known
692 * + if the first message containes a new id, all messages on
693 * the server will be new
694 * + if the first is known, try to estimate the last known message
695 * on the server and check. If this works you know the total number
696 * of messages to get.
697 * + Otherwise run a binary search to determine the last known message
699 int ok, nolinear = 0;
700 int first_nr, list_len, try_id, try_nr, add_id;
704 if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
707 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
708 /* the first message is unknown -> all messages are new */
713 /* check where we expect the latest known message */
714 list_len = count_list( &ctl->oldsaved );
715 try_id = list_len - first_nr; /* -1 + 1 */
717 if( try_id <= *countp ) {
718 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
721 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
726 if( try_nr != list_len -1 ) {
727 /* some messages inbetween have been deleted... */
731 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
733 for( ; add_id; add_id >>= 1 ) {
735 if( try_id - add_id <= 1 ) {
742 if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
744 try_nr = str_nr_in_list(&ctl->oldsaved, id);
751 GT_("Messages inserted into list on server. Cannot handle this.\n"));
756 /* the first try_id messages are known -> copy them to the newsaved list */
757 for( num = first_nr; num < list_len; num++ )
759 struct idlist *new = save_str(&ctl->newsaved,
760 str_from_nr_list(&ctl->oldsaved, num),
762 new->val.status.num = num - first_nr + 1;
766 free_str_list(&ctl->oldsaved);
771 *newp = *countp - try_id;
775 static int pop3_getrange(int sock,
778 int *countp, int *newp, int *bytes)
779 /* get range of messages to be fetched */
782 char buf [POPBUFSIZE+1];
784 /* Ensure that the new list is properly empty */
785 ctl->newsaved = (struct idlist *)NULL;
788 /* Alain Knaff suggests this, but it's not RFC standard */
790 if ((ok = gen_transact(sock, "MBOX %s", folder)))
794 /* get the total message count */
795 gen_send(sock, "STAT");
796 ok = pop3_ok(sock, buf);
798 sscanf(buf,"%d %d", countp, bytes);
803 * Newer, RFC-1725-conformant POP servers may not have the LAST command.
804 * We work as hard as possible to hide this ugliness, but it makes
805 * counting new messages intrinsically quadratic in the worst case.
809 if (*countp > 0 && !ctl->fetchall)
814 /* should we do fast uidl this time? */
815 fastuidl = ctl->fastuidl;
816 if (*countp > 7 && /* linear search is better if there are few mails! */
817 !ctl->flush && /* with flush, it is safer to disable fastuidl */
818 NUM_NONZERO (fastuidl))
823 dofastuidl = ctl->fastuidlcount != 0;
828 if (!ctl->server.uidl) {
829 gen_send(sock, "LAST");
830 ok = pop3_ok(sock, buf);
835 if (sscanf(buf, "%d", &last) == 0)
837 report(stderr, GT_("protocol error\n"));
840 *newp = (*countp - last);
845 return(pop3_fastuidl( sock, ctl, *countp, newp));
846 /* grab the mailbox's UID list */
847 if ((ok = gen_transact(sock, "UIDL")) != 0)
849 /* don't worry, yet! do it the slow way */
850 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
852 report(stderr, GT_("protocol error while fetching UIDLs\n"));
861 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
865 else if (sscanf(buf, "%d %s", &num, id) == 2)
867 struct idlist *old, *new;
869 new = save_str(&ctl->newsaved, id, UID_UNSEEN);
870 new->val.status.num = num;
872 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
874 flag mark = old->val.status.mark;
875 if (mark == UID_DELETED || mark == UID_EXPUNGED)
877 if (outlevel >= O_VERBOSE)
878 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, num);
879 /* just mark it as seen now! */
880 old->val.status.mark = mark = UID_SEEN;
882 new->val.status.mark = mark;
883 if (mark == UID_UNSEEN)
886 if (outlevel >= O_DEBUG)
887 report(stdout, GT_("%u is unseen\n"), num);
893 if (outlevel >= O_DEBUG)
894 report(stdout, GT_("%u is unseen\n"), num);
895 /* add it to oldsaved also! In case, we do not
896 * swap the lists (say, due to socket error),
897 * the same mail will not be downloaded again.
899 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
900 old->val.status.num = num;
911 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
912 /* capture the size of message #first */
915 char buf [POPBUFSIZE+1];
916 unsigned int num, size;
918 for (i = first; i <= last; i++) {
919 gen_send(sock, "LIST %d", i);
920 if ((ok = pop3_ok(sock, buf)) != 0)
922 if (sscanf(buf, "%u %u", &num, &size) == 2) {
924 sizes[i - first] = size;
926 /* warn about possible attempt to induce buffer overrun
928 * we expect server reply message number and requested
929 * message number to match */
930 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
936 static int pop3_getsizes(int sock, int count, int *sizes)
937 /* capture the sizes of all messages */
941 if ((ok = gen_transact(sock, "LIST")) != 0)
945 char buf [POPBUFSIZE+1];
947 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
949 unsigned int num, size;
953 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
954 if (num > 0 && num <= count)
955 sizes[num - 1] = size;
957 /* warn about possible attempt to induce buffer overrun */
958 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
966 static int pop3_is_old(int sock, struct query *ctl, int num)
967 /* is the given message old? */
971 return (num <= last);
979 /* in fast uidl, we manipulate the old list only! */
981 if ((new = id_find(&ctl->oldsaved, num)))
983 /* we already have the id! */
984 return(new->val.status.mark != UID_UNSEEN);
987 /* get the uidl first! */
988 if (pop3_getuidl(sock, num, id) != PS_SUCCESS)
991 if ((new = str_in_list(&ctl->oldsaved, id, FALSE))) {
992 /* we already have the id! */
993 new->val.status.num = num;
994 return(new->val.status.mark != UID_UNSEEN);
998 new = save_str(&ctl->oldsaved, id, UID_UNSEEN);
999 new->val.status.num = num;
1003 return ((new = id_find(&ctl->newsaved, num)) != NULL &&
1004 new->val.status.mark != UID_UNSEEN);
1009 * We could use this to fetch headers only as we do for IMAP. The trouble
1010 * is that there's no way to fetch the body only. So the following RETR
1011 * would have to re-fetch the header. Enough messages have longer headers
1012 * than bodies to make this a net loss.
1014 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1015 /* request headers of nth message */
1018 char buf[POPBUFSIZE+1];
1020 gen_send(sock, "TOP %d 0", number);
1021 if ((ok = pop3_ok(sock, buf)) != 0)
1024 *lenp = -1; /* we got sizes from the LIST response */
1030 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1031 /* request nth message */
1034 char buf[POPBUFSIZE+1];
1038 * See http://www.demon.net/services/mail/sdps-tech.html
1039 * for a description of what we're parsing here.
1041 if (ctl->server.sdps)
1045 sdps_envfrom = (char *)NULL;
1046 sdps_envto = (char *)NULL;
1047 gen_send(sock, "*ENV %d", number);
1049 if (gen_recv(sock, buf, sizeof(buf)))
1054 switch (linecount) {
1056 /* No need to wrap envelope from address */
1057 sdps_envfrom = xmalloc(strlen(buf)+1);
1058 strcpy(sdps_envfrom,buf);
1061 /* Wrap address with To: <> so nxtaddr() likes it */
1062 sdps_envto = xmalloc(strlen(buf)+7);
1063 sprintf(sdps_envto,"To: <%s>",buf);
1067 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1069 #endif /* SDPS_ENABLE */
1072 * Though the POP RFCs don't document this fact, on almost every
1073 * POP3 server I know of messages are marked "seen" only at the
1074 * time the OK response to a RETR is issued.
1076 * This means we can use TOP to fetch the message without setting its
1077 * seen flag. This is good! It means that if the protocol exchange
1078 * craps out during the message, it will still be marked `unseen' on
1079 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1080 * reported to mark messages seen on a TOP fetch.)
1082 * However...*don't* do this if we're using keep to suppress deletion!
1083 * In that case, marking the seen flag is the only way to prevent the
1084 * message from being re-fetched on subsequent runs.
1086 * Also use RETR if fetchall is on. This gives us a workaround
1087 * for servers like usa.net's that bungle TOP. It's pretty
1088 * harmless because fetchall guarantees that any message dropped
1089 * by an interrupted RETR will be picked up on the next poll of the
1092 * We take advantage here of the fact that, according to all the
1093 * POP RFCs, "if the number of lines requested by the POP3 client
1094 * is greater than than the number of lines in the body, then the
1095 * POP3 server sends the entire message.").
1097 * The line count passed (99999999) is the maximum value CompuServe will
1098 * accept; it's much lower than the natural value 2147483646 (the maximum
1099 * twos-complement signed 32-bit integer minus 1) */
1100 if (ctl->keep || ctl->fetchall)
1101 gen_send(sock, "RETR %d", number);
1103 gen_send(sock, "TOP %d 99999999", number);
1104 if ((ok = pop3_ok(sock, buf)) != 0)
1107 *lenp = -1; /* we got sizes from the LIST response */
1112 static void mark_uid_seen(struct query *ctl, int number)
1113 /* Tell the UID code we've seen this. */
1117 if ((sdp = id_find(&ctl->newsaved, number)))
1118 sdp->val.status.mark = UID_SEEN;
1119 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1120 * (say, due to socket error), the same mail will not be downloaded
1123 if ((sdp = id_find(&ctl->oldsaved, number)))
1124 sdp->val.status.mark = UID_SEEN;
1127 static int pop3_delete(int sock, struct query *ctl, int number)
1128 /* delete a given message */
1131 mark_uid_seen(ctl, number);
1132 /* actually, mark for deletion -- doesn't happen until QUIT time */
1133 ok = gen_transact(sock, "DELE %d", number);
1134 if (ok != PS_SUCCESS)
1136 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1140 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1141 /* mark a given message as seen */
1143 mark_uid_seen(ctl, number);
1147 static int pop3_logout(int sock, struct query *ctl)
1148 /* send logout command */
1154 * We used to do this in case the server marks messages deleted when seen.
1155 * (Yes, this has been reported, in the MercuryP/NLM server.
1156 * It's even legal under RFC 1939 (section 8) as a site policy.)
1157 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1158 * "Running 'fetchmail -F -v' and checking the logs, I found out
1159 * that fetchmail did in fact flush my mailbox properly, but sent
1160 * a RSET just before sending QUIT to log off. This caused the
1161 * POP3 server to undo/forget about the previous DELEs, resetting
1162 * my mailbox to its original (ie. unflushed) state. The
1163 * ~/.fetchids file did get flushed though, so the next time
1164 * fetchmail was run it saw all the old messages as new ones ..."
1167 gen_transact(sock, "RSET");
1168 #endif /* __UNUSED__ */
1170 ok = gen_transact(sock, "QUIT");
1177 const static struct method pop3 =
1179 "POP3", /* Post Office Protocol v3 */
1181 "pop3", /* standard POP3 port */
1182 "pop3s", /* ssl POP3 port */
1183 #else /* INET6_ENABLE */
1184 110, /* standard POP3 port */
1185 995, /* ssl POP3 port */
1186 #endif /* INET6_ENABLE */
1187 FALSE, /* this is not a tagged protocol */
1188 TRUE, /* this uses a message delimiter */
1189 pop3_ok, /* parse command response */
1190 pop3_getauth, /* get authorization */
1191 pop3_getrange, /* query range of messages */
1192 pop3_getsizes, /* we can get a list of sizes */
1193 pop3_getpartialsizes, /* we can get the size of 1 mail */
1194 pop3_is_old, /* how do we tell a message is old? */
1195 pop3_fetch, /* request given message */
1196 NULL, /* no way to fetch body alone */
1197 NULL, /* no message trailer */
1198 pop3_delete, /* how to delete a message */
1199 pop3_mark_seen, /* how to mark a message as seen */
1200 pop3_logout, /* log out, we're done */
1201 FALSE, /* no, we can't re-poll */
1204 int doPOP3 (struct query *ctl)
1205 /* retrieve messages using POP3 */
1208 if (ctl->mailboxes->id) {
1209 fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
1213 peek_capable = !ctl->fetchall;
1214 return(do_protocol(ctl, &pop3));
1216 #endif /* POP3_ENABLE */
1218 /* pop3.c ends here */