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)
31 #if defined(HAVE_SYS_ITIMER_H)
32 #include <sys/itimer.h>
37 #ifdef HAVE_GETHOSTBYNAME
40 #endif /* HAVE_GETHOSTBYNAME */
43 #if defined (__bsdi__)
44 #include <des.h> /* order of includes matters */
46 #define krb_get_err_text(e) (krb_err_txt[e])
48 #if defined(__FreeBSD__)
49 #define krb_get_err_text(e) (krb_err_txt[e])
55 #endif /* ! defined (__FreeBSD__) */
56 #endif /* ! defined (__bsdi__) */
57 #include <netinet/in.h>
59 #endif /* KERBEROS_V4 */
60 #include "fetchmail.h"
64 /* BSD portability hack...I know, this is an ugly place to put it */
65 #if !defined(SIGCHLD) && defined(SIGCLD)
66 #define SIGCHLD SIGCLD
69 #define SMTP_PORT 25 /* standard SMTP service port */
71 extern char *strstr(); /* needed on sysV68 R3V7.1. */
73 int fetchlimit; /* how often to tear down the server connection */
74 int batchcount; /* count of messages sent in current batch */
75 flag peek_capable; /* can we peek for better error recovery? */
76 int pass; /* how many times have we re-polled? */
78 static const struct method *protocol;
79 static jmp_buf restart;
83 #define GENSYM (sprintf(tag, "a%04d", ++tagnum), tag)
85 static char *shroud; /* string to shroud in debug output, if non-NULL */
86 static int mytimeout; /* value of nonreponse timeout */
87 static int msglen; /* actual message length */
89 static void set_timeout(int timeleft)
90 /* reset the nonresponse-timeout */
92 struct itimerval ntimeout;
94 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
95 ntimeout.it_value.tv_sec = timeleft;
96 ntimeout.it_value.tv_usec = 0;
97 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
100 static void timeout_handler (int signal)
101 /* handle server-timeout SIGALRM signal */
106 #define XMIT_ACCEPT 1
107 #define XMIT_REJECT 2
108 #define XMIT_ANTISPAM 3
109 static int accept_count, reject_count;
111 #ifdef HAVE_RES_SEARCH
114 static int is_host_alias(const char *name, struct query *ctl)
115 /* determine whether name is a DNS alias of the hostname */
118 struct mxentry *mxp, *mxrecords;
120 struct hostdata *lead_server =
121 ctl->server.lead_server ? ctl->server.lead_server : &ctl->server;
124 * The first two checks are optimizations that will catch a good
127 * (1) check against the `true name' deduced from the poll label
128 * and the via option (if present) at the beginning of the poll cycle.
129 * Odds are good this will either be the mailserver's FQDN or a suffix of
130 * it with the mailserver's domain's default host name omitted.
132 * (2) Then check the rest of the `also known as'
133 * cache accumulated by previous DNS checks. This cache is primed
134 * by the aka list option.
136 * Any of these on a mail address is definitive. Only if the
137 * name doesn't match any is it time to call the bind library.
138 * If this happens odds are good we're looking at an MX name.
140 if (strcmp(lead_server->truename, name) == 0)
142 else if (str_in_list(&lead_server->akalist, name))
144 else if (!ctl->server.dns)
148 * We know DNS service was up at the beginning of this poll cycle.
149 * If it's down, our nameserver has crashed. We don't want to try
150 * delivering the current message or anything else from this
151 * mailbox until it's back up.
153 else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
155 if (strcmp(ctl->server.truename, he->h_name) == 0)
163 case HOST_NOT_FOUND: /* specified host is unknown */
164 case NO_ADDRESS: /* valid, but does not have an IP address */
167 case NO_RECOVERY: /* non-recoverable name server error */
168 case TRY_AGAIN: /* temporary error on authoritative server */
170 if (outlevel != O_SILENT)
171 putchar('\n'); /* terminate the progress message */
173 "nameserver failure while looking for `%s' during poll of %s.",
174 name, ctl->server.pollname);
180 * We're only here if DNS was OK but the gethostbyname() failed
181 * with a HOST_NOT_FOUND or NO_ADDRESS error.
182 * Search for a name match on MX records pointing to the server.
185 if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
189 case HOST_NOT_FOUND: /* specified host is unknown */
190 case NO_ADDRESS: /* valid, but does not have an IP address */
194 case NO_RECOVERY: /* non-recoverable name server error */
195 case TRY_AGAIN: /* temporary error on authoritative server */
198 "nameserver failure while looking for `%s' during poll of %s.",
199 name, ctl->server.pollname);
206 for (mxp = mxrecords; mxp->name; mxp++)
207 if (strcmp(ctl->server.truename, mxp->name) == 0)
213 /* add this name to relevant server's `also known as' list */
214 save_str(&lead_server->akalist, -1, name);
218 static void map_name(name, ctl, xmit_names)
219 /* add given name to xmit_names if it matches declared localnames */
220 const char *name; /* name to map */
221 struct query *ctl; /* list of permissible aliases */
222 struct idlist **xmit_names; /* list of recipient names parsed out */
226 lname = idpair_find(&ctl->localnames, name);
227 if (!lname && ctl->wildcard)
230 if (lname != (char *)NULL)
232 if (outlevel == O_VERBOSE)
233 error(0, 0, "mapped %s to local %s", name, lname);
234 save_str(xmit_names, XMIT_ACCEPT, lname);
239 void find_server_names(hdr, ctl, xmit_names)
240 /* parse names out of a RFC822 header into an ID list */
241 const char *hdr; /* RFC822 header in question */
242 struct query *ctl; /* list of permissible aliases */
243 struct idlist **xmit_names; /* list of recipient names parsed out */
245 if (hdr == (char *)NULL)
251 if ((cp = nxtaddr(hdr)) != (char *)NULL)
255 if ((atsign = strchr(cp, '@')))
260 * Does a trailing segment of the hostname match something
261 * on the localdomains list? If so, save the whole name
264 for (idp = ctl->server.localdomains; idp; idp = idp->next)
268 rhs = atsign + (strlen(atsign) - strlen(idp->id));
269 if ((rhs[-1] == '.' || rhs[-1] == '@')
270 && strcasecmp(rhs, idp->id) == 0)
272 if (outlevel == O_VERBOSE)
273 error(0, 0, "passed through %s matching %s",
275 save_str(xmit_names, XMIT_ACCEPT, cp);
282 * Check to see if the right-hand part is an alias
283 * or MX equivalent of the mailserver. If it's
284 * not, skip this name. If it is, we'll keep
285 * going and try to find a mapping to a client name.
287 if (!is_host_alias(atsign+1, ctl))
289 save_str(xmit_names, XMIT_REJECT, cp);
296 map_name(cp, ctl, xmit_names);
298 ((cp = nxtaddr((char *)NULL)) != (char *)NULL);
302 static char *parse_received(struct query *ctl, char *bufp)
303 /* try to extract real addressee from the Received line */
305 char *ok = (char *)NULL;
306 static char rbuf[HOSTLEN + USERNAMELEN + 4];
309 * Try to extract the real envelope addressee. We look here
310 * specifically for the mailserver's Received line.
311 * Note: this will only work for sendmail, or an MTA that
312 * shares sendmail's convention for embedding the envelope
313 * address in the Received line. Sendmail itself only
314 * does this when the mail has a single recipient.
316 if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
320 /* extract space-delimited token after "by " */
321 for (sp = ok + 3; isspace(*sp); sp++)
324 for (; !isspace(*sp); sp++)
329 * If it's a DNS name of the mail server, look for the
330 * recipient name after a following "for". Otherwise
333 if (!is_host_alias(rbuf, ctl))
335 else if ((ok = strstr(sp, "for ")) && isspace(ok[-1]))
341 while (*sp && *sp != '>' && *sp != '@' && *sp != ';')
346 /* uh oh -- whitespace here can't be right! */
358 if (outlevel == O_VERBOSE)
359 error(0, 0, "found Received address `%s'", rbuf);
363 #endif /* HAVE_RES_SEARCH */
365 static int smtp_open(struct query *ctl)
366 /* try to open a socket to the appropriate SMTP server for this query */
368 /* maybe it's time to close the socket in order to force delivery */
369 if (ctl->batchlimit > 0 && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
371 close(ctl->smtp_socket);
372 ctl->smtp_socket = -1;
376 /* if no socket to any SMTP host is already set up, try to open one */
377 if (ctl->smtp_socket == -1)
380 * RFC 1123 requires that the domain name in HELO address is a
381 * "valid principal domain name" for the client host. We
382 * violate this with malice aforethought in order to make the
383 * Received headers and logging look right.
385 * In fact this code relies on the RFC1123 requirement that the
386 * SMTP listener must accept messages even if verification of the
387 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
389 * How we compute the true mailhost name to pass to the
390 * listener doesn't affect behavior on RFC1123- violating
391 * listener that check for name match; we're going to lose
392 * on those anyway because we can never give them a name
393 * that matches the local machine fetchmail is running on.
394 * What it will affect is the listener's logging.
400 /* run down the SMTP hunt list looking for a server that's up */
401 for (idp = ctl->smtphunt; idp; idp = idp->next)
403 ctl->smtphost = idp->id; /* remember last host tried. */
405 if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
408 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
409 SMTP_ehlo(ctl->smtp_socket,
410 ctl->server.truename,
411 &ctl->server.esmtp_options) == SM_OK)
415 * RFC 1869 warns that some listeners hang up on a failed EHLO,
416 * so it's safest not to assume the socket will still be good.
418 close(ctl->smtp_socket);
419 ctl->smtp_socket = -1;
421 /* if opening for ESMTP failed, try SMTP */
422 if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
425 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
426 SMTP_helo(ctl->smtp_socket, ctl->server.truename) == SM_OK)
429 close(ctl->smtp_socket);
430 ctl->smtp_socket = -1;
434 if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
435 error(0, 0, "forwarding to SMTP port on %s", ctl->smtphost);
437 return(ctl->smtp_socket);
440 /* these are shared by stuffline, readheaders and readbody */
442 static RETSIGTYPE (*sigchld)();
443 static int sizeticker;
445 static int stuffline(struct query *ctl, char *buf)
446 /* ship a line to the given control block's output sink (SMTP server or MDA) */
450 /* fix message lines that have only \n termination (for qmail) */
453 char *cp = buf + strlen(buf) - 1;
455 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
464 * SMTP byte-stuffing. We only do this if the protocol does *not*
465 * use .<CR><LF> as EOM. If it does, the server will already have
466 * decorated any . lines it sends back up.
469 if (protocol->delimited) /* server has already byte-stuffed */
474 /* writing to SMTP, leave the byte-stuffing in place */;
476 else /* if (!protocol->delimited) /* not byte-stuffed already */
479 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
481 /* leave it alone */;
484 /* we may need to strip carriage returns */
489 for (sp = tp = buf; *sp; sp++)
497 n = fwrite(buf, 1, strlen(buf), sinkfp);
498 else if (ctl->smtp_socket != -1)
499 n = SockWrite(ctl->smtp_socket, buf, strlen(buf));
504 static int readheaders(sock, len, ctl, realname, num)
505 /* read message headers and ship to SMTP or MDA */
506 int sock; /* to which the server is connected */
507 long len; /* length of message */
508 struct query *ctl; /* query control record */
509 char *realname; /* real name of host */
510 int num; /* index of message */
515 struct addrblk *next;
516 } *addrchain = NULL, **chainptr = &addrchain;
517 char buf[MSGBUFSIZE+1], return_path[MSGBUFSIZE+1];
518 int from_offs, ctt_offs, env_offs, next_address;
519 char *headers, *received_for, *desthost, *rcv;
520 int n, linelen, oldlen, ch, remaining;
522 struct idlist *idp, *xmit_names;
523 flag good_addresses, bad_addresses, has_nuls;
524 #ifdef HAVE_RES_SEARCH
525 flag no_local_matches = FALSE;
526 #endif /* HAVE_RES_SEARCH */
529 next_address = sizeticker = 0;
531 return_path[0] = '\0';
532 olderrs = ctl->errcount;
534 /* read message headers */
535 headers = received_for = NULL;
536 from_offs = ctt_offs = env_offs = -1;
540 for (remaining = len; remaining > 0 || protocol->delimited; remaining -= linelen)
544 line = xmalloc(sizeof(buf));
548 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1)
553 /* lines may not be properly CRLF terminated; fix this for qmail */
556 cp = buf + strlen(buf) - 1;
557 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
565 set_timeout(ctl->server.timeout);
567 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
570 if (line[0] == '\r' && line[1] == '\n')
573 /* we may need to grab RFC822 continuations */
574 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
576 /* write the message size dots */
577 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
579 sizeticker += linelen;
580 while (sizeticker >= SIZETICKER)
583 sizeticker -= SIZETICKER;
587 if (linelen != strlen(line))
590 /* check for end of headers; don't save terminating line */
591 if (line[0] == '\r' && line[1] == '\n')
598 * The University of Washington IMAP server (the reference
599 * implementation of IMAP4 written by Mark Crispin) relies
600 * on being able to keep base-UID information in a special
601 * message at the head of the mailbox. This message should
602 * neither be deleted nor forwarded.
606 * We disable this check under POP2 because there's no way to
607 * prevent deletion of the message. So at least we ought to
608 * forward it to the user so he or she will have some clue
609 * that things have gone awry.
611 if (protocol->port != 109)
612 #endif /* POP2_ENABLE */
613 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7))
617 * This code prevents fetchmail from becoming an accessory after
618 * the fact to upstream sendmails with the `E' option on. This
619 * can result in an escaped Unix From_ line at the beginning of
620 * the headers. If fetchmail just passes it through, the client
621 * listener may think the message has *no* headers (since the first)
622 * line it sees doesn't look RFC822-conformant) and fake up a set.
624 * What the user would see in this case is bogus (synthesized)
625 * headers, followed by a blank line, followed by the >From,
626 * followed by the real headers, followed by a blank line,
629 * We forestall this lossage by tossing anything that looks
630 * like an escaped From_ line in headers. These aren't RFC822
631 * so our conscience is clear...
633 if (!strncasecmp(line, ">From ", 6))
640 * If we see a Status line, it may have been inserted by an MUA
641 * on the mail host, or it may have been inserted by the server
642 * program after the headers in the transaction stream. This
643 * can actually hose some new-mail notifiers such as xbuffy,
644 * which assumes any Status line came from a *local* MDA and
645 * therefore indicates that the message has been seen.
647 * Some buggy POP servers (including at least the 3.3(20)
648 * version of the one distributed with IMAP) insert empty
649 * Status lines in the transaction stream; we'll chuck those
650 * unconditionally. Nonempty ones get chucked if the user
651 * turns on the dropstatus flag.
653 if (!strncasecmp(line, "Status:", 7))
657 for (cp = line + 7; *cp && isspace(*cp); cp++)
660 if (!*cp || ctl->dropstatus)
668 * OK, this is messy. If we're forwarding by SMTP, it's the
669 * SMTP-receiver's job (according to RFC821, page 22, section
670 * 4.1.1) to generate a Return-Path line on final delivery.
671 * The trouble is, we've already got one because the
672 * mailserver's SMTP thought *it* was responsible for final
675 * Stash away the contents of Return-Path for use in generating
676 * MAIL FROM later on, then prevent the header from being saved
677 * with the others. In effect, we strip it off here.
679 * If the SMTP server conforms to the standards, and fetchmail gets the
680 * envelope sender from the Return-Path, the new Return-Path should be
681 * exactly the same as the original one.
683 if (!ctl->mda && !strncasecmp("Return-Path:", line, 12))
685 strcpy(return_path, nxtaddr(line));
691 line = reply_hack(line, realname);
695 oldlen = strlen(line);
696 headers = xmalloc(oldlen + 1);
697 (void) strcpy(headers, line);
705 newlen = oldlen + strlen(line);
706 headers = (char *) realloc(headers, newlen + 1);
709 strcpy(headers + oldlen, line);
711 line = headers + oldlen;
715 if (from_offs == -1 && !strncasecmp("From:", line, 5))
716 from_offs = (line - headers);
717 else if (from_offs == -1 && !strncasecmp("Resent-From:", line, 12))
718 from_offs = (line - headers);
719 else if (from_offs == -1 && !strncasecmp("Apparently-From:", line, 16))
720 from_offs = (line - headers);
721 else if (!strncasecmp("Content-Transfer-Encoding:", line, 26))
722 ctt_offs = (line - headers);
723 else if (!strncasecmp("Message-Id:", buf, 11 ))
725 if( ctl->server.uidl )
728 sscanf( buf+12, "%s", id);
729 if( !str_in_list( &ctl->newsaved, id ) )
730 save_str(&ctl->newsaved, num, id );
734 else if (!MULTIDROP(ctl))
737 else if (!strncasecmp("To:", line, 3)
738 || !strncasecmp("Cc:", line, 3)
739 || !strncasecmp("Bcc:", line, 4))
741 *chainptr = xmalloc(sizeof(struct addrblk));
742 (*chainptr)->offset = (line - headers);
743 chainptr = &(*chainptr)->next;
747 else if (ctl->server.envelope != STRING_DISABLED)
749 if (ctl->server.envelope
750 && strcasecmp(ctl->server.envelope, "received"))
752 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
754 strlen(ctl->server.envelope)))
755 env_offs = (line - headers);
757 #ifdef HAVE_RES_SEARCH
758 else if (!received_for && !strncasecmp("Received:", line, 9))
759 received_for = parse_received(ctl, line);
760 #endif /* HAVE_RES_SEARCH */
765 * Hack time. If the first line of the message was blank, with no headers
766 * (this happens occasionally due to bad gatewaying software) cons up
767 * a set of fake headers.
769 * If you modify the fake header template below, be sure you don't
770 * make either From or To address @-less, otherwise the reply_hack
771 * logic will do bad things.
773 if (headers == (char *)NULL)
776 "From: <FETCHMAIL-DAEMON@%s>\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
777 fetchmailhost, user, ctl->remotename, realname);
778 headers = xstrdup(buf);
782 * We can now process message headers before reading the text.
783 * In fact we have to, as this will tell us where to forward to.
786 /* cons up a list of local recipients */
787 xmit_names = (struct idlist *)NULL;
788 bad_addresses = good_addresses = accept_count = reject_count = 0;
789 #ifdef HAVE_RES_SEARCH
790 /* is this a multidrop box? */
793 if (env_offs > -1) /* We have the actual envelope addressee */
794 find_server_names(headers + env_offs, ctl, &xmit_names);
795 else if (received_for)
797 * We have the Received for addressee.
798 * It has to be a mailserver address, or we
799 * wouldn't have got here.
801 map_name(received_for, ctl, &xmit_names);
807 * We haven't extracted the envelope address.
808 * So check all the header addresses.
812 register struct addrblk *nextptr;
814 find_server_names(headers+addrchain->offset, ctl, &xmit_names);
815 nextptr = addrchain->next;
822 no_local_matches = TRUE;
823 save_str(&xmit_names, XMIT_ACCEPT, user);
824 if (outlevel == O_VERBOSE)
826 "no local matches, forwarding to %s",
830 else /* it's a single-drop box, use first localname */
831 #endif /* HAVE_RES_SEARCH */
832 save_str(&xmit_names, XMIT_ACCEPT, ctl->localnames->id);
836 * Time to either address the message or decide we can't deliver it yet.
838 if (ctl->errcount > olderrs) /* there were DNS errors above */
840 if (outlevel == O_VERBOSE)
841 error(0,0, "forwarding and deletion suppressed due to DNS errors");
843 return(PS_TRANSIENT);
845 else if (ctl->mda) /* we have a declared MDA */
850 desthost = "localhost";
853 * We go through this in order to be able to handle very
854 * long lists of users and (re)implement %s.
856 for (idp = xmit_names; idp; idp = idp->next)
857 if (idp->val.num == XMIT_ACCEPT)
859 length += (strlen(idp->id) + 1);
862 names = (char *)alloca(length);
864 for (idp = xmit_names; idp; idp = idp->next)
865 if (idp->val.num == XMIT_ACCEPT)
867 strcat(names, idp->id);
870 cmd = (char *)alloca(strlen(ctl->mda) + length);
871 sprintf(cmd, ctl->mda, names);
872 if (outlevel == O_VERBOSE)
873 error(0, 0, "about to deliver with: %s", cmd);
877 * Arrange to run with user's permissions if we're root.
878 * This will initialize the ownership of any files the
879 * MDA creates properly. (The seteuid call is available
880 * under all BSDs and Linux)
883 #endif /* HAVE_SETEUID */
885 sinkfp = popen(cmd, "w");
888 /* this will fail quietly if we didn't start as root */
890 #endif /* HAVE_SETEUID */
894 error(0, 0, "MDA open failed");
898 sigchld = signal(SIGCHLD, SIG_DFL);
902 char *ap, *ctt, options[MSGBUFSIZE], addr[128];
904 /* build a connection to the SMTP listener */
905 if ((smtp_open(ctl) == -1))
907 error(0, errno, "SMTP connect to %s failed",
908 ctl->smtphost ? ctl->smtphost : "localhost");
909 free_str_list(&xmit_names);
914 * Compute ESMTP options. It's a kluge to use nxtaddr()
915 * here because the contents of the Content-Transfer-Encoding
916 * headers isn't semantically an address. But it has the
917 * desired tokenizing effect.
920 if (ctl->server.esmtp_options & ESMTP_8BITMIME)
922 sprintf(options, " BODY=8BITMIME");
923 else if ((ctt_offs >= 0) && (ctt = nxtaddr(headers + ctt_offs)))
925 if (!strcasecmp(ctt,"7BIT"))
926 sprintf(options, " BODY=7BIT");
927 else if (!strcasecmp(ctt,"8BIT"))
928 sprintf(options, " BODY=8BITMIME");
930 if ((ctl->server.esmtp_options & ESMTP_SIZE))
931 sprintf(options + strlen(options), " SIZE=%ld", len);
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, take the From address.
940 * Try to get the SMTP listener to take the Return-Path or
941 * From address as MAIL FROM . If it won't, fall back on the
942 * calling-user ID. This won't affect replies, which use the
943 * header From address anyway.
945 * RFC 1123 requires that the domain name part of the
946 * MAIL FROM address be "canonicalized", that is a
947 * FQDN or MX but not a CNAME. We'll assume the From
948 * header is already in this form here (it certainly
949 * is if rewrite is on). RFC 1123 is silent on whether
950 * a nonexistent hostname part is considered canonical.
952 * This is a potential problem if the MTAs further upstream
953 * didn't pass canonicalized From/Return-Path lines, *and* the
954 * local SMTP listener insists on them.
959 else if (from_offs == -1 || !(ap = nxtaddr(headers + from_offs)))
961 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
963 int smtperr = atoi(smtp_response);
966 * Suppress error message only if the response specifically
967 * means `excluded for policy reasons'. We *should* see
968 * an error when the return code is less specific.
970 if (smtperr >= 400 && smtperr != 571)
971 error(0, -1, "SMTP error: %s", smtp_response);
975 case 571: /* sendmail's "unsolicited email refused" */
976 case 501: /* exim's old antispam response */
977 case 550: /* exim's new antispam response (temporary) */
979 * SMTP listener explicitly refuses to deliver
980 * mail coming from this address, probably due
981 * to an anti-spam domain exclusion. Respect
982 * this. Don't try to ship the message, and
983 * don't prevent it from being deleted.
988 case 452: /* insufficient system storage */
990 * Temporary out-of-queue-space condition on the
991 * ESMTP server. Don't try to ship the message,
992 * and suppress deletion so it can be retried on
993 * a future retrieval cycle.
995 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
997 return(PS_TRANSIENT);
999 case 552: /* message exceeds fixed maximum message size */
1001 * Permanent no-go condition on the
1002 * ESMTP server. Don't try to ship the message,
1003 * and allow it to be deleted.
1005 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1009 default: /* retry with invoking user's address */
1010 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1012 error(0, -1, "SMTP error: %s", smtp_response);
1014 return(PS_SMTP); /* should never happen */
1020 * Now list the recipient addressees
1022 * RFC 1123 requires that the domain name part of the
1023 * RCPT TO address be "canonicalized", that is a FQDN
1024 * or MX but not a CNAME. Some listeners (like exim)
1027 desthost = ctl->smtphost ? ctl->smtphost : "localhost";
1028 for (idp = xmit_names; idp; idp = idp->next)
1029 if (idp->val.num == XMIT_ACCEPT)
1031 if (strchr(idp->id, '@'))
1032 strcpy(addr, idp->id);
1034 #ifdef HAVE_SNPRINTF
1035 snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, desthost);
1037 sprintf(addr, "%s@%s", idp->id, desthost);
1038 #endif /* HAVE_SNPRINTF */
1040 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1045 idp->val.num = XMIT_ANTISPAM;
1047 "SMTP listener doesn't like recipient address `%s'", idp->id);
1050 if (!good_addresses)
1052 #ifdef HAVE_SNPRINTF
1053 snprintf(addr, sizeof(addr)-1, "%s@%s", user, desthost);
1055 sprintf(addr, "%s@%s", user, desthost);
1056 #endif /* HAVE_SNPRINTF */
1058 if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1060 error(0, 0, "can't even send to calling user!");
1066 /* tell it we're ready to send data */
1067 SMTP_data(ctl->smtp_socket);
1072 * Some server/sendmail combinations cause problems when our
1073 * synthetic Received line is before the From header. Cope
1076 if ((rcv = strstr("Received:", headers)) == (char *)NULL)
1081 n = stuffline(ctl, headers);
1086 /* utter any per-message Received information we need here */
1087 sprintf(buf, "Received: from %s\n", ctl->server.truename);
1088 n = stuffline(ctl, buf);
1091 sprintf(buf, "\tby %s (fetchmail-%s %s run by %s)\n",
1096 n = stuffline(ctl, buf);
1102 if (good_addresses == 0)
1105 "for <%s@%s> (by default); ",
1108 else if (good_addresses == 1)
1110 for (idp = xmit_names; idp; idp = idp->next)
1111 if (idp->val.num == XMIT_ACCEPT)
1112 break; /* only report first address */
1113 sprintf(buf+1, "for <%s@%s> (%s); ",
1115 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1121 strcat(buf, ctime(&now));
1122 n = stuffline(ctl, buf);
1124 n = stuffline(ctl, rcv); /* ship out rest of headers */
1131 error(0, errno, "writing RFC822 headers");
1135 signal(SIGCHLD, sigchld);
1139 else if (outlevel == O_VERBOSE)
1142 /* write error notifications */
1143 #ifdef HAVE_RES_SEARCH
1144 if (no_local_matches || has_nuls || bad_addresses)
1146 if (has_nuls || bad_addresses)
1147 #endif /* HAVE_RES_SEARCH */
1150 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1153 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1154 #ifdef HAVE_RES_SEARCH
1155 if (no_local_matches)
1157 if (reject_count != 1)
1158 strcat(errhd, "no recipient addresses matched declared local names");
1161 for (idp = xmit_names; idp; idp = idp->next)
1162 if (idp->val.num == XMIT_REJECT)
1164 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1167 #endif /* HAVE_RES_SEARCH */
1171 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1172 strcat(errhd, "; ");
1173 strcat(errhd, "message has embedded NULs");
1178 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1179 strcat(errhd, "; ");
1180 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1181 errlen = strlen(errhd);
1182 for (idp = xmit_names; idp; idp = idp->next)
1183 if (idp->val.num == XMIT_ANTISPAM)
1184 errlen += strlen(idp->id) + 2;
1186 errmsg = alloca(errlen+3);
1187 (void) strcpy(errmsg, errhd);
1188 for (idp = xmit_names; idp; idp = idp->next)
1189 if (idp->val.num == XMIT_ANTISPAM)
1191 strcat(errmsg, idp->id);
1193 strcat(errmsg, ", ");
1198 strcat(errmsg, "\n");
1200 /* ship out the error line */
1202 stuffline(ctl, errmsg);
1205 free_str_list(&xmit_names);
1207 /* issue the delimiter line */
1212 stuffline(ctl, buf);
1217 static int readbody(sock, ctl, forward, len)
1218 /* read and dispose of a message body presented on sock */
1219 struct query *ctl; /* query control record */
1220 int sock; /* to which the server is connected */
1221 int len; /* length of message */
1222 flag forward; /* TRUE to forward */
1225 char buf[MSGBUFSIZE+1], *cp;
1227 /* pass through the text lines */
1228 while (protocol->delimited || len > 0)
1230 if ((linelen = SockRead(sock, buf, sizeof(buf)-1)) == -1)
1235 signal(SIGCHLD, sigchld);
1239 set_timeout(ctl->server.timeout);
1241 /* write the message size dots */
1244 sizeticker += linelen;
1245 while (sizeticker >= SIZETICKER)
1247 if (outlevel > O_SILENT)
1249 sizeticker -= SIZETICKER;
1254 /* check for end of message */
1255 if (protocol->delimited && *buf == '.')
1256 if (buf[1] == '\r' && buf[2] == '\n' && buf[3] == '\0')
1258 else if (buf[1] == '\n' && buf[2] == '\0')
1261 msglen--; /* subtract the size of the dot escape */
1265 /* ship out the text line */
1268 int n = stuffline(ctl, buf);
1272 error(0, errno, "writing message text");
1276 signal(SIGCHLD, sigchld);
1280 else if (outlevel == O_VERBOSE)
1290 kerberos_auth (socket, canonical)
1291 /* authenticate to the server host using Kerberos V4 */
1292 int socket; /* socket to server host */
1294 char *canonical; /* server name */
1296 const char *canonical; /* server name */
1299 char * host_primary;
1303 Key_schedule schedule;
1306 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1307 rem = (krb_sendauth (0L, socket, ticket, "pop",
1309 ((char *) (krb_realmofhost (canonical))),
1310 ((unsigned long) 0),
1314 ((struct sockaddr_in *) 0),
1315 ((struct sockaddr_in *) 0),
1318 if (rem != KSUCCESS)
1320 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1321 return (PS_AUTHFAIL);
1325 #endif /* KERBEROS_V4 */
1327 int do_protocol(ctl, proto)
1328 /* retrieve messages from server using given protocol method table */
1329 struct query *ctl; /* parsed options with merged-in defaults */
1330 const struct method *proto; /* protocol method table */
1332 int ok, js, pst, sock = -1;
1333 char *msg, *cp, realname[HOSTLEN];
1337 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1339 error(0, -1, "Kerberos V4 support not linked.");
1342 #endif /* KERBEROS_V4 */
1344 /* lacking methods, there are some options that may fail */
1347 /* check for unsupported options */
1350 "Option --flush is not supported with %s",
1354 else if (ctl->fetchall) {
1356 "Option --all is not supported with %s",
1361 if (!proto->getsizes && ctl->limit)
1364 "Option --limit is not supported with %s",
1372 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1374 error_init(poll_interval == 0 && !logfile);
1376 /* set up the server-nonresponse timeout */
1377 sigsave = signal(SIGALRM, timeout_handler);
1378 set_timeout(mytimeout = ctl->server.timeout);
1380 if ((js = setjmp(restart)) == 1)
1383 "timeout after %d seconds waiting for %s.",
1384 ctl->server.timeout, ctl->server.pollname);
1385 if (ctl->smtp_socket != -1)
1386 close(ctl->smtp_socket);
1393 char buf [POPBUFSIZE+1], *sp, *realhost;
1394 int *msgsizes, len, num, count, new, deletions = 0;
1398 /* execute pre-initialization command, if any */
1399 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1401 sprintf(buf, "pre-connection command failed with status %d", ok);
1407 /* open a socket to the mail server */
1408 port = ctl->server.port ? ctl->server.port : protocol->port;
1409 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1410 if ((sock = SockOpen(realhost, port)) == -1)
1412 #ifndef EHOSTUNREACH
1413 #define EHOSTUNREACH (-1)
1415 if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1417 error_build("fetchmail: %s connection to %s failed: ",
1418 protocol->name, ctl->server.pollname);
1419 if (h_errno == HOST_NOT_FOUND)
1420 error_complete(0, 0, "host is unknown");
1421 else if (h_errno == NO_ADDRESS)
1422 error_complete(0, 0, "name is valid but has no IP address");
1423 else if (h_errno == NO_RECOVERY)
1424 error_complete(0, 0, "unrecoverable name server error");
1425 else if (h_errno == TRY_AGAIN)
1426 error_complete(0, 0, "temporary name server error");
1428 error_complete(0, 0, "unknown DNS error %d", h_errno);
1430 error_complete(0, errno, "local error");
1437 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1439 ok = kerberos_auth(sock, ctl->server.truename);
1442 set_timeout(ctl->server.timeout);
1444 #endif /* KERBEROS_V4 */
1446 /* accept greeting message from mail server */
1447 ok = (protocol->parse_response)(sock, buf);
1450 set_timeout(ctl->server.timeout);
1453 * Try to parse the host's actual name out of the greeting
1454 * message. We do this so that the progress messages will
1455 * make sense even if the connection is indirected through
1456 * ssh. *Do* use this for hacking reply headers, but *don't*
1457 * use it for error logging, as the names in the log should
1458 * correlate directly back to rc file entries.
1460 * This assumes that the first space-delimited token found
1461 * that contains at least two dots (with the characters on
1462 * each side of the dot alphanumeric to exclude version
1463 * numbers) is the hostname. The hostname candidate may not
1464 * contain @ -- if it does it's probably a mailserver
1465 * maintainer's name. If no such token is found, fall back on
1466 * the .fetchmailrc id.
1469 sp = (char *)NULL; /* sacrifice to -Wall */
1470 for (cp = buf; *cp; cp++)
1474 case 0: /* skip to end of current token */
1479 case 1: /* look for blank-delimited token */
1487 case 2: /* look for first dot */
1490 else if (*cp == ' ')
1492 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1496 case 3: /* look for second dot */
1499 else if (*cp == ' ')
1501 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1505 case 4: /* look for trailing space */
1508 else if (*cp == ' ')
1519 char *tp = realname;
1526 strcpy(realname, ctl->server.pollname);
1528 /* try to get authorized to fetch mail */
1529 if (protocol->getauth)
1531 shroud = ctl->password;
1532 ok = (protocol->getauth)(sock, ctl, buf);
1533 shroud = (char *)NULL;
1536 if (ok == PS_LOCKBUSY)
1537 error(0, -1, "Lock-busy error on %s@%s",
1544 error(0, -1, "Authorization failure on %s@%s",
1550 set_timeout(ctl->server.timeout);
1553 ctl->errcount = fetches = 0;
1555 /* now iterate over each folder selected */
1556 for (idp = ctl->mailboxes; idp; idp = idp->next)
1561 if (outlevel >= O_VERBOSE)
1563 error(0, 0, "selecting or re-polling folder %s");
1565 error(0, 0, "selecting or re-polling default folder");
1567 /* compute # of messages and number of new messages waiting */
1568 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new);
1571 set_timeout(ctl->server.timeout);
1573 /* show user how many messages we downloaded */
1575 (void) sprintf(buf, "%s@%s:%s",
1576 ctl->remotename, realname, idp->id);
1578 (void) sprintf(buf, "%s@%s", ctl->remotename, realname);
1579 if (outlevel > O_SILENT)
1580 if (count == -1) /* only used for ETRN */
1581 error(0, 0, "Polling %s", realname);
1582 else if (count != 0)
1584 if (new != -1 && (count - new) > 0)
1585 error(0, 0, "%d message%s (%d seen) at %s.",
1586 count, count > 1 ? "s" : "", count-new, buf);
1588 error(0, 0, "%d message%s at %s.",
1589 count, count > 1 ? "s" : "", buf);
1593 /* these are pointless in normal daemon mode */
1594 if (pass == 1 && (poll_interval == 0 || outlevel == O_VERBOSE))
1595 error(0, 0, "No mail at %s", buf);
1601 if (new == -1 || ctl->fetchall)
1603 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1608 flag force_retrieval;
1611 * What forces this code is that in POP3 and
1612 * IMAP2BIS you can't fetch a message without
1613 * having it marked `seen'. In IMAP4, on the
1614 * other hand, you can (peek_capable is set to
1617 * The result of being unable to peek is that if there's
1618 * any kind of transient error (DNS lookup failure, or
1619 * sendmail refusing delivery due to process-table limits)
1620 * the message will be marked "seen" on the server without
1621 * having been delivered. This is not a big problem if
1622 * fetchmail is running in foreground, because the user
1623 * will see a "skipped" message when it next runs and get
1626 * But in daemon mode this leads to the message
1627 * being silently ignored forever. This is not
1630 * We compensate for this by checking the error
1631 * count from the previous pass and forcing all
1632 * messages to be considered new if it's nonzero.
1634 force_retrieval = !peek_capable && (ctl->errcount > 0);
1637 * We need the size of each message before it's
1638 * loaded in order to pass via the ESMTP SIZE
1639 * option. If the protocol has a getsizes method,
1640 * we presume this means it doesn't get reliable
1641 * sizes from message fetch responses.
1643 if (proto->getsizes)
1645 msgsizes = (int *)alloca(sizeof(int) * count);
1647 ok = (proto->getsizes)(sock, count, msgsizes);
1650 set_timeout(ctl->server.timeout);
1653 /* read, forward, and delete messages */
1654 for (num = 1; num <= count; num++)
1656 flag toolarge = (ctl->limit > 0)
1657 && msgsizes && (msgsizes[num-1] > ctl->limit);
1658 flag fetch_it = !toolarge
1659 && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
1660 flag suppress_delete = FALSE;
1661 flag suppress_forward = FALSE;
1662 flag retained = FALSE;
1665 * This check copes with Post Office/NT's
1666 * annoying habit of randomly prepending bogus
1667 * LIST items of length -1. Patrick Audley
1668 * <paudley@pobox.com> tells us: LIST shows a
1669 * size of -1, RETR and TOP return "-ERR
1670 * System error - couldn't open message", and
1671 * DELE succeeds but doesn't actually delete
1674 if (msgsizes && msgsizes[num-1] == -1)
1676 if (outlevel >= O_VERBOSE)
1678 "Skipping message %d, length -1",
1683 /* we may want to reject this message if it's old */
1686 if (outlevel > O_SILENT)
1688 error_build("skipping message %d", num);
1690 error_build(" (oversized, %d bytes)",
1696 flag wholesize = !protocol->fetch_body;
1698 /* request a message */
1699 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1702 set_timeout(ctl->server.timeout);
1704 /* -1 means we didn't see a size in the response */
1705 if (len == -1 && msgsizes)
1707 len = msgsizes[num - 1];
1711 if (outlevel > O_SILENT)
1713 error_build("reading message %d of %d",
1717 error_build(" (%d %sbytes)",
1718 len, wholesize ? "" : "header ");
1719 if (outlevel == O_VERBOSE)
1720 error_complete(0, 0, "");
1726 * Read the message headers and ship them to the
1729 ok = readheaders(sock, len, ctl, realname, num);
1730 if (ok == PS_RETAINED)
1731 suppress_forward = retained = TRUE;
1732 else if (ok == PS_TRANSIENT)
1733 suppress_delete = suppress_forward = TRUE;
1734 else if (ok == PS_REFUSED)
1735 suppress_forward = TRUE;
1738 set_timeout(ctl->server.timeout);
1741 * If we're using IMAP4 or something else that
1742 * can fetch headers separately from bodies,
1743 * it's time to request the body now. This
1744 * fetch may be skipped if we got an anti-spam
1745 * or other PS_REFUSED error response during
1748 if (protocol->fetch_body)
1750 if (outlevel == O_VERBOSE)
1751 fputc('\n', stderr);
1753 if ((ok = (protocol->trail)(sock, ctl, num)))
1755 set_timeout(ctl->server.timeout);
1757 if (!suppress_forward)
1759 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1761 if (outlevel > O_SILENT && !wholesize)
1762 error_build(" (%d body bytes) ", len);
1763 set_timeout(ctl->server.timeout);
1767 /* process the body now */
1774 if (ok == PS_TRANSIENT)
1775 suppress_delete = suppress_forward = TRUE;
1778 set_timeout(ctl->server.timeout);
1780 /* tell server we got it OK and resynchronize */
1781 if (protocol->trail)
1783 if (outlevel == O_VERBOSE)
1784 fputc('\n', stderr);
1786 ok = (protocol->trail)(sock, ctl, num);
1789 set_timeout(ctl->server.timeout);
1794 * Check to see if the numbers matched?
1796 * Yes, some servers foo this up horribly.
1797 * All IMAP servers seem to get it right, and
1798 * so does Eudora QPOP at least in 2.xx
1801 * Microsoft Exchange gets it completely
1802 * wrong, reporting compressed rather than
1803 * actual sizes (so the actual length of
1804 * message is longer than the reported size).
1805 * Another fine example of Microsoft brain death!
1807 * Some older POP servers, like the old UCB
1808 * POP server and the pre-QPOP QUALCOMM
1809 * versions, report a longer size in the LIST
1810 * response than actually gets shipped up.
1811 * It's unclear what is going on here, as the
1812 * QUALCOMM server (at least) seems to be
1813 * reporting the on-disk size correctly.
1815 if (msgsizes && msglen != msgsizes[num-1])
1817 if (outlevel >= O_VERBOSE)
1819 "message %d was not the expected length (%d != %d)",
1820 num, msglen, msgsizes[num-1]);
1823 /* end-of-message processing starts here */
1829 /* close the delivery pipe, we'll reopen before next message */
1830 rc = pclose(sinkfp);
1831 signal(SIGCHLD, sigchld);
1834 error(0, -1, "MDA exited abnormally or returned nonzero status");
1838 else if (!suppress_forward)
1840 /* write message terminator */
1841 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
1843 error(0, -1, "SMTP listener refused delivery");
1845 suppress_delete = TRUE;
1853 * At this point in flow of control, either
1854 * we've bombed on a protocol error or had
1855 * delivery refused by the SMTP server
1856 * (unlikely -- I've never seen it) or we've
1857 * seen `accepted for delivery' and the
1858 * message is shipped. It's safe to mark the
1859 * message seen and delete it on the server
1863 /* maybe we delete this message now? */
1866 if (outlevel > O_SILENT)
1867 error_complete(0, 0, " retained");
1869 else if (protocol->delete
1871 && (fetch_it ? !ctl->keep : ctl->flush))
1874 if (outlevel > O_SILENT)
1875 error_complete(0, 0, " flushed");
1876 ok = (protocol->delete)(sock, ctl, num);
1879 set_timeout(ctl->server.timeout);
1880 delete_str(&ctl->newsaved, num);
1882 else if (outlevel > O_SILENT)
1883 error_complete(0, 0, " not flushed");
1885 /* perhaps this as many as we're ready to handle */
1886 if (ctl->fetchlimit > 0 && ctl->fetchlimit <= fetches)
1892 * Only re-poll if we allowed deletions and had no errors.
1893 * Otherwise it is far too easy to get into infinite loops.
1895 (protocol->retry && !ctl->keep && !ctl->errcount);
1899 set_timeout(ctl->server.timeout);
1900 ok = (protocol->logout_cmd)(sock, ctl);
1902 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1908 set_timeout(ctl->server.timeout);
1909 if (ok != 0 && ok != PS_SOCKET)
1910 (protocol->logout_cmd)(sock, ctl);
1915 msg = (char *)NULL; /* sacrifice to -Wall */
1922 msg = "authorization";
1925 msg = "missing or bad RFC822 header";
1931 msg = "client/server synchronization";
1934 msg = "client/server protocol";
1937 msg = "lock busy on server";
1940 msg = "SMTP transaction";
1946 error(0, 0, "undefined");
1949 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
1950 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
1951 || ok==PS_LOCKBUSY || ok==PS_SMTP)
1952 error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
1955 /* execute post-initialization command, if any */
1956 if (ctl->postconnect && (ok = system(ctl->postconnect)))
1960 sprintf(buf, "post-connection command failed with status %d", ok);
1962 if (ok == PS_SUCCESS)
1966 signal(SIGALRM, sigsave);
1970 #if defined(HAVE_STDARG_H)
1971 void gen_send(int sock, char *fmt, ... )
1972 /* assemble command in printf(3) style and send to the server */
1974 void gen_send(sock, fmt, va_alist)
1975 /* assemble command in printf(3) style and send to the server */
1976 int sock; /* socket to which server is connected */
1977 const char *fmt; /* printf-style format */
1981 char buf [POPBUFSIZE+1];
1984 if (protocol->tagged)
1985 (void) sprintf(buf, "%s ", GENSYM);
1989 #if defined(HAVE_STDARG_H)
1994 #ifdef HAVE_VSNPRINTF
1995 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
1997 vsprintf(buf + strlen(buf), fmt, ap);
2001 strcat(buf, "\r\n");
2002 SockWrite(sock, buf, strlen(buf));
2004 if (outlevel == O_VERBOSE)
2008 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2012 sp = cp + strlen(shroud);
2018 buf[strlen(buf)-2] = '\0';
2019 error(0, 0, "%s> %s", protocol->name, buf);
2023 int gen_recv(sock, buf, size)
2024 /* get one line of input from the server */
2025 int sock; /* socket to which server is connected */
2026 char *buf; /* buffer to receive input */
2027 int size; /* length of buffer */
2029 if (SockRead(sock, buf, size) == -1)
2033 if (buf[strlen(buf)-1] == '\n')
2034 buf[strlen(buf)-1] = '\0';
2035 if (buf[strlen(buf)-1] == '\r')
2036 buf[strlen(buf)-1] = '\r';
2037 if (outlevel == O_VERBOSE)
2038 error(0, 0, "%s< %s", protocol->name, buf);
2043 #if defined(HAVE_STDARG_H)
2044 int gen_transact(int sock, char *fmt, ... )
2045 /* assemble command in printf(3) style, send to server, accept a response */
2047 int gen_transact(int sock, fmt, va_alist)
2048 /* assemble command in printf(3) style, send to server, accept a response */
2049 int sock; /* socket to which server is connected */
2050 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)-1] = '\0';
2093 error(0, 0, "%s> %s", protocol->name, buf);
2096 /* we presume this does its own response echoing */
2097 ok = (protocol->parse_response)(sock, buf);
2098 set_timeout(mytimeout);
2103 /* driver.c ends here */