2 * driver.c -- generic driver for mail fetch method protocols
4 * Copyright 1997 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
16 #endif /* HAVE_MEMORY_H */
17 #if defined(STDC_HEADERS)
20 #if defined(HAVE_UNISTD_H)
23 #if defined(HAVE_STDARG_H)
28 #if defined(HAVE_ALLOCA_H)
35 #if defined(HAVE_SYS_ITIMER_H)
36 #include <sys/itimer.h>
41 #ifndef HAVE_STRFTIME /* For ctime prototype */
42 #include <sys/types.h>
46 #ifdef HAVE_GETHOSTBYNAME
49 #endif /* HAVE_GETHOSTBYNAME */
52 #if defined (__bsdi__)
53 #include <des.h> /* order of includes matters */
55 #define krb_get_err_text(e) (krb_err_txt[e])
57 #if defined(__FreeBSD__) || defined(__linux__)
58 #define krb_get_err_text(e) (krb_err_txt[e])
64 #endif /* ! defined (__FreeBSD__) */
65 #endif /* ! defined (__bsdi__) */
66 #include <netinet/in.h>
68 #endif /* KERBEROS_V4 */
69 #include "fetchmail.h"
73 /* BSD portability hack...I know, this is an ugly place to put it */
74 #if !defined(SIGCHLD) && defined(SIGCLD)
75 #define SIGCHLD SIGCLD
79 #define SMTP_PORT "smtp" /* standard SMTP service port */
81 #define SMTP_PORT 25 /* standard SMTP service port */
84 #ifndef strstr /* glibc-2.1 declares this as a macro */
85 extern char *strstr(); /* needed on sysV68 R3V7.1. */
88 int fetchlimit; /* how often to tear down the server connection */
89 int batchcount; /* count of messages sent in current batch */
90 flag peek_capable; /* can we peek for better error recovery? */
91 int pass; /* how many times have we re-polled? */
93 static const struct method *protocol;
94 static jmp_buf restart;
98 #define GENSYM (sprintf(tag, "a%04d", ++tagnum % TAGMOD), tag)
100 static char *shroud; /* string to shroud in debug output, if non-NULL */
101 static int mytimeout; /* value of nonreponse timeout */
102 static int msglen; /* actual message length */
104 /* use these to track what was happening when the nonresponse timer fired */
105 #define GENERAL_WAIT 0
106 #define SERVER_WAIT 1
107 #define FORWARDING_WAIT 2
110 static void set_timeout(int timeleft)
111 /* reset the nonresponse-timeout */
113 struct itimerval ntimeout;
115 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
116 ntimeout.it_value.tv_sec = timeleft;
117 ntimeout.it_value.tv_usec = 0;
118 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
121 static void timeout_handler (int signal)
122 /* handle server-timeout SIGALRM signal */
127 #define XMIT_ACCEPT 1
128 #define XMIT_REJECT 2
129 #define XMIT_ANTISPAM 3
130 static int accept_count, reject_count;
134 static int is_host_alias(const char *name, struct query *ctl)
135 /* determine whether name is a DNS alias of the hostname */
138 struct mxentry *mxp, *mxrecords;
140 struct hostdata *lead_server =
141 ctl->server.lead_server ? ctl->server.lead_server : &ctl->server;
144 * The first two checks are optimizations that will catch a good
147 * (1) check against the `true name' deduced from the poll label
148 * and the via option (if present) at the beginning of the poll cycle.
149 * Odds are good this will either be the mailserver's FQDN or a suffix of
150 * it with the mailserver's domain's default host name omitted.
152 * (2) Then check the rest of the `also known as'
153 * cache accumulated by previous DNS checks. This cache is primed
154 * by the aka list option.
156 * Any of these on a mail address is definitive. Only if the
157 * name doesn't match any is it time to call the bind library.
158 * If this happens odds are good we're looking at an MX name.
160 if (strcasecmp(lead_server->truename, name) == 0)
162 else if (str_in_list(&lead_server->akalist, name))
164 else if (!ctl->server.dns)
167 #ifndef HAVE_RES_SEARCH
171 * The only code that calls the BIND library is here and in the
172 * start-of-query probe with gethostbyname(3).
174 * We know DNS service was up at the beginning of this poll cycle.
175 * If it's down, our nameserver has crashed. We don't want to try
176 * delivering the current message or anything else from this
177 * mailbox until it's back up.
179 else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
181 if (strcasecmp(ctl->server.truename, he->h_name) == 0)
189 case HOST_NOT_FOUND: /* specified host is unknown */
190 case NO_ADDRESS: /* valid, but does not have an IP address */
193 case NO_RECOVERY: /* non-recoverable name server error */
194 case TRY_AGAIN: /* temporary error on authoritative server */
196 if (outlevel != O_SILENT)
197 putchar('\n'); /* terminate the progress message */
199 "nameserver failure while looking for `%s' during poll of %s.",
200 name, ctl->server.pollname);
206 * We're only here if DNS was OK but the gethostbyname() failed
207 * with a HOST_NOT_FOUND or NO_ADDRESS error.
208 * Search for a name match on MX records pointing to the server.
211 if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
215 case HOST_NOT_FOUND: /* specified host is unknown */
216 case NO_ADDRESS: /* valid, but does not have an IP address */
220 case NO_RECOVERY: /* non-recoverable name server error */
221 case TRY_AGAIN: /* temporary error on authoritative server */
224 "nameserver failure while looking for `%s' during poll of %s.",
225 name, ctl->server.pollname);
232 for (mxp = mxrecords; mxp->name; mxp++)
233 if (strcasecmp(ctl->server.truename, mxp->name) == 0)
239 /* add this name to relevant server's `also known as' list */
240 save_str(&lead_server->akalist, -1, name);
242 #endif /* HAVE_RES_SEARCH */
245 static void map_name(name, ctl, xmit_names)
246 /* add given name to xmit_names if it matches declared localnames */
247 const char *name; /* name to map */
248 struct query *ctl; /* list of permissible aliases */
249 struct idlist **xmit_names; /* list of recipient names parsed out */
255 lname = idpair_find(&ctl->localnames, name);
256 if (!lname && ctl->wildcard)
259 if (lname != (char *)NULL)
262 * If the name of the user begins with a
263 * qmail virtual domain prefix, remove
266 if (ctl->server.qvirtual)
268 sl=strlen(ctl->server.qvirtual);
269 if (!strncasecmp(lname,ctl->server.qvirtual,sl)) off=sl;
271 if (outlevel == O_VERBOSE)
272 error(0, 0, "mapped %s to local %s", name, lname+off);
273 save_str(xmit_names, XMIT_ACCEPT, lname+off);
278 void find_server_names(hdr, ctl, xmit_names)
279 /* parse names out of a RFC822 header into an ID list */
280 const char *hdr; /* RFC822 header in question */
281 struct query *ctl; /* list of permissible aliases */
282 struct idlist **xmit_names; /* list of recipient names parsed out */
284 if (hdr == (char *)NULL)
290 for (cp = nxtaddr(hdr);
296 if ((atsign = strchr(cp, '@'))) {
300 * Does a trailing segment of the hostname match something
301 * on the localdomains list? If so, save the whole name
304 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
307 rhs = atsign + (strlen(atsign) - strlen(idp->id));
309 (rhs[-1] == '.' || rhs[-1] == '@') &&
310 strcasecmp(rhs, idp->id) == 0)
312 if (outlevel == O_VERBOSE)
313 error(0, 0, "passed through %s matching %s",
315 save_str(xmit_names, XMIT_ACCEPT, cp);
320 /* if we matched a local domain, idp != NULL */
324 * Check to see if the right-hand part is an alias
325 * or MX equivalent of the mailserver. If it's
326 * not, skip this name. If it is, we'll keep
327 * going and try to find a mapping to a client name.
329 if (!is_host_alias(atsign+1, ctl))
331 save_str(xmit_names, XMIT_REJECT, cp);
338 map_name(cp, ctl, xmit_names);
343 static char *parse_received(struct query *ctl, char *bufp)
344 /* try to extract real address from the Received line */
345 /* If a valid Received: line is found, we return the full address in
346 * a buffer wich can be parsed from nxtaddr(). This is to ansure that
347 * the local domain part of the address can be passed along in
348 * find_server_names() if it contains one.
349 * Note: We should return a dummy header containing the address
350 * which makes nxtaddr() behave correctly.
353 char *ok = (char *)NULL;
354 static char rbuf[HOSTLEN + USERNAMELEN + 4];
357 * Try to extract the real envelope addressee. We look here
358 * specifically for the mailserver's Received line.
359 * Note: this will only work for sendmail, or an MTA that
360 * shares sendmail's convention for embedding the envelope
361 * address in the Received line. Sendmail itself only
362 * does this when the mail has a single recipient.
364 if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
368 /* extract space-delimited token after "by " */
369 for (sp = ok + 3; isspace(*sp); sp++)
372 for (; !isspace(*sp); sp++)
377 * If it's a DNS name of the mail server, look for the
378 * recipient name after a following "for". Otherwise
381 if (is_host_alias(rbuf, ctl) &&
382 (ok = strstr(sp, "for ")) &&
387 *tp++ = ':'; /* Here is the hack. This is to be friend */
388 *tp++ = ' '; /* with nxtaddr()... */
391 while (*sp == '@') /* skip routes */
392 while (*sp && *sp++ != ':')
394 while (*sp && *sp != '>' && *sp != ';')
399 /* uh oh -- whitespace here can't be right! */
405 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
415 if (outlevel == O_VERBOSE) {
416 char *lf = rbuf + strlen(rbuf)-1;
418 error(0, 0, "found Received address `%s'", rbuf+2);
425 static int smtp_open(struct query *ctl)
426 /* try to open a socket to the appropriate SMTP server for this query */
428 /* maybe it's time to close the socket in order to force delivery */
429 if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
431 close(ctl->smtp_socket);
432 ctl->smtp_socket = -1;
436 /* if no socket to any SMTP host is already set up, try to open one */
437 if (ctl->smtp_socket == -1)
440 * RFC 1123 requires that the domain name in HELO address is a
441 * "valid principal domain name" for the client host. If we're
442 * running in invisible mode, violate this with malice
443 * aforethought in order to make the Received headers and
444 * logging look right.
446 * In fact this code relies on the RFC1123 requirement that the
447 * SMTP listener must accept messages even if verification of the
448 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
450 * How we compute the true mailhost name to pass to the
451 * listener doesn't affect behavior on RFC1123- violating
452 * listener that check for name match; we're going to lose
453 * on those anyway because we can never give them a name
454 * that matches the local machine fetchmail is running on.
455 * What it will affect is the listener's logging.
458 char *id_me = use_invisible ? ctl->server.truename : fetchmailhost;
463 * Run down the SMTP hunt list looking for a server that's up.
464 * Use both explicit hunt entries (value TRUE) and implicit
465 * (default) ones (value FALSE).
467 for (idp = ctl->smtphunt; idp; idp = idp->next)
469 char *cp, *parsed_host = alloca(strlen(idp->id) + 1);
471 char *portnum = SMTP_PORT;
473 int portnum = SMTP_PORT;
476 ctl->smtphost = idp->id; /* remember last host tried. */
478 strcpy(parsed_host, idp->id);
479 if ((cp = strrchr(parsed_host, '/')))
489 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
492 /* first, probe for ESMTP */
493 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
494 SMTP_ehlo(ctl->smtp_socket, id_me,
495 &ctl->server.esmtp_options) == SM_OK)
499 * RFC 1869 warns that some listeners hang up on a failed EHLO,
500 * so it's safest not to assume the socket will still be good.
502 close(ctl->smtp_socket);
503 ctl->smtp_socket = -1;
505 /* if opening for ESMTP failed, try SMTP */
506 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
509 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
510 SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
513 close(ctl->smtp_socket);
514 ctl->smtp_socket = -1;
518 if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
519 error(0, 0, "forwarding to %s", ctl->smtphost);
521 return(ctl->smtp_socket);
524 /* these are shared by stuffline, readheaders and readbody */
526 static RETSIGTYPE (*sigchld)();
527 static int sizeticker;
529 static int stuffline(struct query *ctl, char *buf)
530 /* ship a line to the given control block's output sink (SMTP server or MDA) */
535 /* The line may contain NUL characters. Find the last char to use
536 * -- the real line termination is the sequence "\n\0".
539 while ((last += strlen(last)) && (last[-1] != '\n'))
542 /* fix message lines that have only \n termination (for qmail) */
545 if (last - 1 == buf || last[-2] != '\r')
554 phase = FORWARDING_WAIT;
557 * SMTP byte-stuffing. We only do this if the protocol does *not*
558 * use .<CR><LF> as EOM. If it does, the server will already have
559 * decorated any . lines it sends back up.
562 if (protocol->delimited) /* server has already byte-stuffed */
567 /* writing to SMTP, leave the byte-stuffing in place */;
569 else /* if (!protocol->delimited) -- not byte-stuffed already */
572 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
574 /* leave it alone */;
577 /* we may need to strip carriage returns */
582 for (sp = tp = buf; sp < last; sp++)
591 n = fwrite(buf, 1, last - buf, sinkfp);
592 else if (ctl->smtp_socket != -1)
593 n = SockWrite(ctl->smtp_socket, buf, last - buf);
600 static int readheaders(sock, fetchlen, reallen, ctl, num)
601 /* read message headers and ship to SMTP or MDA */
602 int sock; /* to which the server is connected */
603 long fetchlen; /* length of message according to fetch response */
604 long reallen; /* length of message according to getsizes */
605 struct query *ctl; /* query control record */
606 int num; /* index of message */
611 struct addrblk *next;
613 struct addrblk *to_addrchain = NULL;
614 struct addrblk **to_chainptr = &to_addrchain;
615 struct addrblk *resent_to_addrchain = NULL;
616 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
618 char buf[MSGBUFSIZE+1];
619 char return_path[HOSTLEN + USERNAMELEN + 4];
620 int from_offs, reply_to_offs, resent_from_offs;
621 int app_from_offs, sender_offs, resent_sender_offs;
622 int ctt_offs, env_offs;
623 char *headers, *received_for, *destaddr, *rcv, *cp;
624 int n, linelen, oldlen, ch, remaining, skipcount;
625 struct idlist *idp, *xmit_names;
626 flag good_addresses, bad_addresses, has_nuls;
627 flag no_local_matches = FALSE;
632 return_path[0] = '\0';
633 olderrs = ctl->errcount;
635 /* read message headers */
636 headers = received_for = NULL;
637 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
638 sender_offs = resent_sender_offs = ctt_offs = env_offs = -1;
643 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
647 line = xmalloc(sizeof(buf));
651 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
659 /* lines may not be properly CRLF terminated; fix this for qmail */
662 cp = buf + strlen(buf) - 1;
663 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
671 set_timeout(ctl->server.timeout);
673 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
676 if (line[0] == '\r' && line[1] == '\n')
679 /* we may need to grab RFC822 continuations */
680 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
682 /* write the message size dots */
683 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
685 sizeticker += linelen;
686 while (sizeticker >= SIZETICKER)
689 sizeticker -= SIZETICKER;
693 if (linelen != strlen(line))
696 /* check for end of headers; don't save terminating line */
697 if (line[0] == '\r' && line[1] == '\n')
704 * The University of Washington IMAP server (the reference
705 * implementation of IMAP4 written by Mark Crispin) relies
706 * on being able to keep base-UID information in a special
707 * message at the head of the mailbox. This message should
708 * neither be deleted nor forwarded.
712 * We disable this check under POP2 because there's no way to
713 * prevent deletion of the message. So at least we ought to
714 * forward it to the user so he or she will have some clue
715 * that things have gone awry.
717 if (protocol->port != 109)
718 #endif /* POP2_ENABLE */
719 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
726 * This code prevents fetchmail from becoming an accessory after
727 * the fact to upstream sendmails with the `E' option on. This
728 * can result in an escaped Unix From_ line at the beginning of
729 * the headers. If fetchmail just passes it through, the client
730 * listener may think the message has *no* headers (since the first)
731 * line it sees doesn't look RFC822-conformant) and fake up a set.
733 * What the user would see in this case is bogus (synthesized)
734 * headers, followed by a blank line, followed by the >From,
735 * followed by the real headers, followed by a blank line,
738 * We forestall this lossage by tossing anything that looks
739 * like an escaped From_ line in headers. These aren't RFC822
740 * so our conscience is clear...
742 if (!strncasecmp(line, ">From ", 6))
749 * If we see a Status line, it may have been inserted by an MUA
750 * on the mail host, or it may have been inserted by the server
751 * program after the headers in the transaction stream. This
752 * can actually hose some new-mail notifiers such as xbuffy,
753 * which assumes any Status line came from a *local* MDA and
754 * therefore indicates that the message has been seen.
756 * Some buggy POP servers (including at least the 3.3(20)
757 * version of the one distributed with IMAP) insert empty
758 * Status lines in the transaction stream; we'll chuck those
759 * unconditionally. Nonempty ones get chucked if the user
760 * turns on the dropstatus flag.
764 if (!strncasecmp(line, "Status:", 7))
766 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
771 while (*cp && isspace(*cp)) cp++;
772 if (!*cp || ctl->dropstatus)
781 line = reply_hack(line, ctl->server.truename);
784 * OK, this is messy. If we're forwarding by SMTP, it's the
785 * SMTP-receiver's job (according to RFC821, page 22, section
786 * 4.1.1) to generate a Return-Path line on final delivery.
787 * The trouble is, we've already got one because the
788 * mailserver's SMTP thought *it* was responsible for final
791 * Stash away the contents of Return-Path for use in generating
792 * MAIL FROM later on, then prevent the header from being saved
793 * with the others. In effect, we strip it off here.
795 * If the SMTP server conforms to the standards, and fetchmail gets the
796 * envelope sender from the Return-Path, the new Return-Path should be
797 * exactly the same as the original one.
799 if (!strncasecmp("Return-Path:", line, 12))
801 strcpy(return_path, nxtaddr(line));
810 oldlen = strlen(line);
811 headers = xmalloc(oldlen + 1);
812 (void) strcpy(headers, line);
820 newlen = oldlen + strlen(line);
821 headers = (char *) realloc(headers, newlen + 1);
822 if (headers == NULL) {
826 strcpy(headers + oldlen, line);
828 line = headers + oldlen;
832 if (!strncasecmp("From:", line, 5))
833 from_offs = (line - headers);
834 else if (!strncasecmp("Reply-To:", line, 9))
835 reply_to_offs = (line - headers);
836 else if (!strncasecmp("Resent-From:", line, 12))
837 resent_from_offs = (line - headers);
838 else if (!strncasecmp("Apparently-From:", line, 16))
839 app_from_offs = (line - headers);
840 else if (!strncasecmp("Sender:", line, 7))
841 sender_offs = (line - headers);
842 else if (!strncasecmp("Resent_Sender:", line, 14))
843 resent_sender_offs = (line - headers);
845 else if (!strncasecmp("Content-Transfer-Encoding:", line, 26))
846 ctt_offs = (line - headers);
847 else if (!strncasecmp("Message-Id:", buf, 11 ))
849 if( ctl->server.uidl )
852 /* prevent stack overflows */
854 sscanf( buf+12, "%s", id);
855 if( !str_find( &ctl->newsaved, num ) )
856 save_str(&ctl->newsaved, num, id );
860 else if (!MULTIDROP(ctl))
863 else if (!strncasecmp("To:", line, 3)
864 || !strncasecmp("Cc:", line, 3)
865 || !strncasecmp("Bcc:", line, 4)
866 || !strncasecmp("Apparently-To:", line, 14))
868 *to_chainptr = xmalloc(sizeof(struct addrblk));
869 (*to_chainptr)->offset = (line - headers);
870 to_chainptr = &(*to_chainptr)->next;
874 else if (!strncasecmp("Resent-To:", line, 10)
875 || !strncasecmp("Resent-Cc:", line, 10)
876 || !strncasecmp("Resent-Bcc:", line, 11))
878 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
879 (*resent_to_chainptr)->offset = (line - headers);
880 resent_to_chainptr = &(*resent_to_chainptr)->next;
881 *resent_to_chainptr = NULL;
884 else if (ctl->server.envelope != STRING_DISABLED)
886 if (ctl->server.envelope
887 && strcasecmp(ctl->server.envelope, "Received"))
889 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
891 strlen(ctl->server.envelope)))
893 if (skipcount++ != ctl->server.envskip)
895 env_offs = (line - headers);
898 else if (!received_for && !strncasecmp("Received:", line, 9))
900 if (skipcount++ != ctl->server.envskip)
902 received_for = parse_received(ctl, line);
908 * Hack time. If the first line of the message was blank, with no headers
909 * (this happens occasionally due to bad gatewaying software) cons up
910 * a set of fake headers.
912 * If you modify the fake header template below, be sure you don't
913 * make either From or To address @-less, otherwise the reply_hack
914 * logic will do bad things.
916 if (headers == (char *)NULL)
919 snprintf(buf, sizeof(buf),
922 #endif /* HAVE_SNPRINTF */
923 "From: <FETCHMAIL-DAEMON@%s>\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
924 fetchmailhost, user, ctl->remotename, ctl->server.truename);
925 headers = xstrdup(buf);
929 * We can now process message headers before reading the text.
930 * In fact we have to, as this will tell us where to forward to.
934 * If there is a Return-Path address on the message, this was
935 * almost certainly the MAIL FROM address given the originating
936 * sendmail. This is the best thing to use for logging the
937 * message origin (it sets up the right behavior for bounces and
938 * mailing lists). Otherwise, fall down to the next available
939 * envelope address wich is the most probable real sender
940 * respectively. *** The order is important! ***
941 * This is especially useful when receiving mailing list
942 * messages in multidrop mode. if a local address doesn't
943 * exist, the bounce message won't be returned blindly to the
944 * author or to the list itself but rather to the list manager
945 * (ex: specified by "Sender:") wich is less anoying. This is
946 * true for most mailing list packages.
948 if( !return_path[0] ){
950 if (resent_sender_offs >= 0 && (ap = nxtaddr(headers + resent_sender_offs)));
951 else if (sender_offs >= 0 && (ap = nxtaddr(headers + sender_offs)));
952 else if (resent_from_offs >= 0 && (ap = nxtaddr(headers + resent_from_offs)));
953 else if (from_offs >= 0 && (ap = nxtaddr(headers + from_offs)));
954 else if (reply_to_offs >= 0 && (ap = nxtaddr(headers + reply_to_offs)));
955 else if (app_from_offs >= 0 && (ap = nxtaddr(headers + app_from_offs)));
956 if (ap) strcpy( return_path, ap );
959 /* cons up a list of local recipients */
960 xmit_names = (struct idlist *)NULL;
961 bad_addresses = good_addresses = accept_count = reject_count = 0;
962 /* is this a multidrop box? */
965 if (env_offs > -1) /* We have the actual envelope addressee */
966 find_server_names(headers + env_offs, ctl, &xmit_names);
967 else if (received_for)
969 * We have the Received for addressee.
970 * It has to be a mailserver address, or we
971 * wouldn't have got here.
972 * We use find_server_names() to let local
973 * hostnames go through.
975 find_server_names(received_for, ctl, &xmit_names);
978 * We haven't extracted the envelope address.
979 * So check all the "Resent-To" header addresses if
980 * they exist. If and only if they don't, consider
983 register struct addrblk *nextptr;
984 if (resent_to_addrchain) {
985 /* delete the "To" chain and substitute it
986 * with the "Resent-To" list
988 while (to_addrchain) {
989 nextptr = to_addrchain->next;
991 to_addrchain = nextptr;
993 to_addrchain = resent_to_addrchain;
994 resent_to_addrchain = NULL;
996 /* now look for remaining adresses */
997 while (to_addrchain) {
998 find_server_names(headers+to_addrchain->offset, ctl, &xmit_names);
999 nextptr = to_addrchain->next;
1001 to_addrchain = nextptr;
1006 no_local_matches = TRUE;
1007 save_str(&xmit_names, XMIT_ACCEPT, user);
1008 if (outlevel == O_VERBOSE)
1010 "no local matches, forwarding to %s",
1014 else /* it's a single-drop box, use first localname */
1015 save_str(&xmit_names, XMIT_ACCEPT, ctl->localnames->id);
1019 * Time to either address the message or decide we can't deliver it yet.
1021 if (ctl->errcount > olderrs) /* there were DNS errors above */
1023 if (outlevel == O_VERBOSE)
1024 error(0,0, "forwarding and deletion suppressed due to DNS errors");
1026 free_str_list(&xmit_names);
1027 return(PS_TRANSIENT);
1029 else if (ctl->mda) /* we have a declared MDA */
1032 char *names, *before, *after;
1034 for (idp = xmit_names; idp; idp = idp->next)
1035 if (idp->val.num == XMIT_ACCEPT)
1038 destaddr = "localhost";
1040 length = strlen(ctl->mda) + 1;
1041 before = xstrdup(ctl->mda);
1043 /* sub user addresses for %T (or %s for backward compatibility) */
1045 if (strstr(before, "%s") || (cp = strstr(before, "%T")))
1049 if (cp && cp[1] == 'T')
1052 /* \177 had better be out-of-band for MDA commands */
1053 for (sp = before; *sp; sp++)
1054 if (*sp == '%' && sp[1] != 's' && sp[1] != 'T')
1058 * We go through this in order to be able to handle very
1059 * long lists of users and (re)implement %s.
1061 for (idp = xmit_names; idp; idp = idp->next)
1062 if (idp->val.num == XMIT_ACCEPT)
1063 length += (strlen(idp->id) + 1);
1065 names = (char *)xmalloc(++length);
1067 for (idp = xmit_names; idp; idp = idp->next)
1068 if (idp->val.num == XMIT_ACCEPT)
1070 strcat(names, idp->id);
1073 after = (char *)xmalloc(length);
1075 snprintf(after, length, before, names);
1077 sprintf(after, before, names);
1078 #endif /* SNPRINTF */
1083 for (sp = before; *sp; sp++)
1088 /* substitute From address for %F */
1089 if ((cp = strstr(before, "%F")))
1091 char *from = return_path;
1094 /* \177 had better be out-of-band for MDA commands */
1095 for (sp = before; *sp; sp++)
1096 if (*sp == '%' && sp[1] != 'F')
1099 length += strlen(from);
1100 after = (char *)xmalloc(length);
1103 snprintf(after, length, before, from);
1105 sprintf(after, before, from);
1106 #endif /* SNPRINTF */
1110 for (sp = before; *sp; sp++)
1115 if (outlevel == O_VERBOSE)
1116 error(0, 0, "about to deliver with: %s", before);
1120 * Arrange to run with user's permissions if we're root.
1121 * This will initialize the ownership of any files the
1122 * MDA creates properly. (The seteuid call is available
1123 * under all BSDs and Linux)
1126 #endif /* HAVE_SETEUID */
1128 sinkfp = popen(before, "w");
1132 /* this will fail quietly if we didn't start as root */
1134 #endif /* HAVE_SETEUID */
1138 error(0, 0, "MDA open failed");
1140 free_str_list(&xmit_names);
1144 sigchld = signal(SIGCHLD, SIG_DFL);
1148 char *ap, *ctt, options[MSGBUFSIZE], addr[128];
1150 /* build a connection to the SMTP listener */
1151 if ((smtp_open(ctl) == -1))
1153 error(0, errno, "SMTP connect to %s failed",
1154 ctl->smtphost ? ctl->smtphost : "localhost");
1156 free_str_list(&xmit_names);
1161 * Compute ESMTP options. It's a kluge to use nxtaddr()
1162 * here because the contents of the Content-Transfer-Encoding
1163 * headers isn't semantically an address. But it has the
1164 * desired tokenizing effect.
1167 if (ctl->server.esmtp_options & ESMTP_8BITMIME)
1169 strcpy(options, " BODY=8BITMIME");
1170 else if ((ctt_offs >= 0) && (ctt = nxtaddr(headers + ctt_offs)))
1172 if (!strcasecmp(ctt,"7BIT"))
1173 strcpy(options, " BODY=7BIT");
1174 else if (!strcasecmp(ctt,"8BIT"))
1175 strcpy(options, " BODY=8BITMIME");
1177 if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
1178 sprintf(options + strlen(options), " SIZE=%ld", reallen);
1181 * Try to get the SMTP listener to take the Return-Path
1182 * address as MAIL FROM . If it won't, fall back on the
1183 * calling-user ID. This won't affect replies, which use the
1184 * header From address anyway.
1186 * RFC 1123 requires that the domain name part of the
1187 * MAIL FROM address be "canonicalized", that is a
1188 * FQDN or MX but not a CNAME. We'll assume the From
1189 * header is already in this form here (it certainly
1190 * is if rewrite is on). RFC 1123 is silent on whether
1191 * a nonexistent hostname part is considered canonical.
1193 * This is a potential problem if the MTAs further upstream
1194 * didn't pass canonicalized From/Return-Path lines, *and* the
1195 * local SMTP listener insists on them.
1197 ap = (return_path[0]) ? return_path : user;
1198 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
1200 int smtperr = atoi(smtp_response);
1203 * Suppress error message only if the response specifically
1204 * means `excluded for policy reasons'. We *should* see
1205 * an error when the return code is less specific.
1207 if (smtperr >= 400 && smtperr != 571)
1208 error(0, -1, "SMTP error: %s", smtp_response);
1212 case 571: /* sendmail's "unsolicited email refused" */
1213 case 501: /* exim's old antispam response */
1214 case 550: /* exim's new antispam response (temporary) */
1216 * SMTP listener explicitly refuses to deliver
1217 * mail coming from this address, probably due
1218 * to an anti-spam domain exclusion. Respect
1219 * this. Don't try to ship the message, and
1220 * don't prevent it from being deleted.
1223 free_str_list(&xmit_names);
1226 case 452: /* insufficient system storage */
1228 * Temporary out-of-queue-space condition on the
1229 * ESMTP server. Don't try to ship the message,
1230 * and suppress deletion so it can be retried on
1231 * a future retrieval cycle.
1233 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1235 free_str_list(&xmit_names);
1236 return(PS_TRANSIENT);
1238 case 552: /* message exceeds fixed maximum message size */
1240 * Permanent no-go condition on the
1241 * ESMTP server. Don't try to ship the message,
1242 * and allow it to be deleted.
1244 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1246 free_str_list(&xmit_names);
1249 default: /* retry with invoking user's address */
1250 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1252 error(0, -1, "SMTP error: %s", smtp_response);
1254 free_str_list(&xmit_names);
1255 return(PS_SMTP); /* should never happen */
1261 * Now list the recipient addressees
1263 * RFC 1123 requires that the domain name part of the
1264 * RCPT TO address be "canonicalized", that is a FQDN
1265 * or MX but not a CNAME. Some listeners (like exim)
1268 destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
1270 for (idp = xmit_names; idp; idp = idp->next)
1271 if (idp->val.num == XMIT_ACCEPT)
1273 if (strchr(idp->id, '@'))
1274 strcpy(addr, idp->id);
1276 #ifdef HAVE_SNPRINTF
1277 snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, destaddr);
1279 sprintf(addr, "%s@%s", idp->id, destaddr);
1280 #endif /* HAVE_SNPRINTF */
1282 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1287 idp->val.num = XMIT_ANTISPAM;
1289 "SMTP listener doesn't like recipient address `%s'",
1293 if (!good_addresses)
1295 #ifdef HAVE_SNPRINTF
1296 snprintf(addr, sizeof(addr)-1, "%s@%s", user, destaddr);
1298 sprintf(addr, "%s@%s", user, destaddr);
1299 #endif /* HAVE_SNPRINTF */
1301 if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1303 error(0, 0, "can't even send to calling user!");
1305 free_str_list(&xmit_names);
1310 /* tell it we're ready to send data */
1311 SMTP_data(ctl->smtp_socket);
1316 * Some server/sendmail combinations cause problems when our
1317 * synthetic Received line is before the From header. Cope
1320 if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
1325 n = stuffline(ctl, headers);
1328 if (!use_invisible && n != -1)
1330 /* utter any per-message Received information we need here */
1331 sprintf(buf, "Received: from %s\n", ctl->server.truename);
1332 n = stuffline(ctl, buf);
1336 * We used to include ctl->remotename in this log line,
1337 * but this can be secure information that would be bad
1340 sprintf(buf, "\tby %s (fetchmail-%s %s)\n",
1344 n = stuffline(ctl, buf);
1350 if (good_addresses == 0)
1353 "for <%s@%s> (by default); ",
1356 else if (good_addresses == 1)
1358 for (idp = xmit_names; idp; idp = idp->next)
1359 if (idp->val.num == XMIT_ACCEPT)
1360 break; /* only report first address */
1361 if (strchr(idp->id, '@'))
1362 sprintf(buf+1, "for <%s>", idp->id);
1364 sprintf(buf+1, "for <%s/%s>", idp->id, destaddr);
1365 sprintf(buf+strlen(buf), " (%s); ",
1366 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1372 #ifdef HAVE_STRFTIME
1374 * Conform to RFC822. This is typically going to emit
1375 * a three-letter timezone for %Z, which is going to
1376 * be marked "obsolete syntax" in 822bis. Note that we
1377 * generate a 4-digit year here.
1379 strftime(buf + strlen(buf), sizeof(buf) - strlen(buf),
1380 "%a, %d %b %Y %H:%M:%S %Z\n", localtime(&now));
1383 * This is really just a portability fallback, as the
1384 * date format ctime(3) emits is not RFC822
1387 strcat(buf, ctime(&now));
1388 #endif /* HAVE_STRFTIME */
1389 n = stuffline(ctl, buf);
1395 n = stuffline(ctl, rcv); /* ship out rest of headers */
1399 error(0, errno, "writing RFC822 headers");
1404 signal(SIGCHLD, sigchld);
1407 free_str_list(&xmit_names);
1410 else if (outlevel == O_VERBOSE)
1413 /* write error notifications */
1414 if (no_local_matches || has_nuls || bad_addresses)
1417 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1420 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1421 if (no_local_matches)
1423 if (reject_count != 1)
1424 strcat(errhd, "no recipient addresses matched declared local names");
1427 for (idp = xmit_names; idp; idp = idp->next)
1428 if (idp->val.num == XMIT_REJECT)
1430 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1436 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1437 strcat(errhd, "; ");
1438 strcat(errhd, "message has embedded NULs");
1443 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1444 strcat(errhd, "; ");
1445 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1446 errlen = strlen(errhd);
1447 for (idp = xmit_names; idp; idp = idp->next)
1448 if (idp->val.num == XMIT_ANTISPAM)
1449 errlen += strlen(idp->id) + 2;
1451 errmsg = alloca(errlen+3);
1452 (void) strcpy(errmsg, errhd);
1453 for (idp = xmit_names; idp; idp = idp->next)
1454 if (idp->val.num == XMIT_ANTISPAM)
1456 strcat(errmsg, idp->id);
1458 strcat(errmsg, ", ");
1463 strcat(errmsg, "\n");
1465 /* ship out the error line */
1467 stuffline(ctl, errmsg);
1470 /* issue the delimiter line */
1475 stuffline(ctl, buf);
1478 free_str_list(&xmit_names);
1482 static int readbody(sock, ctl, forward, len)
1483 /* read and dispose of a message body presented on sock */
1484 struct query *ctl; /* query control record */
1485 int sock; /* to which the server is connected */
1486 int len; /* length of message */
1487 flag forward; /* TRUE to forward */
1490 char buf[MSGBUFSIZE+1];
1492 /* pass through the text lines */
1493 while (protocol->delimited || len > 0)
1495 if ((linelen = SockRead(sock, buf, sizeof(buf)-1)) == -1)
1501 signal(SIGCHLD, sigchld);
1505 set_timeout(ctl->server.timeout);
1507 /* write the message size dots */
1510 sizeticker += linelen;
1511 while (sizeticker >= SIZETICKER)
1513 if (outlevel > O_SILENT)
1515 sizeticker -= SIZETICKER;
1520 /* check for end of message */
1521 if (protocol->delimited && *buf == '.')
1522 if (buf[1] == '\r' && buf[2] == '\n' && buf[3] == '\0')
1524 else if (buf[1] == '\n' && buf[2] == '\0')
1527 msglen--; /* subtract the size of the dot escape */
1531 /* ship out the text line */
1534 int n = stuffline(ctl, buf);
1538 error(0, errno, "writing message text");
1543 signal(SIGCHLD, sigchld);
1547 else if (outlevel == O_VERBOSE)
1557 kerberos_auth (socket, canonical)
1558 /* authenticate to the server host using Kerberos V4 */
1559 int socket; /* socket to server host */
1561 char *canonical; /* server name */
1563 const char *canonical; /* server name */
1566 char * host_primary;
1570 Key_schedule schedule;
1573 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1574 rem = (krb_sendauth (0L, socket, ticket, "pop",
1576 ((char *) (krb_realmofhost (canonical))),
1577 ((unsigned long) 0),
1581 ((struct sockaddr_in *) 0),
1582 ((struct sockaddr_in *) 0),
1585 if (rem != KSUCCESS)
1587 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1588 return (PS_AUTHFAIL);
1592 #endif /* KERBEROS_V4 */
1594 int do_protocol(ctl, proto)
1595 /* retrieve messages from server using given protocol method table */
1596 struct query *ctl; /* parsed options with merged-in defaults */
1597 const struct method *proto; /* protocol method table */
1599 int ok, js, sock = -1;
1604 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1606 error(0, -1, "Kerberos V4 support not linked.");
1609 #endif /* KERBEROS_V4 */
1611 /* lacking methods, there are some options that may fail */
1614 /* check for unsupported options */
1617 "Option --flush is not supported with %s",
1621 else if (ctl->fetchall) {
1623 "Option --all is not supported with %s",
1628 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1631 "Option --limit is not supported with %s",
1639 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1642 /* set up the server-nonresponse timeout */
1643 sigsave = signal(SIGALRM, timeout_handler);
1644 set_timeout(mytimeout = ctl->server.timeout);
1646 if ((js = setjmp(restart)) == 1)
1648 if (phase == SERVER_WAIT)
1650 "timeout after %d seconds waiting for server %s.",
1651 ctl->server.timeout, ctl->server.pollname);
1652 else if (phase == FORWARDING_WAIT)
1654 "timeout after %d seconds waiting for %s.",
1655 ctl->server.timeout,
1656 ctl->mda ? "MDA" : "SMTP");
1658 error(0, 0, "timeout after %d seconds.", ctl->server.timeout);
1660 if (ctl->smtp_socket != -1)
1661 close(ctl->smtp_socket);
1670 char buf [POPBUFSIZE+1], *realhost;
1671 int *msgsizes, len, num, count, new, deletions = 0;
1673 int fetches, dispatches;
1675 int port, fetches, dispatches;
1679 /* execute pre-initialization command, if any */
1680 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1682 sprintf(buf, "pre-connection command failed with status %d", ok);
1688 /* open a socket to the mail server */
1690 port = ctl->server.port ? ctl->server.port : protocol->port;
1692 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1694 if ((sock = SockOpen(realhost,
1695 ctl->server.service ? ctl->server.service : protocol->service,
1696 ctl->server.netsec)) == -1)
1698 if ((sock = SockOpen(realhost, port, NULL)) == -1)
1702 #ifndef EHOSTUNREACH
1703 #define EHOSTUNREACH (-1)
1705 if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1707 error_build("fetchmail: %s connection to %s failed: ",
1708 protocol->name, ctl->server.pollname);
1709 #ifdef HAVE_RES_SEARCH
1710 if (h_errno == HOST_NOT_FOUND)
1711 error_complete(0, 0, "host is unknown");
1712 else if (h_errno == NO_ADDRESS)
1713 error_complete(0, 0, "name is valid but has no IP address");
1714 else if (h_errno == NO_RECOVERY)
1715 error_complete(0, 0, "unrecoverable name server error");
1716 else if (h_errno == TRY_AGAIN)
1717 error_complete(0, 0, "temporary name server error");
1719 error_complete(0, 0, "unknown DNS error %d", h_errno);
1721 #endif /* HAVE_RES_SEARCH */
1722 error_complete(0, errno, "local error");
1730 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1732 ok = kerberos_auth(sock, ctl->server.truename);
1735 set_timeout(ctl->server.timeout);
1737 #endif /* KERBEROS_V4 */
1739 /* accept greeting message from mail server */
1740 ok = (protocol->parse_response)(sock, buf);
1743 set_timeout(ctl->server.timeout);
1745 /* try to get authorized to fetch mail */
1746 if (protocol->getauth)
1748 shroud = ctl->password;
1749 ok = (protocol->getauth)(sock, ctl, buf);
1750 shroud = (char *)NULL;
1753 if (ok == PS_LOCKBUSY)
1754 error(0, -1, "Lock-busy error on %s@%s",
1756 ctl->server.truename);
1761 error(0, -1, "Authorization failure on %s@%s",
1763 ctl->server.truename);
1767 set_timeout(ctl->server.timeout);
1770 ctl->errcount = fetches = 0;
1772 /* now iterate over each folder selected */
1773 for (idp = ctl->mailboxes; idp; idp = idp->next)
1780 if (outlevel >= O_VERBOSE)
1782 error(0, 0, "selecting or re-polling folder %s", idp->id);
1784 error(0, 0, "selecting or re-polling default folder");
1786 /* compute # of messages and number of new messages waiting */
1787 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new);
1790 set_timeout(ctl->server.timeout);
1792 /* show user how many messages we downloaded */
1794 (void) sprintf(buf, "%s at %s (folder %s)",
1795 ctl->remotename, ctl->server.truename, idp->id);
1797 (void) sprintf(buf, "%s at %s", ctl->remotename, ctl->server.truename);
1798 if (outlevel > O_SILENT)
1799 if (count == -1) /* only used for ETRN */
1800 error(0, 0, "Polling %s", ctl->server.truename);
1801 else if (count != 0)
1803 if (new != -1 && (count - new) > 0)
1804 error(0, 0, "%d message%s (%d seen) for %s.",
1805 count, count > 1 ? "s" : "", count-new, buf);
1807 error(0, 0, "%d message%s for %s.",
1808 count, count > 1 ? "s" : "", buf);
1812 /* these are pointless in normal daemon mode */
1813 if (pass == 1 && (poll_interval == 0 || outlevel == O_VERBOSE))
1814 error(0, 0, "No mail for %s", buf);
1817 /* very important, this is where we leave the do loop */
1823 if (new == -1 || ctl->fetchall)
1825 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1830 flag force_retrieval;
1833 * What forces this code is that in POP3 and
1834 * IMAP2BIS you can't fetch a message without
1835 * having it marked `seen'. In IMAP4, on the
1836 * other hand, you can (peek_capable is set to
1839 * The result of being unable to peek is that if there's
1840 * any kind of transient error (DNS lookup failure, or
1841 * sendmail refusing delivery due to process-table limits)
1842 * the message will be marked "seen" on the server without
1843 * having been delivered. This is not a big problem if
1844 * fetchmail is running in foreground, because the user
1845 * will see a "skipped" message when it next runs and get
1848 * But in daemon mode this leads to the message
1849 * being silently ignored forever. This is not
1852 * We compensate for this by checking the error
1853 * count from the previous pass and forcing all
1854 * messages to be considered new if it's nonzero.
1856 force_retrieval = !peek_capable && (ctl->errcount > 0);
1859 * We need the size of each message before it's
1860 * loaded in order to pass via the ESMTP SIZE
1861 * option. If the protocol has a getsizes method,
1862 * we presume this means it doesn't get reliable
1863 * sizes from message fetch responses.
1865 if (proto->getsizes)
1869 msgsizes = (int *)alloca(sizeof(int) * count);
1870 for (i = 0; i < count; i++)
1873 ok = (proto->getsizes)(sock, count, msgsizes);
1876 set_timeout(ctl->server.timeout);
1879 /* read, forward, and delete messages */
1880 for (num = 1; num <= count; num++)
1882 flag toolarge = NUM_NONZERO(ctl->limit)
1883 && msgsizes && (msgsizes[num-1] > ctl->limit);
1884 flag fetch_it = !toolarge
1885 && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
1886 flag suppress_delete = FALSE;
1887 flag suppress_forward = FALSE;
1888 flag retained = FALSE;
1891 * This check copes with Post Office/NT's
1892 * annoying habit of randomly prepending bogus
1893 * LIST items of length -1. Patrick Audley
1894 * <paudley@pobox.com> tells us: LIST shows a
1895 * size of -1, RETR and TOP return "-ERR
1896 * System error - couldn't open message", and
1897 * DELE succeeds but doesn't actually delete
1900 if (msgsizes && msgsizes[num-1] == -1)
1902 if (outlevel >= O_VERBOSE)
1904 "Skipping message %d, length -1",
1909 /* we may want to reject this message if it's old */
1912 if (outlevel > O_SILENT)
1914 error_build("skipping message %d", num);
1916 error_build(" (oversized, %d bytes)",
1922 flag wholesize = !protocol->fetch_body;
1924 /* request a message */
1925 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1928 set_timeout(ctl->server.timeout);
1930 /* -1 means we didn't see a size in the response */
1931 if (len == -1 && msgsizes)
1933 len = msgsizes[num - 1];
1937 if (outlevel > O_SILENT)
1939 error_build("reading message %d of %d",
1943 error_build(" (%d %sbytes)",
1944 len, wholesize ? "" : "header ");
1945 if (outlevel == O_VERBOSE)
1946 error_complete(0, 0, "");
1951 /* later we'll test for this before closing */
1952 sinkfp = (FILE *)NULL;
1955 * Read the message headers and ship them to the
1958 ok = readheaders(sock, len, msgsizes[num-1],
1960 if (ok == PS_RETAINED)
1961 suppress_forward = retained = TRUE;
1962 else if (ok == PS_TRANSIENT)
1963 suppress_delete = suppress_forward = TRUE;
1964 else if (ok == PS_REFUSED)
1965 suppress_forward = TRUE;
1968 set_timeout(ctl->server.timeout);
1971 * If we're using IMAP4 or something else that
1972 * can fetch headers separately from bodies,
1973 * it's time to request the body now. This
1974 * fetch may be skipped if we got an anti-spam
1975 * or other PS_REFUSED error response during
1978 if (protocol->fetch_body)
1980 if (outlevel == O_VERBOSE)
1981 fputc('\n', stderr);
1983 if ((ok = (protocol->trail)(sock, ctl, num)))
1985 set_timeout(ctl->server.timeout);
1987 if (!suppress_forward)
1989 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1991 if (outlevel > O_SILENT && !wholesize)
1992 error_build(" (%d body bytes) ", len);
1993 set_timeout(ctl->server.timeout);
1997 /* process the body now */
2004 if (ok == PS_TRANSIENT)
2005 suppress_delete = suppress_forward = TRUE;
2008 set_timeout(ctl->server.timeout);
2010 /* tell server we got it OK and resynchronize */
2011 if (protocol->trail)
2013 if (outlevel == O_VERBOSE)
2014 fputc('\n', stderr);
2016 ok = (protocol->trail)(sock, ctl, num);
2019 set_timeout(ctl->server.timeout);
2023 /* count # messages forwarded on this pass */
2024 if (!suppress_forward)
2028 * Check to see if the numbers matched?
2030 * Yes, some servers foo this up horribly.
2031 * All IMAP servers seem to get it right, and
2032 * so does Eudora QPOP at least in 2.xx
2035 * Microsoft Exchange gets it completely
2036 * wrong, reporting compressed rather than
2037 * actual sizes (so the actual length of
2038 * message is longer than the reported size).
2039 * Another fine example of Microsoft brain death!
2041 * Some older POP servers, like the old UCB
2042 * POP server and the pre-QPOP QUALCOMM
2043 * versions, report a longer size in the LIST
2044 * response than actually gets shipped up.
2045 * It's unclear what is going on here, as the
2046 * QUALCOMM server (at least) seems to be
2047 * reporting the on-disk size correctly.
2049 if (msgsizes && msglen != msgsizes[num-1])
2051 if (outlevel >= O_VERBOSE)
2053 "message %d was not the expected length (%d != %d)",
2054 num, msglen, msgsizes[num-1]);
2057 /* end-of-message processing starts here */
2063 /* close the delivery pipe, we'll reopen before next message */
2065 rc = pclose(sinkfp);
2068 signal(SIGCHLD, sigchld);
2071 error(0, -1, "MDA exited abnormally or returned nonzero status");
2075 else if (!suppress_forward)
2077 /* write message terminator */
2078 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
2080 error(0, -1, "SMTP listener refused delivery");
2082 suppress_delete = TRUE;
2090 * At this point in flow of control, either
2091 * we've bombed on a protocol error or had
2092 * delivery refused by the SMTP server
2093 * (unlikely -- I've never seen it) or we've
2094 * seen `accepted for delivery' and the
2095 * message is shipped. It's safe to mark the
2096 * message seen and delete it on the server
2100 /* tell the UID code we've seen this */
2105 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2106 if (sdp->val.num == num)
2107 MARK_SEEN(sdp->val.num);
2110 /* maybe we delete this message now? */
2113 if (outlevel > O_SILENT)
2114 error_complete(0, 0, " retained");
2116 else if (protocol->delete
2118 && (fetch_it ? !ctl->keep : ctl->flush))
2121 if (outlevel > O_SILENT)
2122 error_complete(0, 0, " flushed");
2123 ok = (protocol->delete)(sock, ctl, num);
2126 set_timeout(ctl->server.timeout);
2128 delete_str(&ctl->newsaved, num);
2129 #endif /* POP3_ENABLE */
2131 else if (outlevel > O_SILENT)
2132 error_complete(0, 0, " not flushed");
2134 /* perhaps this as many as we're ready to handle */
2135 if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
2141 * Only re-poll if we had some actual forwards, allowed
2142 * deletions and had no errors.
2143 * Otherwise it is far too easy to get into infinite loops.
2145 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2149 set_timeout(ctl->server.timeout);
2150 ok = (protocol->logout_cmd)(sock, ctl);
2152 * Hmmmm...arguably this would be incorrect if we had fetches but
2153 * no dispatches (due to oversized messages, etc.)
2156 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2162 set_timeout(ctl->server.timeout);
2163 if (ok != 0 && ok != PS_SOCKET)
2164 (protocol->logout_cmd)(sock, ctl);
2169 msg = (char *)NULL; /* sacrifice to -Wall */
2176 msg = "authorization";
2179 msg = "missing or bad RFC822 header";
2185 msg = "client/server synchronization";
2188 msg = "client/server protocol";
2191 msg = "lock busy on server";
2194 msg = "SMTP transaction";
2200 error(0, 0, "undefined");
2203 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2204 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2205 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2206 error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2209 /* execute post-initialization command, if any */
2210 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2214 sprintf(buf, "post-connection command failed with status %d", ok);
2216 if (ok == PS_SUCCESS)
2220 signal(SIGALRM, sigsave);
2224 #if defined(HAVE_STDARG_H)
2225 void gen_send(int sock, const char *fmt, ... )
2226 /* assemble command in printf(3) style and send to the server */
2228 void gen_send(sock, fmt, va_alist)
2229 /* assemble command in printf(3) style and send to the server */
2230 int sock; /* socket to which server is connected */
2231 const char *fmt; /* printf-style format */
2235 char buf [POPBUFSIZE+1];
2238 if (protocol->tagged)
2239 (void) sprintf(buf, "%s ", GENSYM);
2243 #if defined(HAVE_STDARG_H)
2248 #ifdef HAVE_VSNPRINTF
2249 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2251 vsprintf(buf + strlen(buf), fmt, ap);
2255 strcat(buf, "\r\n");
2256 SockWrite(sock, buf, strlen(buf));
2258 if (outlevel == O_VERBOSE)
2262 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2266 sp = cp + strlen(shroud);
2272 buf[strlen(buf)-2] = '\0';
2273 error(0, 0, "%s> %s", protocol->name, buf);
2277 int gen_recv(sock, buf, size)
2278 /* get one line of input from the server */
2279 int sock; /* socket to which server is connected */
2280 char *buf; /* buffer to receive input */
2281 int size; /* length of buffer */
2283 int oldphase = phase; /* we don't have to be re-entrant */
2285 phase = SERVER_WAIT;
2286 if (SockRead(sock, buf, size) == -1)
2293 if (buf[strlen(buf)-1] == '\n')
2294 buf[strlen(buf)-1] = '\0';
2295 if (buf[strlen(buf)-1] == '\r')
2296 buf[strlen(buf)-1] = '\r';
2297 if (outlevel == O_VERBOSE)
2298 error(0, 0, "%s< %s", protocol->name, buf);
2304 #if defined(HAVE_STDARG_H)
2305 int gen_transact(int sock, char *fmt, ... )
2306 /* assemble command in printf(3) style, send to server, accept a response */
2308 int gen_transact(int sock, fmt, va_alist)
2309 /* assemble command in printf(3) style, send to server, accept a response */
2310 int sock; /* socket to which server is connected */
2311 const char *fmt; /* printf-style format */
2316 char buf [POPBUFSIZE+1];
2318 int oldphase = phase; /* we don't have to be re-entrant */
2320 phase = SERVER_WAIT;
2322 if (protocol->tagged)
2323 (void) sprintf(buf, "%s ", GENSYM);
2327 #if defined(HAVE_STDARG_H)
2332 #ifdef HAVE_VSNPRINTF
2333 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2335 vsprintf(buf + strlen(buf), fmt, ap);
2339 strcat(buf, "\r\n");
2340 SockWrite(sock, buf, strlen(buf));
2342 if (outlevel == O_VERBOSE)
2346 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2350 sp = cp + strlen(shroud);
2356 buf[strlen(buf)-1] = '\0';
2357 error(0, 0, "%s> %s", protocol->name, buf);
2360 /* we presume this does its own response echoing */
2361 ok = (protocol->parse_response)(sock, buf);
2362 set_timeout(mytimeout);
2368 /* driver.c ends here */