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 #ifdef HAVE_GETHOSTBYNAME
44 #endif /* HAVE_GETHOSTBYNAME */
47 #if defined (__bsdi__)
48 #include <des.h> /* order of includes matters */
50 #define krb_get_err_text(e) (krb_err_txt[e])
52 #if defined(__FreeBSD__) || defined(__linux__)
53 #define krb_get_err_text(e) (krb_err_txt[e])
59 #endif /* ! defined (__FreeBSD__) */
60 #endif /* ! defined (__bsdi__) */
61 #include <netinet/in.h>
63 #endif /* KERBEROS_V4 */
64 #include "fetchmail.h"
68 /* BSD portability hack...I know, this is an ugly place to put it */
69 #if !defined(SIGCHLD) && defined(SIGCLD)
70 #define SIGCHLD SIGCLD
73 #define SMTP_PORT 25 /* standard SMTP service port */
75 #ifndef strstr /* glibc-2.1 declares this as a macro */
76 extern char *strstr(); /* needed on sysV68 R3V7.1. */
79 int fetchlimit; /* how often to tear down the server connection */
80 int batchcount; /* count of messages sent in current batch */
81 flag peek_capable; /* can we peek for better error recovery? */
82 int pass; /* how many times have we re-polled? */
84 static const struct method *protocol;
85 static jmp_buf restart;
89 #define GENSYM (sprintf(tag, "a%04d", ++tagnum % TAGMOD), tag)
91 static char *shroud; /* string to shroud in debug output, if non-NULL */
92 static int mytimeout; /* value of nonreponse timeout */
93 static int msglen; /* actual message length */
95 static void set_timeout(int timeleft)
96 /* reset the nonresponse-timeout */
98 struct itimerval ntimeout;
100 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
101 ntimeout.it_value.tv_sec = timeleft;
102 ntimeout.it_value.tv_usec = 0;
103 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
106 static void timeout_handler (int signal)
107 /* handle server-timeout SIGALRM signal */
112 #define XMIT_ACCEPT 1
113 #define XMIT_REJECT 2
114 #define XMIT_ANTISPAM 3
115 static int accept_count, reject_count;
119 static int is_host_alias(const char *name, struct query *ctl)
120 /* determine whether name is a DNS alias of the hostname */
123 struct mxentry *mxp, *mxrecords;
125 struct hostdata *lead_server =
126 ctl->server.lead_server ? ctl->server.lead_server : &ctl->server;
129 * The first two checks are optimizations that will catch a good
132 * (1) check against the `true name' deduced from the poll label
133 * and the via option (if present) at the beginning of the poll cycle.
134 * Odds are good this will either be the mailserver's FQDN or a suffix of
135 * it with the mailserver's domain's default host name omitted.
137 * (2) Then check the rest of the `also known as'
138 * cache accumulated by previous DNS checks. This cache is primed
139 * by the aka list option.
141 * Any of these on a mail address is definitive. Only if the
142 * name doesn't match any is it time to call the bind library.
143 * If this happens odds are good we're looking at an MX name.
145 if (strcmp(lead_server->truename, name) == 0)
147 else if (str_in_list(&lead_server->akalist, name))
149 else if (!ctl->server.dns)
152 #ifndef HAVE_RES_SEARCH
156 * The only code that calls the BIND library is here and in the
157 * start-of-query probe with gethostbyname(3).
159 * We know DNS service was up at the beginning of this poll cycle.
160 * If it's down, our nameserver has crashed. We don't want to try
161 * delivering the current message or anything else from this
162 * mailbox until it's back up.
164 else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
166 if (strcmp(ctl->server.truename, he->h_name) == 0)
174 case HOST_NOT_FOUND: /* specified host is unknown */
175 case NO_ADDRESS: /* valid, but does not have an IP address */
178 case NO_RECOVERY: /* non-recoverable name server error */
179 case TRY_AGAIN: /* temporary error on authoritative server */
181 if (outlevel != O_SILENT)
182 putchar('\n'); /* terminate the progress message */
184 "nameserver failure while looking for `%s' during poll of %s.",
185 name, ctl->server.pollname);
191 * We're only here if DNS was OK but the gethostbyname() failed
192 * with a HOST_NOT_FOUND or NO_ADDRESS error.
193 * Search for a name match on MX records pointing to the server.
196 if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
200 case HOST_NOT_FOUND: /* specified host is unknown */
201 case NO_ADDRESS: /* valid, but does not have an IP address */
205 case NO_RECOVERY: /* non-recoverable name server error */
206 case TRY_AGAIN: /* temporary error on authoritative server */
209 "nameserver failure while looking for `%s' during poll of %s.",
210 name, ctl->server.pollname);
217 for (mxp = mxrecords; mxp->name; mxp++)
218 if (strcmp(ctl->server.truename, mxp->name) == 0)
224 /* add this name to relevant server's `also known as' list */
225 save_str(&lead_server->akalist, -1, name);
227 #endif /* HAVE_RES_SEARCH */
230 static void map_name(name, ctl, xmit_names)
231 /* add given name to xmit_names if it matches declared localnames */
232 const char *name; /* name to map */
233 struct query *ctl; /* list of permissible aliases */
234 struct idlist **xmit_names; /* list of recipient names parsed out */
240 lname = idpair_find(&ctl->localnames, name);
241 if (!lname && ctl->wildcard)
244 if (lname != (char *)NULL)
247 * If the name of the user begins with a
248 * qmail virtual domain prefix, remove
251 if (ctl->server.qvirtual)
253 sl=strlen(ctl->server.qvirtual);
254 if (!strncasecmp(lname,ctl->server.qvirtual,sl)) off=sl;
256 if (outlevel == O_VERBOSE)
257 error(0, 0, "mapped %s to local %s", name, lname+off);
258 save_str(xmit_names, XMIT_ACCEPT, lname+off);
263 void find_server_names(hdr, ctl, xmit_names)
264 /* parse names out of a RFC822 header into an ID list */
265 const char *hdr; /* RFC822 header in question */
266 struct query *ctl; /* list of permissible aliases */
267 struct idlist **xmit_names; /* list of recipient names parsed out */
269 if (hdr == (char *)NULL)
275 if ((cp = nxtaddr(hdr)) != (char *)NULL)
279 if ((atsign = strchr(cp, '@')))
284 * Does a trailing segment of the hostname match something
285 * on the localdomains list? If so, save the whole name
288 for (idp = ctl->server.localdomains; idp; idp = idp->next)
292 rhs = atsign + (strlen(atsign) - strlen(idp->id));
293 if ((rhs[-1] == '.' || rhs[-1] == '@')
294 && strcasecmp(rhs, idp->id) == 0)
296 if (outlevel == O_VERBOSE)
297 error(0, 0, "passed through %s matching %s",
299 save_str(xmit_names, XMIT_ACCEPT, cp);
306 * Check to see if the right-hand part is an alias
307 * or MX equivalent of the mailserver. If it's
308 * not, skip this name. If it is, we'll keep
309 * going and try to find a mapping to a client name.
311 if (!is_host_alias(atsign+1, ctl))
313 save_str(xmit_names, XMIT_REJECT, cp);
320 map_name(cp, ctl, xmit_names);
322 ((cp = nxtaddr((char *)NULL)) != (char *)NULL);
326 static char *parse_received(struct query *ctl, char *bufp)
327 /* try to extract real addressee from the Received line */
329 char *ok = (char *)NULL;
330 static char rbuf[HOSTLEN + USERNAMELEN + 4];
333 * Try to extract the real envelope addressee. We look here
334 * specifically for the mailserver's Received line.
335 * Note: this will only work for sendmail, or an MTA that
336 * shares sendmail's convention for embedding the envelope
337 * address in the Received line. Sendmail itself only
338 * does this when the mail has a single recipient.
340 if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
344 /* extract space-delimited token after "by " */
345 for (sp = ok + 3; isspace(*sp); sp++)
348 for (; !isspace(*sp); sp++)
353 * If it's a DNS name of the mail server, look for the
354 * recipient name after a following "for". Otherwise
357 if (!is_host_alias(rbuf, ctl))
359 else if ((ok = strstr(sp, "for ")) && isspace(ok[-1]))
365 while (*sp == '@') /* skip routes */
368 while (*sp && *sp != '>' && *sp != '@' && *sp != ';')
373 /* uh oh -- whitespace here can't be right! */
385 if (outlevel == O_VERBOSE)
386 error(0, 0, "found Received address `%s'", rbuf);
391 static int smtp_open(struct query *ctl)
392 /* try to open a socket to the appropriate SMTP server for this query */
394 /* maybe it's time to close the socket in order to force delivery */
395 if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
397 close(ctl->smtp_socket);
398 ctl->smtp_socket = -1;
402 /* if no socket to any SMTP host is already set up, try to open one */
403 if (ctl->smtp_socket == -1)
406 * RFC 1123 requires that the domain name in HELO address is a
407 * "valid principal domain name" for the client host. If we're
408 * running in invisible mode, violate this with malice
409 * aforethought in order to make the Received headers and
410 * logging look right.
412 * In fact this code relies on the RFC1123 requirement that the
413 * SMTP listener must accept messages even if verification of the
414 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
416 * How we compute the true mailhost name to pass to the
417 * listener doesn't affect behavior on RFC1123- violating
418 * listener that check for name match; we're going to lose
419 * on those anyway because we can never give them a name
420 * that matches the local machine fetchmail is running on.
421 * What it will affect is the listener's logging.
424 char *id_me = use_invisible ? ctl->server.truename : fetchmailhost;
429 * Run down the SMTP hunt list looking for a server that's up.
430 * Use both explicit hunt entries (value TRUE) and implicit
431 * (default) ones (value FALSE).
433 for (idp = ctl->smtphunt; idp; idp = idp->next)
435 ctl->smtphost = idp->id; /* remember last host tried. */
437 if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
440 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
441 SMTP_ehlo(ctl->smtp_socket, id_me,
442 &ctl->server.esmtp_options) == SM_OK)
446 * RFC 1869 warns that some listeners hang up on a failed EHLO,
447 * so it's safest not to assume the socket will still be good.
449 close(ctl->smtp_socket);
450 ctl->smtp_socket = -1;
452 /* if opening for ESMTP failed, try SMTP */
453 if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
456 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
457 SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
460 close(ctl->smtp_socket);
461 ctl->smtp_socket = -1;
465 if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
466 error(0, 0, "forwarding to SMTP port on %s", ctl->smtphost);
468 return(ctl->smtp_socket);
471 /* these are shared by stuffline, readheaders and readbody */
473 static RETSIGTYPE (*sigchld)();
474 static int sizeticker;
476 static int stuffline(struct query *ctl, char *buf)
477 /* ship a line to the given control block's output sink (SMTP server or MDA) */
482 /* The line may contain NUL characters. Find the last char to use
483 * -- the real line termination is the sequence "\n\0".
486 while ((last += strlen(last)) && (last[-1] != '\n'))
489 /* fix message lines that have only \n termination (for qmail) */
492 if (last - 1 == buf || last[-2] != '\r')
501 * SMTP byte-stuffing. We only do this if the protocol does *not*
502 * use .<CR><LF> as EOM. If it does, the server will already have
503 * decorated any . lines it sends back up.
506 if (protocol->delimited) /* server has already byte-stuffed */
511 /* writing to SMTP, leave the byte-stuffing in place */;
513 else /* if (!protocol->delimited) -- not byte-stuffed already */
516 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
518 /* leave it alone */;
521 /* we may need to strip carriage returns */
526 for (sp = tp = buf; sp < last; sp++)
535 n = fwrite(buf, 1, last - buf, sinkfp);
536 else if (ctl->smtp_socket != -1)
537 n = SockWrite(ctl->smtp_socket, buf, last - buf);
542 static int readheaders(sock, fetchlen, reallen, ctl, num)
543 /* read message headers and ship to SMTP or MDA */
544 int sock; /* to which the server is connected */
545 long fetchlen; /* length of message according to fetch response */
546 long reallen; /* length of message according to getsizes */
547 struct query *ctl; /* query control record */
548 int num; /* index of message */
553 struct addrblk *next;
554 } *addrchain = NULL, **chainptr = &addrchain;
555 char buf[MSGBUFSIZE+1], return_path[MSGBUFSIZE+1];
556 int from_offs, ctt_offs, env_offs, next_address;
557 char *headers, *received_for, *destaddr, *rcv;
558 int n, linelen, oldlen, ch, remaining, skipcount;
560 struct idlist *idp, *xmit_names;
561 flag good_addresses, bad_addresses, has_nuls;
562 flag no_local_matches = FALSE;
565 next_address = sizeticker = 0;
567 return_path[0] = '\0';
568 olderrs = ctl->errcount;
570 /* read message headers */
571 headers = received_for = NULL;
572 from_offs = ctt_offs = env_offs = -1;
577 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
581 line = xmalloc(sizeof(buf));
585 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1)
590 /* lines may not be properly CRLF terminated; fix this for qmail */
593 cp = buf + strlen(buf) - 1;
594 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
602 set_timeout(ctl->server.timeout);
604 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
607 if (line[0] == '\r' && line[1] == '\n')
610 /* we may need to grab RFC822 continuations */
611 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
613 /* write the message size dots */
614 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
616 sizeticker += linelen;
617 while (sizeticker >= SIZETICKER)
620 sizeticker -= SIZETICKER;
624 if (linelen != strlen(line))
627 /* check for end of headers; don't save terminating line */
628 if (line[0] == '\r' && line[1] == '\n')
635 * The University of Washington IMAP server (the reference
636 * implementation of IMAP4 written by Mark Crispin) relies
637 * on being able to keep base-UID information in a special
638 * message at the head of the mailbox. This message should
639 * neither be deleted nor forwarded.
643 * We disable this check under POP2 because there's no way to
644 * prevent deletion of the message. So at least we ought to
645 * forward it to the user so he or she will have some clue
646 * that things have gone awry.
648 if (protocol->port != 109)
649 #endif /* POP2_ENABLE */
650 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7))
654 * This code prevents fetchmail from becoming an accessory after
655 * the fact to upstream sendmails with the `E' option on. This
656 * can result in an escaped Unix From_ line at the beginning of
657 * the headers. If fetchmail just passes it through, the client
658 * listener may think the message has *no* headers (since the first)
659 * line it sees doesn't look RFC822-conformant) and fake up a set.
661 * What the user would see in this case is bogus (synthesized)
662 * headers, followed by a blank line, followed by the >From,
663 * followed by the real headers, followed by a blank line,
666 * We forestall this lossage by tossing anything that looks
667 * like an escaped From_ line in headers. These aren't RFC822
668 * so our conscience is clear...
670 if (!strncasecmp(line, ">From ", 6))
677 * If we see a Status line, it may have been inserted by an MUA
678 * on the mail host, or it may have been inserted by the server
679 * program after the headers in the transaction stream. This
680 * can actually hose some new-mail notifiers such as xbuffy,
681 * which assumes any Status line came from a *local* MDA and
682 * therefore indicates that the message has been seen.
684 * Some buggy POP servers (including at least the 3.3(20)
685 * version of the one distributed with IMAP) insert empty
686 * Status lines in the transaction stream; we'll chuck those
687 * unconditionally. Nonempty ones get chucked if the user
688 * turns on the dropstatus flag.
690 if (!strncasecmp(line, "Status:", 7))
694 for (cp = line + 7; *cp && isspace(*cp); cp++)
697 if (!*cp || ctl->dropstatus)
705 * OK, this is messy. If we're forwarding by SMTP, it's the
706 * SMTP-receiver's job (according to RFC821, page 22, section
707 * 4.1.1) to generate a Return-Path line on final delivery.
708 * The trouble is, we've already got one because the
709 * mailserver's SMTP thought *it* was responsible for final
712 * Stash away the contents of Return-Path for use in generating
713 * MAIL FROM later on, then prevent the header from being saved
714 * with the others. In effect, we strip it off here.
716 * If the SMTP server conforms to the standards, and fetchmail gets the
717 * envelope sender from the Return-Path, the new Return-Path should be
718 * exactly the same as the original one.
720 if (!ctl->mda && !strncasecmp("Return-Path:", line, 12))
722 strcpy(return_path, nxtaddr(line));
728 line = reply_hack(line, ctl->server.truename);
732 oldlen = strlen(line);
733 headers = xmalloc(oldlen + 1);
734 (void) strcpy(headers, line);
742 newlen = oldlen + strlen(line);
743 headers = (char *) realloc(headers, newlen + 1);
746 strcpy(headers + oldlen, line);
748 line = headers + oldlen;
752 if (from_offs == -1 && !strncasecmp("From:", line, 5))
753 from_offs = (line - headers);
754 else if (from_offs == -1 && !strncasecmp("Resent-From:", line, 12))
755 from_offs = (line - headers);
756 else if (from_offs == -1 && !strncasecmp("Apparently-From:", line, 16))
757 from_offs = (line - headers);
758 else if (!strncasecmp("Content-Transfer-Encoding:", line, 26))
759 ctt_offs = (line - headers);
760 else if (!strncasecmp("Message-Id:", buf, 11 ))
762 if( ctl->server.uidl )
765 /* prevent stack overflows */
767 sscanf( buf+12, "%s", id);
768 if( !str_find( &ctl->newsaved, num ) )
769 save_str(&ctl->newsaved, num, id );
773 else if (!MULTIDROP(ctl))
776 else if (!strncasecmp("To:", line, 3)
777 || !strncasecmp("Cc:", line, 3)
778 || !strncasecmp("Bcc:", line, 4))
780 *chainptr = xmalloc(sizeof(struct addrblk));
781 (*chainptr)->offset = (line - headers);
782 chainptr = &(*chainptr)->next;
786 else if (ctl->server.envelope != STRING_DISABLED)
788 if (ctl->server.envelope
789 && strcasecmp(ctl->server.envelope, "received"))
791 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
793 strlen(ctl->server.envelope)))
795 if (skipcount++ != ctl->server.envskip)
797 env_offs = (line - headers);
800 else if (!received_for && !strncasecmp("Received:", line, 9))
802 if (skipcount++ != ctl->server.envskip)
804 received_for = parse_received(ctl, line);
810 * Hack time. If the first line of the message was blank, with no headers
811 * (this happens occasionally due to bad gatewaying software) cons up
812 * a set of fake headers.
814 * If you modify the fake header template below, be sure you don't
815 * make either From or To address @-less, otherwise the reply_hack
816 * logic will do bad things.
818 if (headers == (char *)NULL)
821 snprintf(buf, sizeof(buf),
824 #endif /* HAVE_SNPRINTF */
825 "From: <FETCHMAIL-DAEMON@%s>\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
826 fetchmailhost, user, ctl->remotename, ctl->server.truename);
827 headers = xstrdup(buf);
831 * We can now process message headers before reading the text.
832 * In fact we have to, as this will tell us where to forward to.
835 /* cons up a list of local recipients */
836 xmit_names = (struct idlist *)NULL;
837 bad_addresses = good_addresses = accept_count = reject_count = 0;
838 /* is this a multidrop box? */
841 if (env_offs > -1) /* We have the actual envelope addressee */
842 find_server_names(headers + env_offs, ctl, &xmit_names);
843 else if (received_for)
845 * We have the Received for addressee.
846 * It has to be a mailserver address, or we
847 * wouldn't have got here.
849 map_name(received_for, ctl, &xmit_names);
853 * We haven't extracted the envelope address.
854 * So check all the header addresses.
858 register struct addrblk *nextptr;
860 find_server_names(headers+addrchain->offset, ctl, &xmit_names);
861 nextptr = addrchain->next;
868 no_local_matches = TRUE;
869 save_str(&xmit_names, XMIT_ACCEPT, user);
870 if (outlevel == O_VERBOSE)
872 "no local matches, forwarding to %s",
876 else /* it's a single-drop box, use first localname */
877 save_str(&xmit_names, XMIT_ACCEPT, ctl->localnames->id);
881 * Time to either address the message or decide we can't deliver it yet.
883 if (ctl->errcount > olderrs) /* there were DNS errors above */
885 if (outlevel == O_VERBOSE)
886 error(0,0, "forwarding and deletion suppressed due to DNS errors");
888 return(PS_TRANSIENT);
890 else if (ctl->mda) /* we have a declared MDA */
893 char *names, *before, *after;
895 for (idp = xmit_names; idp; idp = idp->next)
896 if (idp->val.num == XMIT_ACCEPT)
899 destaddr = "localhost";
901 length = strlen(ctl->mda) + 1;
902 before = xstrdup(ctl->mda);
904 /* sub user addresses for %T (or %s for backward compatibility) */
906 if (strstr(before, "%s") || (cp = strstr(before, "%T")))
910 if (cp && cp[1] == 'T')
913 /* \177 had better be out-of-band for MDA commands */
914 for (sp = before; *sp; sp++)
915 if (*sp == '%' && sp[1] != 's' && sp[1] != 'T')
919 * We go through this in order to be able to handle very
920 * long lists of users and (re)implement %s.
922 for (idp = xmit_names; idp; idp = idp->next)
923 if (idp->val.num == XMIT_ACCEPT)
924 length += (strlen(idp->id) + 1);
926 names = (char *)xmalloc(++length);
928 for (idp = xmit_names; idp; idp = idp->next)
929 if (idp->val.num == XMIT_ACCEPT)
931 strcat(names, idp->id);
934 after = (char *)xmalloc(length);
936 snprintf(after, length, before, names);
938 sprintf(after, before, names);
939 #endif /* SNPRINTF */
944 for (sp = before; *sp; sp++)
949 /* substitute From address for %F */
950 if ((cp = strstr(before, "%F")))
952 char *from = nxtaddr(headers + from_offs);
955 /* \177 had better be out-of-band for MDA commands */
956 for (sp = before; *sp; sp++)
957 if (*sp == '%' && sp[1] != 'F')
960 length += strlen(from);
961 after = (char *)xmalloc(length);
964 snprintf(after, length, before, from);
966 sprintf(after, before, from);
967 #endif /* SNPRINTF */
971 for (sp = before; *sp; sp++)
976 if (outlevel == O_VERBOSE)
977 error(0, 0, "about to deliver with: %s", before);
981 * Arrange to run with user's permissions if we're root.
982 * This will initialize the ownership of any files the
983 * MDA creates properly. (The seteuid call is available
984 * under all BSDs and Linux)
987 #endif /* HAVE_SETEUID */
989 sinkfp = popen(before, "w");
993 /* this will fail quietly if we didn't start as root */
995 #endif /* HAVE_SETEUID */
999 error(0, 0, "MDA open failed");
1003 sigchld = signal(SIGCHLD, SIG_DFL);
1007 char *ap, *ctt, options[MSGBUFSIZE], addr[128];
1009 /* build a connection to the SMTP listener */
1010 if ((smtp_open(ctl) == -1))
1012 error(0, errno, "SMTP connect to %s failed",
1013 ctl->smtphost ? ctl->smtphost : "localhost");
1014 free_str_list(&xmit_names);
1019 * Compute ESMTP options. It's a kluge to use nxtaddr()
1020 * here because the contents of the Content-Transfer-Encoding
1021 * headers isn't semantically an address. But it has the
1022 * desired tokenizing effect.
1025 if (ctl->server.esmtp_options & ESMTP_8BITMIME)
1027 strcpy(options, " BODY=8BITMIME");
1028 else if ((ctt_offs >= 0) && (ctt = nxtaddr(headers + ctt_offs)))
1030 if (!strcasecmp(ctt,"7BIT"))
1031 strcpy(options, " BODY=7BIT");
1032 else if (!strcasecmp(ctt,"8BIT"))
1033 strcpy(options, " BODY=8BITMIME");
1035 if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
1036 sprintf(options + strlen(options), " SIZE=%ld", reallen);
1039 * If there is a Return-Path address on the message, this was
1040 * almost certainly the MAIL FROM address given the originating
1041 * sendmail. This is the best thing to use for logging the
1042 * message origin (it sets up the right behavior for bounces and
1043 * mailing lists). Otherwise, take the From address.
1045 * Try to get the SMTP listener to take the Return-Path or
1046 * From address as MAIL FROM . If it won't, fall back on the
1047 * calling-user ID. This won't affect replies, which use the
1048 * header From address anyway.
1050 * RFC 1123 requires that the domain name part of the
1051 * MAIL FROM address be "canonicalized", that is a
1052 * FQDN or MX but not a CNAME. We'll assume the From
1053 * header is already in this form here (it certainly
1054 * is if rewrite is on). RFC 1123 is silent on whether
1055 * a nonexistent hostname part is considered canonical.
1057 * This is a potential problem if the MTAs further upstream
1058 * didn't pass canonicalized From/Return-Path lines, *and* the
1059 * local SMTP listener insists on them.
1064 else if (from_offs == -1 || !(ap = nxtaddr(headers + from_offs)))
1066 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
1068 int smtperr = atoi(smtp_response);
1071 * Suppress error message only if the response specifically
1072 * means `excluded for policy reasons'. We *should* see
1073 * an error when the return code is less specific.
1075 if (smtperr >= 400 && smtperr != 571)
1076 error(0, -1, "SMTP error: %s", smtp_response);
1080 case 571: /* sendmail's "unsolicited email refused" */
1081 case 501: /* exim's old antispam response */
1082 case 550: /* exim's new antispam response (temporary) */
1084 * SMTP listener explicitly refuses to deliver
1085 * mail coming from this address, probably due
1086 * to an anti-spam domain exclusion. Respect
1087 * this. Don't try to ship the message, and
1088 * don't prevent it from being deleted.
1093 case 452: /* insufficient system storage */
1095 * Temporary out-of-queue-space condition on the
1096 * ESMTP server. Don't try to ship the message,
1097 * and suppress deletion so it can be retried on
1098 * a future retrieval cycle.
1100 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1102 return(PS_TRANSIENT);
1104 case 552: /* message exceeds fixed maximum message size */
1106 * Permanent no-go condition on the
1107 * ESMTP server. Don't try to ship the message,
1108 * and allow it to be deleted.
1110 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1114 default: /* retry with invoking user's address */
1115 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1117 error(0, -1, "SMTP error: %s", smtp_response);
1119 return(PS_SMTP); /* should never happen */
1125 * Now list the recipient addressees
1127 * RFC 1123 requires that the domain name part of the
1128 * RCPT TO address be "canonicalized", that is a FQDN
1129 * or MX but not a CNAME. Some listeners (like exim)
1132 destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
1134 for (idp = xmit_names; idp; idp = idp->next)
1135 if (idp->val.num == XMIT_ACCEPT)
1137 if (strchr(idp->id, '@'))
1138 strcpy(addr, idp->id);
1140 #ifdef HAVE_SNPRINTF
1141 snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, destaddr);
1143 sprintf(addr, "%s@%s", idp->id, destaddr);
1144 #endif /* HAVE_SNPRINTF */
1146 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1151 idp->val.num = XMIT_ANTISPAM;
1153 "SMTP listener doesn't like recipient address `%s@%s'", idp->id, destaddr);
1156 if (!good_addresses)
1158 #ifdef HAVE_SNPRINTF
1159 snprintf(addr, sizeof(addr)-1, "%s@%s", user, destaddr);
1161 sprintf(addr, "%s@%s", user, destaddr);
1162 #endif /* HAVE_SNPRINTF */
1164 if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1166 error(0, 0, "can't even send to calling user!");
1172 /* tell it we're ready to send data */
1173 SMTP_data(ctl->smtp_socket);
1178 * Some server/sendmail combinations cause problems when our
1179 * synthetic Received line is before the From header. Cope
1182 if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
1187 n = stuffline(ctl, headers);
1190 if (!use_invisible && n != -1)
1192 /* utter any per-message Received information we need here */
1193 sprintf(buf, "Received: from %s\n", ctl->server.truename);
1194 n = stuffline(ctl, buf);
1198 * We used to include ctl->remotename in this log line,
1199 * but this can be secure information that would be bad
1202 sprintf(buf, "\tby %s (fetchmail-%s %s)\n",
1206 n = stuffline(ctl, buf);
1212 if (good_addresses == 0)
1215 "for <%s@%s> (by default); ",
1218 else if (good_addresses == 1)
1220 for (idp = xmit_names; idp; idp = idp->next)
1221 if (idp->val.num == XMIT_ACCEPT)
1222 break; /* only report first address */
1223 sprintf(buf+1, "for <%s@%s> (%s); ",
1225 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1231 #ifdef HAVE_STRFTIME
1233 * Conform to RFC822. This is typically going to emit
1234 * a three-letter timezone for %Z, which is going to
1235 * be marked "obsolete syntax" in 822bis. Note that we
1236 * generate a 4-digit year here.
1238 strftime(buf + strlen(buf), sizeof(buf) - strlen(buf),
1239 "%a, %d %b %Y %H:%M:%S %Z\n", localtime(&now));
1242 * This is really just a portability fallback, as the
1243 * date format ctime(3) emits is not RFC822
1246 strcat(buf, ctime(&now));
1247 #endif /* HAVE_STRFTIME */
1248 n = stuffline(ctl, buf);
1254 n = stuffline(ctl, rcv); /* ship out rest of headers */
1258 error(0, errno, "writing RFC822 headers");
1263 signal(SIGCHLD, sigchld);
1267 else if (outlevel == O_VERBOSE)
1270 /* write error notifications */
1271 if (no_local_matches || has_nuls || bad_addresses)
1274 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1277 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1278 if (no_local_matches)
1280 if (reject_count != 1)
1281 strcat(errhd, "no recipient addresses matched declared local names");
1284 for (idp = xmit_names; idp; idp = idp->next)
1285 if (idp->val.num == XMIT_REJECT)
1287 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1293 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1294 strcat(errhd, "; ");
1295 strcat(errhd, "message has embedded NULs");
1300 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1301 strcat(errhd, "; ");
1302 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1303 errlen = strlen(errhd);
1304 for (idp = xmit_names; idp; idp = idp->next)
1305 if (idp->val.num == XMIT_ANTISPAM)
1306 errlen += strlen(idp->id) + 2;
1308 errmsg = alloca(errlen+3);
1309 (void) strcpy(errmsg, errhd);
1310 for (idp = xmit_names; idp; idp = idp->next)
1311 if (idp->val.num == XMIT_ANTISPAM)
1313 strcat(errmsg, idp->id);
1315 strcat(errmsg, ", ");
1320 strcat(errmsg, "\n");
1322 /* ship out the error line */
1324 stuffline(ctl, errmsg);
1327 free_str_list(&xmit_names);
1329 /* issue the delimiter line */
1334 stuffline(ctl, buf);
1339 static int readbody(sock, ctl, forward, len)
1340 /* read and dispose of a message body presented on sock */
1341 struct query *ctl; /* query control record */
1342 int sock; /* to which the server is connected */
1343 int len; /* length of message */
1344 flag forward; /* TRUE to forward */
1347 char buf[MSGBUFSIZE+1];
1349 /* pass through the text lines */
1350 while (protocol->delimited || len > 0)
1352 if ((linelen = SockRead(sock, buf, sizeof(buf)-1)) == -1)
1358 signal(SIGCHLD, sigchld);
1362 set_timeout(ctl->server.timeout);
1364 /* write the message size dots */
1367 sizeticker += linelen;
1368 while (sizeticker >= SIZETICKER)
1370 if (outlevel > O_SILENT)
1372 sizeticker -= SIZETICKER;
1377 /* check for end of message */
1378 if (protocol->delimited && *buf == '.')
1379 if (buf[1] == '\r' && buf[2] == '\n' && buf[3] == '\0')
1381 else if (buf[1] == '\n' && buf[2] == '\0')
1384 msglen--; /* subtract the size of the dot escape */
1388 /* ship out the text line */
1391 int n = stuffline(ctl, buf);
1395 error(0, errno, "writing message text");
1400 signal(SIGCHLD, sigchld);
1404 else if (outlevel == O_VERBOSE)
1414 kerberos_auth (socket, canonical)
1415 /* authenticate to the server host using Kerberos V4 */
1416 int socket; /* socket to server host */
1418 char *canonical; /* server name */
1420 const char *canonical; /* server name */
1423 char * host_primary;
1427 Key_schedule schedule;
1430 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1431 rem = (krb_sendauth (0L, socket, ticket, "pop",
1433 ((char *) (krb_realmofhost (canonical))),
1434 ((unsigned long) 0),
1438 ((struct sockaddr_in *) 0),
1439 ((struct sockaddr_in *) 0),
1442 if (rem != KSUCCESS)
1444 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1445 return (PS_AUTHFAIL);
1449 #endif /* KERBEROS_V4 */
1451 int do_protocol(ctl, proto)
1452 /* retrieve messages from server using given protocol method table */
1453 struct query *ctl; /* parsed options with merged-in defaults */
1454 const struct method *proto; /* protocol method table */
1456 int ok, js, sock = -1;
1461 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1463 error(0, -1, "Kerberos V4 support not linked.");
1466 #endif /* KERBEROS_V4 */
1468 /* lacking methods, there are some options that may fail */
1471 /* check for unsupported options */
1474 "Option --flush is not supported with %s",
1478 else if (ctl->fetchall) {
1480 "Option --all is not supported with %s",
1485 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1488 "Option --limit is not supported with %s",
1496 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1499 /* set up the server-nonresponse timeout */
1500 sigsave = signal(SIGALRM, timeout_handler);
1501 set_timeout(mytimeout = ctl->server.timeout);
1503 if ((js = setjmp(restart)) == 1)
1506 "timeout after %d seconds waiting for %s.",
1507 ctl->server.timeout, ctl->server.pollname);
1508 if (ctl->smtp_socket != -1)
1509 close(ctl->smtp_socket);
1516 char buf [POPBUFSIZE+1], *realhost;
1517 int *msgsizes, len, num, count, new, deletions = 0;
1518 int port, fetches, dispatches;
1521 /* execute pre-initialization command, if any */
1522 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1524 sprintf(buf, "pre-connection command failed with status %d", ok);
1530 /* open a socket to the mail server */
1531 port = ctl->server.port ? ctl->server.port : protocol->port;
1532 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1533 if ((sock = SockOpen(realhost, port)) == -1)
1535 #ifndef EHOSTUNREACH
1536 #define EHOSTUNREACH (-1)
1538 if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1540 error_build("fetchmail: %s connection to %s failed: ",
1541 protocol->name, ctl->server.pollname);
1542 if (h_errno == HOST_NOT_FOUND)
1543 error_complete(0, 0, "host is unknown");
1544 else if (h_errno == NO_ADDRESS)
1545 error_complete(0, 0, "name is valid but has no IP address");
1546 else if (h_errno == NO_RECOVERY)
1547 error_complete(0, 0, "unrecoverable name server error");
1548 else if (h_errno == TRY_AGAIN)
1549 error_complete(0, 0, "temporary name server error");
1551 error_complete(0, 0, "unknown DNS error %d", h_errno);
1553 error_complete(0, errno, "local error");
1560 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1562 ok = kerberos_auth(sock, ctl->server.truename);
1565 set_timeout(ctl->server.timeout);
1567 #endif /* KERBEROS_V4 */
1569 /* accept greeting message from mail server */
1570 ok = (protocol->parse_response)(sock, buf);
1573 set_timeout(ctl->server.timeout);
1575 /* try to get authorized to fetch mail */
1576 if (protocol->getauth)
1578 shroud = ctl->password;
1579 ok = (protocol->getauth)(sock, ctl, buf);
1580 shroud = (char *)NULL;
1583 if (ok == PS_LOCKBUSY)
1584 error(0, -1, "Lock-busy error on %s@%s",
1586 ctl->server.truename);
1591 error(0, -1, "Authorization failure on %s@%s",
1593 ctl->server.truename);
1597 set_timeout(ctl->server.timeout);
1600 ctl->errcount = fetches = 0;
1602 /* now iterate over each folder selected */
1603 for (idp = ctl->mailboxes; idp; idp = idp->next)
1610 if (outlevel >= O_VERBOSE)
1612 error(0, 0, "selecting or re-polling folder %s", idp->id);
1614 error(0, 0, "selecting or re-polling default folder");
1616 /* compute # of messages and number of new messages waiting */
1617 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new);
1620 set_timeout(ctl->server.timeout);
1622 /* show user how many messages we downloaded */
1624 (void) sprintf(buf, "%s at %s (folder %s)",
1625 ctl->remotename, ctl->server.truename, idp->id);
1627 (void) sprintf(buf, "%s at %s", ctl->remotename, ctl->server.truename);
1628 if (outlevel > O_SILENT)
1629 if (count == -1) /* only used for ETRN */
1630 error(0, 0, "Polling %s", ctl->server.truename);
1631 else if (count != 0)
1633 if (new != -1 && (count - new) > 0)
1634 error(0, 0, "%d message%s (%d seen) for %s.",
1635 count, count > 1 ? "s" : "", count-new, buf);
1637 error(0, 0, "%d message%s for %s.",
1638 count, count > 1 ? "s" : "", buf);
1642 /* these are pointless in normal daemon mode */
1643 if (pass == 1 && (poll_interval == 0 || outlevel == O_VERBOSE))
1644 error(0, 0, "No mail for %s", buf);
1647 /* very important, this is where we leave the do loop */
1653 if (new == -1 || ctl->fetchall)
1655 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1660 flag force_retrieval;
1663 * What forces this code is that in POP3 and
1664 * IMAP2BIS you can't fetch a message without
1665 * having it marked `seen'. In IMAP4, on the
1666 * other hand, you can (peek_capable is set to
1669 * The result of being unable to peek is that if there's
1670 * any kind of transient error (DNS lookup failure, or
1671 * sendmail refusing delivery due to process-table limits)
1672 * the message will be marked "seen" on the server without
1673 * having been delivered. This is not a big problem if
1674 * fetchmail is running in foreground, because the user
1675 * will see a "skipped" message when it next runs and get
1678 * But in daemon mode this leads to the message
1679 * being silently ignored forever. This is not
1682 * We compensate for this by checking the error
1683 * count from the previous pass and forcing all
1684 * messages to be considered new if it's nonzero.
1686 force_retrieval = !peek_capable && (ctl->errcount > 0);
1689 * We need the size of each message before it's
1690 * loaded in order to pass via the ESMTP SIZE
1691 * option. If the protocol has a getsizes method,
1692 * we presume this means it doesn't get reliable
1693 * sizes from message fetch responses.
1695 if (proto->getsizes)
1699 msgsizes = (int *)alloca(sizeof(int) * count);
1700 for (i = 0; i < count; i++)
1703 ok = (proto->getsizes)(sock, count, msgsizes);
1706 set_timeout(ctl->server.timeout);
1709 /* read, forward, and delete messages */
1710 for (num = 1; num <= count; num++)
1712 flag toolarge = NUM_NONZERO(ctl->limit)
1713 && msgsizes && (msgsizes[num-1] > ctl->limit);
1714 flag fetch_it = !toolarge
1715 && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
1716 flag suppress_delete = FALSE;
1717 flag suppress_forward = FALSE;
1718 flag retained = FALSE;
1721 * This check copes with Post Office/NT's
1722 * annoying habit of randomly prepending bogus
1723 * LIST items of length -1. Patrick Audley
1724 * <paudley@pobox.com> tells us: LIST shows a
1725 * size of -1, RETR and TOP return "-ERR
1726 * System error - couldn't open message", and
1727 * DELE succeeds but doesn't actually delete
1730 if (msgsizes && msgsizes[num-1] == -1)
1732 if (outlevel >= O_VERBOSE)
1734 "Skipping message %d, length -1",
1739 /* we may want to reject this message if it's old */
1742 if (outlevel > O_SILENT)
1744 error_build("skipping message %d", num);
1746 error_build(" (oversized, %d bytes)",
1752 flag wholesize = !protocol->fetch_body;
1754 /* request a message */
1755 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1758 set_timeout(ctl->server.timeout);
1760 /* -1 means we didn't see a size in the response */
1761 if (len == -1 && msgsizes)
1763 len = msgsizes[num - 1];
1767 if (outlevel > O_SILENT)
1769 error_build("reading message %d of %d",
1773 error_build(" (%d %sbytes)",
1774 len, wholesize ? "" : "header ");
1775 if (outlevel == O_VERBOSE)
1776 error_complete(0, 0, "");
1781 /* later we'll test for this before closing */
1782 sinkfp = (FILE *)NULL;
1785 * Read the message headers and ship them to the
1788 ok = readheaders(sock, len, msgsizes[num-1],
1790 if (ok == PS_RETAINED)
1791 suppress_forward = retained = TRUE;
1792 else if (ok == PS_TRANSIENT)
1793 suppress_delete = suppress_forward = TRUE;
1794 else if (ok == PS_REFUSED)
1795 suppress_forward = TRUE;
1798 set_timeout(ctl->server.timeout);
1801 * If we're using IMAP4 or something else that
1802 * can fetch headers separately from bodies,
1803 * it's time to request the body now. This
1804 * fetch may be skipped if we got an anti-spam
1805 * or other PS_REFUSED error response during
1808 if (protocol->fetch_body)
1810 if (outlevel == O_VERBOSE)
1811 fputc('\n', stderr);
1813 if ((ok = (protocol->trail)(sock, ctl, num)))
1815 set_timeout(ctl->server.timeout);
1817 if (!suppress_forward)
1819 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1821 if (outlevel > O_SILENT && !wholesize)
1822 error_build(" (%d body bytes) ", len);
1823 set_timeout(ctl->server.timeout);
1827 /* process the body now */
1834 if (ok == PS_TRANSIENT)
1835 suppress_delete = suppress_forward = TRUE;
1838 set_timeout(ctl->server.timeout);
1840 /* tell server we got it OK and resynchronize */
1841 if (protocol->trail)
1843 if (outlevel == O_VERBOSE)
1844 fputc('\n', stderr);
1846 ok = (protocol->trail)(sock, ctl, num);
1849 set_timeout(ctl->server.timeout);
1853 /* count # messages forwarded on this pass */
1854 if (!suppress_forward)
1858 * Check to see if the numbers matched?
1860 * Yes, some servers foo this up horribly.
1861 * All IMAP servers seem to get it right, and
1862 * so does Eudora QPOP at least in 2.xx
1865 * Microsoft Exchange gets it completely
1866 * wrong, reporting compressed rather than
1867 * actual sizes (so the actual length of
1868 * message is longer than the reported size).
1869 * Another fine example of Microsoft brain death!
1871 * Some older POP servers, like the old UCB
1872 * POP server and the pre-QPOP QUALCOMM
1873 * versions, report a longer size in the LIST
1874 * response than actually gets shipped up.
1875 * It's unclear what is going on here, as the
1876 * QUALCOMM server (at least) seems to be
1877 * reporting the on-disk size correctly.
1879 if (msgsizes && msglen != msgsizes[num-1])
1881 if (outlevel >= O_VERBOSE)
1883 "message %d was not the expected length (%d != %d)",
1884 num, msglen, msgsizes[num-1]);
1887 /* end-of-message processing starts here */
1893 /* close the delivery pipe, we'll reopen before next message */
1895 rc = pclose(sinkfp);
1898 signal(SIGCHLD, sigchld);
1901 error(0, -1, "MDA exited abnormally or returned nonzero status");
1905 else if (!suppress_forward)
1907 /* write message terminator */
1908 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
1910 error(0, -1, "SMTP listener refused delivery");
1912 suppress_delete = TRUE;
1920 * At this point in flow of control, either
1921 * we've bombed on a protocol error or had
1922 * delivery refused by the SMTP server
1923 * (unlikely -- I've never seen it) or we've
1924 * seen `accepted for delivery' and the
1925 * message is shipped. It's safe to mark the
1926 * message seen and delete it on the server
1930 /* maybe we delete this message now? */
1933 if (outlevel > O_SILENT)
1934 error_complete(0, 0, " retained");
1936 else if (protocol->delete
1938 && (fetch_it ? !ctl->keep : ctl->flush))
1941 if (outlevel > O_SILENT)
1942 error_complete(0, 0, " flushed");
1943 ok = (protocol->delete)(sock, ctl, num);
1946 set_timeout(ctl->server.timeout);
1948 delete_str(&ctl->newsaved, num);
1949 #endif /* POP3_ENABLE */
1951 else if (outlevel > O_SILENT)
1952 error_complete(0, 0, " not flushed");
1954 /* perhaps this as many as we're ready to handle */
1955 if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
1961 * Only re-poll if we had some actual forwards, allowed
1962 * deletions and had no errors.
1963 * Otherwise it is far too easy to get into infinite loops.
1965 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
1969 set_timeout(ctl->server.timeout);
1970 ok = (protocol->logout_cmd)(sock, ctl);
1972 * Hmmmm...arguably this would be incorrect if we had fetches but
1973 * no dispatches (due to oversized messages, etc.)
1976 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1982 set_timeout(ctl->server.timeout);
1983 if (ok != 0 && ok != PS_SOCKET)
1984 (protocol->logout_cmd)(sock, ctl);
1989 msg = (char *)NULL; /* sacrifice to -Wall */
1996 msg = "authorization";
1999 msg = "missing or bad RFC822 header";
2005 msg = "client/server synchronization";
2008 msg = "client/server protocol";
2011 msg = "lock busy on server";
2014 msg = "SMTP transaction";
2020 error(0, 0, "undefined");
2023 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2024 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2025 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2026 error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2029 /* execute post-initialization command, if any */
2030 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2034 sprintf(buf, "post-connection command failed with status %d", ok);
2036 if (ok == PS_SUCCESS)
2040 signal(SIGALRM, sigsave);
2044 #if defined(HAVE_STDARG_H)
2045 void gen_send(int sock, const char *fmt, ... )
2046 /* assemble command in printf(3) style and send to the server */
2048 void gen_send(sock, fmt, va_alist)
2049 /* assemble command in printf(3) style and send to the server */
2050 int sock; /* socket to which server is connected */
2051 const char *fmt; /* printf-style format */
2055 char buf [POPBUFSIZE+1];
2058 if (protocol->tagged)
2059 (void) sprintf(buf, "%s ", GENSYM);
2063 #if defined(HAVE_STDARG_H)
2068 #ifdef HAVE_VSNPRINTF
2069 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2071 vsprintf(buf + strlen(buf), fmt, ap);
2075 strcat(buf, "\r\n");
2076 SockWrite(sock, buf, strlen(buf));
2078 if (outlevel == O_VERBOSE)
2082 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2086 sp = cp + strlen(shroud);
2092 buf[strlen(buf)-2] = '\0';
2093 error(0, 0, "%s> %s", protocol->name, buf);
2097 int gen_recv(sock, buf, size)
2098 /* get one line of input from the server */
2099 int sock; /* socket to which server is connected */
2100 char *buf; /* buffer to receive input */
2101 int size; /* length of buffer */
2103 if (SockRead(sock, buf, size) == -1)
2107 if (buf[strlen(buf)-1] == '\n')
2108 buf[strlen(buf)-1] = '\0';
2109 if (buf[strlen(buf)-1] == '\r')
2110 buf[strlen(buf)-1] = '\r';
2111 if (outlevel == O_VERBOSE)
2112 error(0, 0, "%s< %s", protocol->name, buf);
2117 #if defined(HAVE_STDARG_H)
2118 int gen_transact(int sock, char *fmt, ... )
2119 /* assemble command in printf(3) style, send to server, accept a response */
2121 int gen_transact(int sock, fmt, va_alist)
2122 /* assemble command in printf(3) style, send to server, accept a response */
2123 int sock; /* socket to which server is connected */
2124 const char *fmt; /* printf-style format */
2129 char buf [POPBUFSIZE+1];
2132 if (protocol->tagged)
2133 (void) sprintf(buf, "%s ", GENSYM);
2137 #if defined(HAVE_STDARG_H)
2142 #ifdef HAVE_VSNPRINTF
2143 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2145 vsprintf(buf + strlen(buf), fmt, ap);
2149 strcat(buf, "\r\n");
2150 SockWrite(sock, buf, strlen(buf));
2152 if (outlevel == O_VERBOSE)
2156 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2160 sp = cp + strlen(shroud);
2166 buf[strlen(buf)-1] = '\0';
2167 error(0, 0, "%s> %s", protocol->name, buf);
2170 /* we presume this does its own response echoing */
2171 ok = (protocol->parse_response)(sock, buf);
2172 set_timeout(mytimeout);
2177 /* driver.c ends here */