]> Pileus Git - ~andy/fetchmail/blob - driver.c
Added smtpaddress option.
[~andy/fetchmail] / driver.c
1 /*
2  * driver.c -- generic driver for mail fetch method protocols
3  *
4  * Copyright 1997 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #include  <stdio.h>
10 #include  <setjmp.h>
11 #include  <errno.h>
12 #include  <ctype.h>
13 #include  <string.h>
14 #ifdef HAVE_MEMORY_H
15 #include  <memory.h>
16 #endif /* HAVE_MEMORY_H */
17 #if defined(STDC_HEADERS)
18 #include  <stdlib.h>
19 #endif
20 #if defined(HAVE_UNISTD_H)
21 #include <unistd.h>
22 #endif
23 #if defined(HAVE_STDARG_H)
24 #include  <stdarg.h>
25 #else
26 #include  <varargs.h>
27 #endif
28 #if defined(HAVE_ALLOCA_H)
29 #include <alloca.h>
30 #else
31 #ifdef _AIX
32  #pragma alloca
33 #endif
34 #endif
35 #if defined(HAVE_SYS_ITIMER_H)
36 #include <sys/itimer.h>
37 #endif
38 #include  <sys/time.h>
39 #include  <signal.h>
40
41 #ifdef HAVE_GETHOSTBYNAME
42 #include <netdb.h>
43 #include "mx.h"
44 #endif /* HAVE_GETHOSTBYNAME */
45
46 #ifdef KERBEROS_V4
47 #if defined (__bsdi__)
48 #include <des.h> /* order of includes matters */
49 #include <krb.h>
50 #define krb_get_err_text(e) (krb_err_txt[e])
51 #else
52 #if defined(__FreeBSD__) || defined(__linux__)
53 #define krb_get_err_text(e) (krb_err_txt[e])
54 #include <krb.h>
55 #include <des.h>
56 #else
57 #include <krb.h>
58 #include <des.h>
59 #endif /* ! defined (__FreeBSD__) */
60 #endif /* ! defined (__bsdi__) */
61 #include <netinet/in.h>
62 #include <netdb.h>
63 #endif /* KERBEROS_V4 */
64 #include  "fetchmail.h"
65 #include  "socket.h"
66 #include  "smtp.h"
67
68 /* BSD portability hack...I know, this is an ugly place to put it */
69 #if !defined(SIGCHLD) && defined(SIGCLD)
70 #define SIGCHLD SIGCLD
71 #endif
72
73 #define SMTP_PORT       25      /* standard SMTP service port */
74
75 #ifndef strstr          /* glibc-2.1 declares this as a macro */
76 extern char *strstr();  /* needed on sysV68 R3V7.1. */
77 #endif /* strstr */
78
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? */
83
84 static const struct method *protocol;
85 static jmp_buf  restart;
86
87 char tag[TAGLEN];
88 static int tagnum;
89 #define GENSYM  (sprintf(tag, "a%04d", ++tagnum % TAGMOD), tag)
90
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 */
94
95 static void set_timeout(int timeleft)
96 /* reset the nonresponse-timeout */
97 {
98     struct itimerval ntimeout;
99
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);
104 }
105
106 static void timeout_handler (int signal)
107 /* handle server-timeout SIGALRM signal */
108 {
109     longjmp(restart, 1);
110 }
111
112 #define XMIT_ACCEPT             1
113 #define XMIT_REJECT             2
114 #define XMIT_ANTISPAM           3       
115 static int accept_count, reject_count;
116
117 #define MX_RETRIES      3
118
119 static int is_host_alias(const char *name, struct query *ctl)
120 /* determine whether name is a DNS alias of the hostname */
121 {
122     struct hostent      *he;
123     struct mxentry      *mxp, *mxrecords;
124
125     struct hostdata *lead_server = 
126         ctl->server.lead_server ? ctl->server.lead_server : &ctl->server;
127
128     /*
129      * The first two checks are optimizations that will catch a good
130      * many cases.
131      *
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.
136      *
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.
140      *
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.
144      */
145     if (strcmp(lead_server->truename, name) == 0)
146         return(TRUE);
147     else if (str_in_list(&lead_server->akalist, name))
148         return(TRUE);
149     else if (!ctl->server.dns)
150         return(FALSE);
151
152 #ifndef HAVE_RES_SEARCH
153     return(FALSE);
154 #else
155     /*
156      * The only code that calls the BIND library is here and in the
157      * start-of-query probe with gethostbyname(3).
158      *
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.
163      */
164     else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
165     {
166         if (strcmp(ctl->server.truename, he->h_name) == 0)
167             goto match;
168         else
169             return(FALSE);
170     }
171     else
172         switch (h_errno)
173         {
174         case HOST_NOT_FOUND:    /* specified host is unknown */
175         case NO_ADDRESS:        /* valid, but does not have an IP address */
176             break;
177
178         case NO_RECOVERY:       /* non-recoverable name server error */
179         case TRY_AGAIN:         /* temporary error on authoritative server */
180         default:
181             if (outlevel != O_SILENT)
182                 putchar('\n');  /* terminate the progress message */
183             error(0, 0,
184                 "nameserver failure while looking for `%s' during poll of %s.",
185                 name, ctl->server.pollname);
186             ctl->errcount++;
187             break;
188         }
189
190     /*
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.
194      */
195     h_errno = 0;
196     if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
197     {
198         switch (h_errno)
199         {
200         case HOST_NOT_FOUND:    /* specified host is unknown */
201         case NO_ADDRESS:        /* valid, but does not have an IP address */
202             return(FALSE);
203             break;
204
205         case NO_RECOVERY:       /* non-recoverable name server error */
206         case TRY_AGAIN:         /* temporary error on authoritative server */
207         default:
208             error(0, -1,
209                 "nameserver failure while looking for `%s' during poll of %s.",
210                 name, ctl->server.pollname);
211             ctl->errcount++;
212             break;
213         }
214     }
215     else
216     {
217         for (mxp = mxrecords; mxp->name; mxp++)
218             if (strcmp(ctl->server.truename, mxp->name) == 0)
219                 goto match;
220         return(FALSE);
221     match:;
222     }
223
224     /* add this name to relevant server's `also known as' list */
225     save_str(&lead_server->akalist, -1, name);
226     return(TRUE);
227 #endif /* HAVE_RES_SEARCH */
228 }
229
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 */
235 {
236     const char  *lname;
237     int sl;
238     int off = 0;
239     
240     lname = idpair_find(&ctl->localnames, name);
241     if (!lname && ctl->wildcard)
242         lname = name;
243
244     if (lname != (char *)NULL)
245     {
246         /* 
247          * If the name of the user begins with a 
248          * qmail virtual domain prefix, remove
249          * the prefix
250          */
251         if (ctl->server.qvirtual)
252         {
253            sl=strlen(ctl->server.qvirtual);
254            if (!strncasecmp(lname,ctl->server.qvirtual,sl)) off=sl; 
255         }
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);
259         accept_count++;
260     }
261 }
262
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 */
268 {
269     if (hdr == (char *)NULL)
270         return;
271     else
272     {
273         char    *cp;
274
275         if ((cp = nxtaddr(hdr)) != (char *)NULL)
276             do {
277                 char    *atsign;
278
279                 if ((atsign = strchr(cp, '@')))
280                 {
281                     struct idlist       *idp;
282
283                     /*
284                      * Does a trailing segment of the hostname match something
285                      * on the localdomains list?  If so, save the whole name
286                      * and keep going.
287                      */
288                     for (idp = ctl->server.localdomains; idp; idp = idp->next)
289                     {
290                         char    *rhs;
291
292                         rhs = atsign + (strlen(atsign) - strlen(idp->id));
293                         if ((rhs[-1] == '.' || rhs[-1] == '@')
294                                         && strcasecmp(rhs, idp->id) == 0)
295                         {
296                             if (outlevel == O_VERBOSE)
297                                 error(0, 0, "passed through %s matching %s", 
298                                       cp, idp->id);
299                             save_str(xmit_names, XMIT_ACCEPT, cp);
300                             accept_count++;
301                             continue;
302                         }
303                     }
304
305                     /*
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.
310                      */
311                     if (!is_host_alias(atsign+1, ctl))
312                     {
313                         save_str(xmit_names, XMIT_REJECT, cp);
314                         reject_count++;
315                         continue;
316                     }
317                     atsign[0] = '\0';
318                 }
319
320                 map_name(cp, ctl, xmit_names);
321             } while
322                 ((cp = nxtaddr((char *)NULL)) != (char *)NULL);
323     }
324 }
325
326 static char *parse_received(struct query *ctl, char *bufp)
327 /* try to extract real addressee from the Received line */
328 {
329     char *ok = (char *)NULL;
330     static char rbuf[HOSTLEN + USERNAMELEN + 4]; 
331
332     /*
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.
339      */
340     if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
341     {
342         char    *sp, *tp;
343
344         /* extract space-delimited token after "by " */
345         for (sp = ok + 3; isspace(*sp); sp++)
346             continue;
347         tp = rbuf;
348         for (; !isspace(*sp); sp++)
349             *tp++ = *sp;
350         *tp = '\0';
351
352         /*
353          * If it's a DNS name of the mail server, look for the
354          * recipient name after a following "for".  Otherwise
355          * punt.
356          */
357         if (!is_host_alias(rbuf, ctl))
358             ok = (char *)NULL;
359         else if ((ok = strstr(sp, "for ")) && isspace(ok[-1]))
360         {
361             tp = rbuf;
362             sp = ok + 4;
363             if (*sp == '<')
364                 sp++;
365             while (*sp == '@')          /* skip routes */
366                 while (*sp++ != ':')
367                     continue;
368             while (*sp && *sp != '>' && *sp != '@' && *sp != ';')
369                 if (!isspace(*sp))
370                     *tp++ = *sp++;
371                 else
372                 {
373                     /* uh oh -- whitespace here can't be right! */
374                     ok = (char *)NULL;
375                     break;
376                 }
377             *tp = '\0';
378         }
379     }
380
381     if (!ok)
382         return(NULL);
383     else
384     {
385         if (outlevel == O_VERBOSE)
386             error(0, 0, "found Received address `%s'", rbuf);
387         return(rbuf);
388     }
389 }
390
391 static int smtp_open(struct query *ctl)
392 /* try to open a socket to the appropriate SMTP server for this query */ 
393 {
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)
396     {
397         close(ctl->smtp_socket);
398         ctl->smtp_socket = -1;
399         batchcount = 0;
400     }
401
402     /* if no socket to any SMTP host is already set up, try to open one */
403     if (ctl->smtp_socket == -1) 
404     {
405         /* 
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.
411          *
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).
415          *
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.
422          */
423         struct idlist   *idp;
424         char *id_me = use_invisible ? ctl->server.truename : fetchmailhost;
425
426         errno = 0;
427
428         /*
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).
432          */
433         for (idp = ctl->smtphunt; idp; idp = idp->next)
434         {
435             ctl->smtphost = idp->id;  /* remember last host tried. */
436
437             if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
438                 continue;
439
440             if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
441                     SMTP_ehlo(ctl->smtp_socket, id_me,
442                           &ctl->server.esmtp_options) == SM_OK)
443                break;  /* success */
444
445             /*
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.
448              */
449             close(ctl->smtp_socket);
450             ctl->smtp_socket = -1;
451
452             /* if opening for ESMTP failed, try SMTP */
453             if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
454                 continue;
455
456             if (SMTP_ok(ctl->smtp_socket) == SM_OK && 
457                     SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
458                 break;  /* success */
459
460             close(ctl->smtp_socket);
461             ctl->smtp_socket = -1;
462         }
463     }
464
465     if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
466         error(0, 0, "forwarding to SMTP port on %s", ctl->smtphost);
467
468     return(ctl->smtp_socket);
469 }
470
471 /* these are shared by stuffline, readheaders and readbody */
472 static FILE *sinkfp;
473 static RETSIGTYPE (*sigchld)();
474 static int sizeticker;
475
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) */
478 {
479     int n;
480     char *last;
481
482     /* The line may contain NUL characters. Find the last char to use
483      * -- the real line termination is the sequence "\n\0".
484      */
485     last = buf;
486     while ((last += strlen(last)) && (last[-1] != '\n'))
487         last++;
488
489     /* fix message lines that have only \n termination (for qmail) */
490     if (ctl->forcecr)
491     {
492         if (last - 1 == buf || last[-2] != '\r')
493         {
494             last[-1] = '\r';
495             *last++  = '\n';
496             *last    = '\0';
497         }
498     }
499
500     /*
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.
504      */
505     if (*buf == '.')
506         if (protocol->delimited)        /* server has already byte-stuffed */
507         {
508             if (ctl->mda)
509                 ++buf;
510             else
511                 /* writing to SMTP, leave the byte-stuffing in place */;
512         }
513         else /* if (!protocol->delimited)       -- not byte-stuffed already */
514         {
515             if (!ctl->mda)
516                 SockWrite(ctl->smtp_socket, buf, 1);    /* byte-stuff it */
517             else
518                 /* leave it alone */;
519         }
520
521     /* we may need to strip carriage returns */
522     if (ctl->stripcr)
523     {
524         char    *sp, *tp;
525
526         for (sp = tp = buf; sp < last; sp++)
527             if (*sp != '\r')
528                 *tp++ =  *sp;
529         *tp = '\0';
530         last = tp;
531     }
532
533     n = 0;
534     if (ctl->mda)
535         n = fwrite(buf, 1, last - buf, sinkfp);
536     else if (ctl->smtp_socket != -1)
537         n = SockWrite(ctl->smtp_socket, buf, last - buf);
538
539     return(n);
540 }
541
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 */
549 {
550     struct addrblk
551     {
552         int             offset;
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;
559     char                *cp;
560     struct idlist       *idp, *xmit_names;
561     flag                good_addresses, bad_addresses, has_nuls;
562     flag                no_local_matches = FALSE;
563     int                 olderrs;
564
565     next_address = sizeticker = 0;
566     has_nuls = FALSE;
567     return_path[0] = '\0';
568     olderrs = ctl->errcount;
569
570     /* read message headers */
571     headers = received_for = NULL;
572     from_offs = ctt_offs = env_offs = -1;
573     oldlen = 0;
574     msglen = 0;
575     skipcount = 0;
576
577     for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
578     {
579         char *line;
580
581         line = xmalloc(sizeof(buf));
582         linelen = 0;
583         line[0] = '\0';
584         do {
585             if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1)
586                 return(PS_SOCKET);
587             linelen += n;
588             msglen += n;
589
590             /* lines may not be properly CRLF terminated; fix this for qmail */
591             if (ctl->forcecr)
592             {
593                 cp = buf + strlen(buf) - 1;
594                 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
595                 {
596                     *cp++ = '\r';
597                     *cp++ = '\n';
598                     *cp++ = '\0';
599                 }
600             }
601
602             set_timeout(ctl->server.timeout);
603
604             line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
605
606             strcat(line, buf);
607             if (line[0] == '\r' && line[1] == '\n')
608                 break;
609         } while
610             /* we may need to grab RFC822 continuations */
611             ((ch = SockPeek(sock)) == ' ' || ch == '\t');
612
613         /* write the message size dots */
614         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
615         {
616             sizeticker += linelen;
617             while (sizeticker >= SIZETICKER)
618             {
619                 error_build(".");
620                 sizeticker -= SIZETICKER;
621             }
622         }
623
624         if (linelen != strlen(line))
625             has_nuls = TRUE;
626
627         /* check for end of headers; don't save terminating line */
628         if (line[0] == '\r' && line[1] == '\n')
629         {
630             free(line);
631             break;
632         }
633      
634         /*
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.
640          */
641 #ifdef POP2_ENABLE
642         /*
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.
647          */
648         if (protocol->port != 109)
649 #endif /* POP2_ENABLE */
650             if (num == 1 && !strncasecmp(line, "X-IMAP:", 7))
651                 return(PS_RETAINED);
652
653         /*
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.
660          *
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,
664          * followed by text.
665          *
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...
669          */
670         if (!strncasecmp(line, ">From ", 6))
671         {
672             free(line);
673             continue;
674         }
675
676         /*
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.
683          *
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.
689          */
690         if (!strncasecmp(line, "Status:", 7))
691         {
692             char        *cp;
693
694             for (cp = line + 7; *cp && isspace(*cp); cp++)
695                 continue;
696
697             if (!*cp || ctl->dropstatus)
698             {
699                 free(line);
700                 continue;
701             }
702         }
703
704         /*
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
710          * delivery.
711          *
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.
715          *
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.
719          */
720         if (!ctl->mda && !strncasecmp("Return-Path:", line, 12))
721         {
722             strcpy(return_path, nxtaddr(line));
723             free(line);
724             continue;
725         }
726
727         if (ctl->rewrite)
728             line = reply_hack(line, ctl->server.truename);
729
730         if (!headers)
731         {
732             oldlen = strlen(line);
733             headers = xmalloc(oldlen + 1);
734             (void) strcpy(headers, line);
735             free(line);
736             line = headers;
737         }
738         else
739         {
740             int newlen;
741
742             newlen = oldlen + strlen(line);
743             headers = (char *) realloc(headers, newlen + 1);
744             if (headers == NULL)
745                 return(PS_IOERR);
746             strcpy(headers + oldlen, line);
747             free(line);
748             line = headers + oldlen;
749             oldlen = newlen;
750         }
751
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 ))
761         {
762             if( ctl->server.uidl )
763             {
764                 char id[IDLEN+1];
765                 /* prevent stack overflows */
766                 buf[IDLEN+12] = 0;
767                 sscanf( buf+12, "%s", id);
768                 if( !str_find( &ctl->newsaved, num ) )
769                     save_str(&ctl->newsaved, num, id );
770             }
771         }
772
773         else if (!MULTIDROP(ctl))
774             continue;
775
776         else if (!strncasecmp("To:", line, 3)
777                         || !strncasecmp("Cc:", line, 3)
778                         || !strncasecmp("Bcc:", line, 4))
779         {
780             *chainptr = xmalloc(sizeof(struct addrblk));
781             (*chainptr)->offset = (line - headers);
782             chainptr = &(*chainptr)->next; 
783             *chainptr = NULL;
784         }
785
786         else if (ctl->server.envelope != STRING_DISABLED)
787         {
788             if (ctl->server.envelope 
789                         && strcasecmp(ctl->server.envelope, "received"))
790             {
791                 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
792                                                 line,
793                                                 strlen(ctl->server.envelope)))
794                 {                               
795                     if (skipcount++ != ctl->server.envskip)
796                         continue;
797                     env_offs = (line - headers);
798                 }    
799             }
800             else if (!received_for && !strncasecmp("Received:", line, 9))
801             {
802                 if (skipcount++ != ctl->server.envskip)
803                     continue;
804                 received_for = parse_received(ctl, line);
805             }
806         }
807     }
808
809     /*
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.  
813      *
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.
817      */
818     if (headers == (char *)NULL)
819     {
820 #ifdef HAVE_SNPRINTF
821         snprintf(buf, sizeof(buf),
822 #else
823         sprintf(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);
828     }
829
830     /*
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.
833      */
834
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? */
839     if (MULTIDROP(ctl))
840     {
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)
844             /*
845              * We have the Received for addressee.  
846              * It has to be a mailserver address, or we
847              * wouldn't have got here.
848              */
849             map_name(received_for, ctl, &xmit_names);
850         else
851         {
852             /*
853              * We haven't extracted the envelope address.
854              * So check all the header addresses.
855              */
856             while (addrchain)
857             {
858                 register struct addrblk *nextptr;
859
860                 find_server_names(headers+addrchain->offset, ctl, &xmit_names);
861                 nextptr = addrchain->next;
862                 free(addrchain);
863                 addrchain = nextptr;
864             }
865         }
866         if (!accept_count)
867         {
868             no_local_matches = TRUE;
869             save_str(&xmit_names, XMIT_ACCEPT, user);
870             if (outlevel == O_VERBOSE)
871                 error(0, 0, 
872                       "no local matches, forwarding to %s",
873                       user);
874         }
875     }
876     else        /* it's a single-drop box, use first localname */
877         save_str(&xmit_names, XMIT_ACCEPT, ctl->localnames->id);
878
879
880     /*
881      * Time to either address the message or decide we can't deliver it yet.
882      */
883     if (ctl->errcount > olderrs)        /* there were DNS errors above */
884     {
885         if (outlevel == O_VERBOSE)
886             error(0,0, "forwarding and deletion suppressed due to DNS errors");
887         free(headers);
888         return(PS_TRANSIENT);
889     }
890     else if (ctl->mda)          /* we have a declared MDA */
891     {
892         int     length = 0;
893         char    *names, *before, *after;
894
895         for (idp = xmit_names; idp; idp = idp->next)
896             if (idp->val.num == XMIT_ACCEPT)
897                 good_addresses++;
898
899         destaddr = "localhost";
900
901         length = strlen(ctl->mda) + 1;
902         before = xstrdup(ctl->mda);
903
904         /* sub user addresses for %T (or %s for backward compatibility) */
905         cp = (char *)NULL;
906         if (strstr(before, "%s") || (cp = strstr(before, "%T")))
907         {
908             char        *sp;
909
910             if (cp && cp[1] == 'T')
911                 cp[1] = 's';
912
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')
916                     *sp = '\177';
917
918             /*
919              * We go through this in order to be able to handle very
920              * long lists of users and (re)implement %s.
921              */
922             for (idp = xmit_names; idp; idp = idp->next)
923                 if (idp->val.num == XMIT_ACCEPT)
924                     length += (strlen(idp->id) + 1);
925
926             names = (char *)xmalloc(++length);
927             names[0] = '\0';
928             for (idp = xmit_names; idp; idp = idp->next)
929                 if (idp->val.num == XMIT_ACCEPT)
930                 {
931                     strcat(names, idp->id);
932                     strcat(names, " ");
933                 }
934             after = (char *)xmalloc(length);
935 #ifdef SNPRINTF
936             snprintf(after, length, before, names);
937 #else
938             sprintf(after, before, names);
939 #endif /* SNPRINTF */
940             free(names);
941             free(before);
942             before = after;
943
944             for (sp = before; *sp; sp++)
945                 if (*sp == '\177')
946                     *sp = '%';
947         }
948
949         /* substitute From address for %F */
950         if ((cp = strstr(before, "%F")))
951         {
952             char *from = nxtaddr(headers + from_offs);
953             char        *sp;
954
955             /* \177 had better be out-of-band for MDA commands */
956             for (sp = before; *sp; sp++)
957                 if (*sp == '%' && sp[1] != 'F')
958                     *sp = '\177';
959
960             length += strlen(from);
961             after = (char *)xmalloc(length);
962             cp[1] = 's';
963 #ifdef SNPRINTF
964             snprintf(after, length, before, from);
965 #else
966             sprintf(after, before, from);
967 #endif /* SNPRINTF */
968             free(before);
969             before = after;
970
971             for (sp = before; *sp; sp++)
972                 if (*sp == '\177')
973                     *sp = '%';
974         }
975
976         if (outlevel == O_VERBOSE)
977             error(0, 0, "about to deliver with: %s", before);
978
979 #ifdef HAVE_SETEUID
980         /*
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)
985          */
986         seteuid(ctl->uid);
987 #endif /* HAVE_SETEUID */
988
989         sinkfp = popen(before, "w");
990         free(before);
991
992 #ifdef HAVE_SETEUID
993         /* this will fail quietly if we didn't start as root */
994         seteuid(0);
995 #endif /* HAVE_SETEUID */
996
997         if (!sinkfp)
998         {
999             error(0, 0, "MDA open failed");
1000             return(PS_IOERR);
1001         }
1002
1003         sigchld = signal(SIGCHLD, SIG_DFL);
1004     }
1005     else
1006     {
1007         char    *ap, *ctt, options[MSGBUFSIZE], addr[128];
1008
1009         /* build a connection to the SMTP listener */
1010         if ((smtp_open(ctl) == -1))
1011         {
1012             error(0, errno, "SMTP connect to %s failed",
1013                   ctl->smtphost ? ctl->smtphost : "localhost");
1014             free_str_list(&xmit_names);
1015             return(PS_SMTP);
1016         }
1017
1018         /*
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.
1023          */
1024         options[0] = '\0';
1025         if (ctl->server.esmtp_options & ESMTP_8BITMIME)
1026             if (ctl->pass8bits)
1027                 strcpy(options, " BODY=8BITMIME");
1028             else if ((ctt_offs >= 0) && (ctt = nxtaddr(headers + ctt_offs)))
1029             {
1030                 if (!strcasecmp(ctt,"7BIT"))
1031                     strcpy(options, " BODY=7BIT");
1032                 else if (!strcasecmp(ctt,"8BIT"))
1033                     strcpy(options, " BODY=8BITMIME");
1034             }
1035         if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
1036             sprintf(options + strlen(options), " SIZE=%ld", reallen);
1037
1038         /*
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.
1044          *
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.
1049          *
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.
1056          *
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.
1060          */
1061         ap = (char *)NULL;
1062         if (return_path[0])
1063             ap = return_path;
1064         else if (from_offs == -1 || !(ap = nxtaddr(headers + from_offs)))
1065             ap = user;
1066         if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
1067         {
1068             int smtperr = atoi(smtp_response);
1069
1070             /*
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.
1074              */
1075             if (smtperr >= 400 && smtperr != 571)
1076                 error(0, -1, "SMTP error: %s", smtp_response);
1077
1078             switch (smtperr)
1079             {
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) */
1083                 /*
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.
1089                  */
1090                 free(headers);
1091                 return(PS_REFUSED);
1092
1093             case 452: /* insufficient system storage */
1094                 /*
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.
1099                  */
1100                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
1101                 free(headers);
1102                 return(PS_TRANSIENT);
1103
1104             case 552: /* message exceeds fixed maximum message size */
1105                 /*
1106                  * Permanent no-go condition on the
1107                  * ESMTP server.  Don't try to ship the message, 
1108                  * and allow it to be deleted.
1109                  */
1110                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
1111                 free(headers);
1112                 return(PS_REFUSED);
1113
1114             default:    /* retry with invoking user's address */
1115                 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1116                 {
1117                     error(0, -1, "SMTP error: %s", smtp_response);
1118                     free(headers);
1119                     return(PS_SMTP);    /* should never happen */
1120                 }
1121             }
1122         }
1123
1124         /*
1125          * Now list the recipient addressees
1126          *
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)
1130          * enforce this.
1131          */
1132         destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
1133         
1134         for (idp = xmit_names; idp; idp = idp->next)
1135             if (idp->val.num == XMIT_ACCEPT)
1136             {
1137                 if (strchr(idp->id, '@'))
1138                     strcpy(addr, idp->id);
1139                 else
1140 #ifdef HAVE_SNPRINTF
1141                     snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, destaddr);
1142 #else
1143                     sprintf(addr, "%s@%s", idp->id, destaddr);
1144 #endif /* HAVE_SNPRINTF */
1145
1146                 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1147                     good_addresses++;
1148                 else
1149                 {
1150                     bad_addresses++;
1151                     idp->val.num = XMIT_ANTISPAM;
1152                     error(0, 0, 
1153                           "SMTP listener doesn't like recipient address `%s@%s'", idp->id, destaddr);
1154                 }
1155             }
1156         if (!good_addresses)
1157         {
1158 #ifdef HAVE_SNPRINTF
1159             snprintf(addr, sizeof(addr)-1, "%s@%s", user, destaddr);
1160 #else
1161             sprintf(addr, "%s@%s", user, destaddr);
1162 #endif /* HAVE_SNPRINTF */
1163
1164             if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1165             {
1166                 error(0, 0, "can't even send to calling user!");
1167                 free(headers);
1168                 return(PS_SMTP);
1169             }
1170         }
1171
1172         /* tell it we're ready to send data */
1173         SMTP_data(ctl->smtp_socket);
1174     }
1175
1176     n = 0;
1177     /*
1178      * Some server/sendmail combinations cause problems when our
1179      * synthetic Received line is before the From header.  Cope
1180      * with this...
1181      */
1182     if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
1183         rcv = headers;
1184     if (rcv > headers)
1185     {
1186         *rcv = '\0';
1187         n = stuffline(ctl, headers);
1188         *rcv = 'R';
1189     }
1190     if (!use_invisible && n != -1)
1191     {
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);
1195         if (n != -1)
1196         {
1197             /*
1198              * We used to include ctl->remotename in this log line,
1199              * but this can be secure information that would be bad
1200              * to reveal.
1201              */
1202             sprintf(buf, "\tby %s (fetchmail-%s %s)\n",
1203                     fetchmailhost, 
1204                     RELEASE_ID,
1205                     protocol->name);
1206             n = stuffline(ctl, buf);
1207             if (n != -1)
1208             {
1209                 time_t  now;
1210
1211                 buf[0] = '\t';
1212                 if (good_addresses == 0)
1213                 {
1214                     sprintf(buf+1, 
1215                             "for <%s@%s> (by default); ",
1216                             user, destaddr);
1217                 }
1218                 else if (good_addresses == 1)
1219                 {
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); ",
1224                             idp->id, destaddr,
1225                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1226                 }
1227                 else
1228                     buf[1] = '\0';
1229
1230                 time(&now);
1231 #ifdef HAVE_STRFTIME
1232                 /*
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.
1237                  */
1238                 strftime(buf + strlen(buf), sizeof(buf) - strlen(buf), 
1239                          "%a, %d %b %Y %H:%M:%S %Z\n", localtime(&now));
1240 #else
1241                 /*
1242                  * This is really just a portability fallback, as the
1243                  * date format ctime(3) emits is not RFC822
1244                  * conformant.
1245                  */
1246                 strcat(buf, ctime(&now));
1247 #endif /* HAVE_STRFTIME */
1248                 n = stuffline(ctl, buf);
1249             }
1250         }
1251     }
1252
1253     if (n != -1)
1254         n = stuffline(ctl, rcv);        /* ship out rest of headers */
1255
1256     if (n == -1)
1257     {
1258         error(0, errno, "writing RFC822 headers");
1259         if (ctl->mda)
1260         {
1261             if (sinkfp)
1262                 pclose(sinkfp);
1263             signal(SIGCHLD, sigchld);
1264         }
1265         return(PS_IOERR);
1266     }
1267     else if (outlevel == O_VERBOSE)
1268         fputs("#", stderr);
1269
1270     /* write error notifications */
1271     if (no_local_matches || has_nuls || bad_addresses)
1272     {
1273         int     errlen = 0;
1274         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1275
1276         errmsg = errhd;
1277         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1278         if (no_local_matches)
1279         {
1280             if (reject_count != 1)
1281                 strcat(errhd, "no recipient addresses matched declared local names");
1282             else
1283             {
1284                 for (idp = xmit_names; idp; idp = idp->next)
1285                     if (idp->val.num == XMIT_REJECT)
1286                         break;
1287                 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1288             }
1289         }
1290
1291         if (has_nuls)
1292         {
1293             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1294                 strcat(errhd, "; ");
1295             strcat(errhd, "message has embedded NULs");
1296         }
1297
1298         if (bad_addresses)
1299         {
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;
1307
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)
1312                 {
1313                     strcat(errmsg, idp->id);
1314                     if (idp->next)
1315                         strcat(errmsg, ", ");
1316                 }
1317
1318         }
1319
1320         strcat(errmsg, "\n");
1321
1322         /* ship out the error line */
1323         if (sinkfp)
1324             stuffline(ctl, errmsg);
1325     }
1326
1327     free_str_list(&xmit_names);
1328
1329     /* issue the delimiter line */
1330     cp = buf;
1331     *cp++ = '\r';
1332     *cp++ = '\n';
1333     *cp++ = '\0';
1334     stuffline(ctl, buf);
1335
1336     return(PS_SUCCESS);
1337 }
1338
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 */
1345 {
1346     int linelen;
1347     char buf[MSGBUFSIZE+1];
1348
1349     /* pass through the text lines */
1350     while (protocol->delimited || len > 0)
1351     {
1352         if ((linelen = SockRead(sock, buf, sizeof(buf)-1)) == -1)
1353         {
1354             if (ctl->mda)
1355             {
1356                 if (sinkfp)
1357                     pclose(sinkfp);
1358                 signal(SIGCHLD, sigchld);
1359             }
1360             return(PS_SOCKET);
1361         }
1362         set_timeout(ctl->server.timeout);
1363
1364         /* write the message size dots */
1365         if (linelen > 0)
1366         {
1367             sizeticker += linelen;
1368             while (sizeticker >= SIZETICKER)
1369             {
1370                 if (outlevel > O_SILENT)
1371                     error_build(".");
1372                 sizeticker -= SIZETICKER;
1373             }
1374         }
1375         len -= linelen;
1376
1377         /* check for end of message */
1378         if (protocol->delimited && *buf == '.')
1379             if (buf[1] == '\r' && buf[2] == '\n' && buf[3] == '\0')
1380                 break;
1381             else if (buf[1] == '\n' && buf[2] == '\0')
1382                 break;
1383             else
1384                 msglen--;       /* subtract the size of the dot escape */
1385
1386         msglen += linelen;
1387
1388         /* ship out the text line */
1389         if (forward)
1390         {
1391             int n = stuffline(ctl, buf);
1392
1393             if (n < 0)
1394             {
1395                 error(0, errno, "writing message text");
1396                 if (ctl->mda)
1397                 {
1398                     if (sinkfp)
1399                         pclose(sinkfp);
1400                     signal(SIGCHLD, sigchld);
1401                 }
1402                 return(PS_IOERR);
1403             }
1404             else if (outlevel == O_VERBOSE)
1405                 fputc('*', stderr);
1406         }
1407     }
1408
1409     return(PS_SUCCESS);
1410 }
1411
1412 #ifdef KERBEROS_V4
1413 int
1414 kerberos_auth (socket, canonical) 
1415 /* authenticate to the server host using Kerberos V4 */
1416 int socket;             /* socket to server host */
1417 #ifdef __FreeBSD__
1418 char *canonical;        /* server name */
1419 #else
1420 const char *canonical;  /* server name */
1421 #endif
1422 {
1423     char * host_primary;
1424     KTEXT ticket;
1425     MSG_DAT msg_data;
1426     CREDENTIALS cred;
1427     Key_schedule schedule;
1428     int rem;
1429   
1430     ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1431     rem = (krb_sendauth (0L, socket, ticket, "pop",
1432                          canonical,
1433                          ((char *) (krb_realmofhost (canonical))),
1434                          ((unsigned long) 0),
1435                          (&msg_data),
1436                          (&cred),
1437                          (schedule),
1438                          ((struct sockaddr_in *) 0),
1439                          ((struct sockaddr_in *) 0),
1440                          "KPOPV0.1"));
1441     free (ticket);
1442     if (rem != KSUCCESS)
1443     {
1444         error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1445         return (PS_AUTHFAIL);
1446     }
1447     return (0);
1448 }
1449 #endif /* KERBEROS_V4 */
1450
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 */
1455 {
1456     int ok, js, sock = -1;
1457     char *msg;
1458     void (*sigsave)();
1459
1460 #ifndef KERBEROS_V4
1461     if (ctl->server.preauthenticate == A_KERBEROS_V4)
1462     {
1463         error(0, -1, "Kerberos V4 support not linked.");
1464         return(PS_ERROR);
1465     }
1466 #endif /* KERBEROS_V4 */
1467
1468     /* lacking methods, there are some options that may fail */
1469     if (!proto->is_old)
1470     {
1471         /* check for unsupported options */
1472         if (ctl->flush) {
1473             error(0, 0,
1474                     "Option --flush is not supported with %s",
1475                     proto->name);
1476             return(PS_SYNTAX);
1477         }
1478         else if (ctl->fetchall) {
1479             error(0, 0,
1480                     "Option --all is not supported with %s",
1481                     proto->name);
1482             return(PS_SYNTAX);
1483         }
1484     }
1485     if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1486     {
1487         error(0, 0,
1488                 "Option --limit is not supported with %s",
1489                 proto->name);
1490         return(PS_SYNTAX);
1491     }
1492
1493     protocol = proto;
1494     pass = 0;
1495     tagnum = 0;
1496     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1497     ok = 0;
1498
1499     /* set up the server-nonresponse timeout */
1500     sigsave = signal(SIGALRM, timeout_handler);
1501     set_timeout(mytimeout = ctl->server.timeout);
1502
1503     if ((js = setjmp(restart)) == 1)
1504     {
1505         error(0, 0,
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);
1510         if (sock != -1)
1511             close(sock);
1512         ok = PS_ERROR;
1513     }
1514     else
1515     {
1516         char buf [POPBUFSIZE+1], *realhost;
1517         int *msgsizes, len, num, count, new, deletions = 0;
1518         int port, fetches, dispatches;
1519         struct idlist *idp;
1520
1521         /* execute pre-initialization command, if any */
1522         if (ctl->preconnect && (ok = system(ctl->preconnect)))
1523         {
1524             sprintf(buf, "pre-connection command failed with status %d", ok);
1525             error(0, 0, buf);
1526             ok = PS_SYNTAX;
1527             goto closeUp;
1528         }
1529
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)
1534         {
1535 #ifndef EHOSTUNREACH
1536 #define EHOSTUNREACH (-1)
1537 #endif
1538             if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1539             {
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");
1550                 else if (h_errno)
1551                     error_complete(0, 0, "unknown DNS error %d", h_errno);
1552                 else
1553                     error_complete(0, errno, "local error");
1554             }
1555             ok = PS_SOCKET;
1556             goto closeUp;
1557         }
1558
1559 #ifdef KERBEROS_V4
1560         if (ctl->server.preauthenticate == A_KERBEROS_V4)
1561         {
1562             ok = kerberos_auth(sock, ctl->server.truename);
1563             if (ok != 0)
1564                 goto cleanUp;
1565             set_timeout(ctl->server.timeout);
1566         }
1567 #endif /* KERBEROS_V4 */
1568
1569         /* accept greeting message from mail server */
1570         ok = (protocol->parse_response)(sock, buf);
1571         if (ok != 0)
1572             goto cleanUp;
1573         set_timeout(ctl->server.timeout);
1574
1575         /* try to get authorized to fetch mail */
1576         if (protocol->getauth)
1577         {
1578             shroud = ctl->password;
1579             ok = (protocol->getauth)(sock, ctl, buf);
1580             shroud = (char *)NULL;
1581             if (ok != 0)
1582             {
1583                 if (ok == PS_LOCKBUSY)
1584                     error(0, -1, "Lock-busy error on %s@%s",
1585                           ctl->remotename,
1586                           ctl->server.truename);
1587                 else
1588                 {
1589                     if (ok == PS_ERROR)
1590                         ok = PS_AUTHFAIL;
1591                     error(0, -1, "Authorization failure on %s@%s", 
1592                           ctl->remotename,
1593                           ctl->server.truename);
1594                 }
1595                 goto cleanUp;
1596             }
1597             set_timeout(ctl->server.timeout);
1598         }
1599
1600         ctl->errcount = fetches = 0;
1601
1602         /* now iterate over each folder selected */
1603         for (idp = ctl->mailboxes; idp; idp = idp->next)
1604         {
1605             pass = 0;
1606             do {
1607                 dispatches = 0;
1608                 ++pass;
1609
1610                 if (outlevel >= O_VERBOSE)
1611                     if (idp->id)
1612                         error(0, 0, "selecting or re-polling folder %s", idp->id);
1613                     else
1614                         error(0, 0, "selecting or re-polling default folder");
1615
1616                 /* compute # of messages and number of new messages waiting */
1617                 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new);
1618                 if (ok != 0)
1619                     goto cleanUp;
1620                 set_timeout(ctl->server.timeout);
1621
1622                 /* show user how many messages we downloaded */
1623                 if (idp->id)
1624                     (void) sprintf(buf, "%s at %s (folder %s)",
1625                                    ctl->remotename, ctl->server.truename, idp->id);
1626                 else
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)
1632                     {
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);
1636                         else
1637                             error(0, 0, "%d message%s for %s.", 
1638                                   count, count > 1 ? "s" : "", buf);
1639                     }
1640                     else
1641                     {
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); 
1645                     }
1646
1647                 /* very important, this is where we leave the do loop */ 
1648                 if (count == 0)
1649                     break;
1650
1651                 if (check_only)
1652                 {
1653                     if (new == -1 || ctl->fetchall)
1654                         new = count;
1655                     ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1656                     goto cleanUp;
1657                 }
1658                 else if (count > 0)
1659                 {    
1660                     flag        force_retrieval;
1661
1662                     /*
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
1667                      * convey this).
1668                      *
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
1676                      * clued in.
1677                      *
1678                      * But in daemon mode this leads to the message
1679                      * being silently ignored forever.  This is not
1680                      * acceptable.
1681                      *
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.
1685                      */
1686                     force_retrieval = !peek_capable && (ctl->errcount > 0);
1687
1688                     /* 
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.
1694                      */
1695                     if (proto->getsizes)
1696                     {
1697                         int     i;
1698
1699                         msgsizes = (int *)alloca(sizeof(int) * count);
1700                         for (i = 0; i < count; i++)
1701                             msgsizes[i] = -1;
1702
1703                         ok = (proto->getsizes)(sock, count, msgsizes);
1704                         if (ok != 0)
1705                             goto cleanUp;
1706                         set_timeout(ctl->server.timeout);
1707                     }
1708
1709                     /* read, forward, and delete messages */
1710                     for (num = 1; num <= count; num++)
1711                     {
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;
1719
1720                         /*
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
1728                          * the message.
1729                          */
1730                         if (msgsizes && msgsizes[num-1] == -1)
1731                         {
1732                             if (outlevel >= O_VERBOSE)
1733                                 error(0, 0, 
1734                                       "Skipping message %d, length -1",
1735                                       num - 1);
1736                             continue;
1737                         }
1738
1739                         /* we may want to reject this message if it's old */
1740                         if (!fetch_it)
1741                         {
1742                             if (outlevel > O_SILENT)
1743                             {
1744                                 error_build("skipping message %d", num);
1745                                 if (toolarge)
1746                                     error_build(" (oversized, %d bytes)",
1747                                                 msgsizes[num-1]);
1748                             }
1749                         }
1750                         else
1751                         {
1752                             flag wholesize = !protocol->fetch_body;
1753
1754                             /* request a message */
1755                             ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1756                             if (ok != 0)
1757                                 goto cleanUp;
1758                             set_timeout(ctl->server.timeout);
1759
1760                             /* -1 means we didn't see a size in the response */
1761                             if (len == -1 && msgsizes)
1762                             {
1763                                 len = msgsizes[num - 1];
1764                                 wholesize = TRUE;
1765                             }
1766
1767                             if (outlevel > O_SILENT)
1768                             {
1769                                 error_build("reading message %d of %d",
1770                                             num,count);
1771
1772                                 if (len > 0)
1773                                     error_build(" (%d %sbytes)",
1774                                         len, wholesize ? "" : "header ");
1775                                 if (outlevel == O_VERBOSE)
1776                                     error_complete(0, 0, "");
1777                                 else
1778                                     error_build(" ");
1779                             }
1780
1781                             /* later we'll test for this before closing */
1782                             sinkfp = (FILE *)NULL;
1783
1784                             /* 
1785                              * Read the message headers and ship them to the
1786                              * output sink.  
1787                              */
1788                             ok = readheaders(sock, len, msgsizes[num-1],
1789                                              ctl, num);
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;
1796                             else if (ok)
1797                                 goto cleanUp;
1798                             set_timeout(ctl->server.timeout);
1799
1800                             /* 
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
1806                              * read_headers.
1807                              */
1808                             if (protocol->fetch_body) 
1809                             {
1810                                 if (outlevel == O_VERBOSE)
1811                                     fputc('\n', stderr);
1812
1813                                 if ((ok = (protocol->trail)(sock, ctl, num)))
1814                                     goto cleanUp;
1815                                 set_timeout(ctl->server.timeout);
1816                                 len = 0;
1817                                 if (!suppress_forward)
1818                                 {
1819                                     if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1820                                         goto cleanUp;
1821                                     if (outlevel > O_SILENT && !wholesize)
1822                                         error_build(" (%d body bytes) ", len);
1823                                     set_timeout(ctl->server.timeout);
1824                                 }
1825                             }
1826
1827                             /* process the body now */
1828                             if (len > 0)
1829                             {
1830                                 ok = readbody(sock,
1831                                               ctl,
1832                                               !suppress_forward,
1833                                               len);
1834                                 if (ok == PS_TRANSIENT)
1835                                     suppress_delete = suppress_forward = TRUE;
1836                                 else if (ok)
1837                                     goto cleanUp;
1838                                 set_timeout(ctl->server.timeout);
1839
1840                                 /* tell server we got it OK and resynchronize */
1841                                 if (protocol->trail)
1842                                 {
1843                                     if (outlevel == O_VERBOSE)
1844                                         fputc('\n', stderr);
1845
1846                                     ok = (protocol->trail)(sock, ctl, num);
1847                                     if (ok != 0)
1848                                         goto cleanUp;
1849                                     set_timeout(ctl->server.timeout);
1850                                 }
1851                             }
1852
1853                             /* count # messages forwarded on this pass */
1854                             if (!suppress_forward)
1855                                 dispatches++;
1856
1857                             /*
1858                              * Check to see if the numbers matched?
1859                              *
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
1863                              * versions.
1864                              *
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!
1870                              *
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.
1878                              */
1879                             if (msgsizes && msglen != msgsizes[num-1])
1880                             {
1881                                 if (outlevel >= O_VERBOSE)
1882                                     error(0, 0,
1883                                           "message %d was not the expected length (%d != %d)",
1884                                           num, msglen, msgsizes[num-1]);
1885                             }
1886
1887                             /* end-of-message processing starts here */
1888
1889                             if (ctl->mda)
1890                             {
1891                                 int rc;
1892
1893                                 /* close the delivery pipe, we'll reopen before next message */
1894                                 if (sinkfp)
1895                                     rc = pclose(sinkfp);
1896                                 else
1897                                     rc = 0;
1898                                 signal(SIGCHLD, sigchld);
1899                                 if (rc)
1900                                 {
1901                                     error(0, -1, "MDA exited abnormally or returned nonzero status");
1902                                     goto cleanUp;
1903                                 }
1904                             }
1905                             else if (!suppress_forward)
1906                             {
1907                                 /* write message terminator */
1908                                 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
1909                                 {
1910                                     error(0, -1, "SMTP listener refused delivery");
1911                                     ctl->errcount++;
1912                                     suppress_delete = TRUE;
1913                                 }
1914                             }
1915
1916                             fetches++;
1917                         }
1918
1919                         /*
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
1927                          * now.
1928                          */
1929
1930                         /* maybe we delete this message now? */
1931                         if (retained)
1932                         {
1933                             if (outlevel > O_SILENT) 
1934                                 error_complete(0, 0, " retained");
1935                         }
1936                         else if (protocol->delete
1937                                  && !suppress_delete
1938                                  && (fetch_it ? !ctl->keep : ctl->flush))
1939                         {
1940                             deletions++;
1941                             if (outlevel > O_SILENT) 
1942                                 error_complete(0, 0, " flushed");
1943                             ok = (protocol->delete)(sock, ctl, num);
1944                             if (ok != 0)
1945                                 goto cleanUp;
1946                             set_timeout(ctl->server.timeout);
1947 #ifdef POP3_ENABLE
1948                             delete_str(&ctl->newsaved, num);
1949 #endif /* POP3_ENABLE */
1950                         }
1951                         else if (outlevel > O_SILENT) 
1952                             error_complete(0, 0, " not flushed");
1953
1954                         /* perhaps this as many as we're ready to handle */
1955                         if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
1956                             goto no_error;
1957                     }
1958                 }
1959             } while
1960                   /*
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.
1964                    */
1965                   (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
1966         }
1967
1968    no_error:
1969         set_timeout(ctl->server.timeout);
1970         ok = (protocol->logout_cmd)(sock, ctl);
1971         /*
1972          * Hmmmm...arguably this would be incorrect if we had fetches but
1973          * no dispatches (due to oversized messages, etc.)
1974          */
1975         if (ok == 0)
1976             ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1977         set_timeout(0);
1978         close(sock);
1979         goto closeUp;
1980
1981     cleanUp:
1982         set_timeout(ctl->server.timeout);
1983         if (ok != 0 && ok != PS_SOCKET)
1984             (protocol->logout_cmd)(sock, ctl);
1985         set_timeout(0);
1986         close(sock);
1987     }
1988
1989     msg = (char *)NULL;         /* sacrifice to -Wall */
1990     switch (ok)
1991     {
1992     case PS_SOCKET:
1993         msg = "socket";
1994         break;
1995     case PS_AUTHFAIL:
1996         msg = "authorization";
1997         break;
1998     case PS_SYNTAX:
1999         msg = "missing or bad RFC822 header";
2000         break;
2001     case PS_IOERR:
2002         msg = "MDA";
2003         break;
2004     case PS_ERROR:
2005         msg = "client/server synchronization";
2006         break;
2007     case PS_PROTOCOL:
2008         msg = "client/server protocol";
2009         break;
2010     case PS_LOCKBUSY:
2011         msg = "lock busy on server";
2012         break;
2013     case PS_SMTP:
2014         msg = "SMTP transaction";
2015         break;
2016     case PS_DNS:
2017         msg = "DNS lookup";
2018         break;
2019     case PS_UNDEFINED:
2020         error(0, 0, "undefined");
2021         break;
2022     }
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);
2027
2028 closeUp:
2029     /* execute post-initialization command, if any */
2030     if (ctl->postconnect && (ok = system(ctl->postconnect)))
2031     {
2032         char buf[80];
2033
2034         sprintf(buf, "post-connection command failed with status %d", ok);
2035         error(0, 0, buf);
2036         if (ok == PS_SUCCESS)
2037             ok = PS_SYNTAX;
2038     }
2039
2040     signal(SIGALRM, sigsave);
2041     return(ok);
2042 }
2043
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 */
2047 #else
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 */
2052 va_dcl
2053 #endif
2054 {
2055     char buf [POPBUFSIZE+1];
2056     va_list ap;
2057
2058     if (protocol->tagged)
2059         (void) sprintf(buf, "%s ", GENSYM);
2060     else
2061         buf[0] = '\0';
2062
2063 #if defined(HAVE_STDARG_H)
2064     va_start(ap, fmt) ;
2065 #else
2066     va_start(ap);
2067 #endif
2068 #ifdef HAVE_VSNPRINTF
2069     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2070 #else
2071     vsprintf(buf + strlen(buf), fmt, ap);
2072 #endif
2073     va_end(ap);
2074
2075     strcat(buf, "\r\n");
2076     SockWrite(sock, buf, strlen(buf));
2077
2078     if (outlevel == O_VERBOSE)
2079     {
2080         char *cp;
2081
2082         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2083         {
2084             char        *sp;
2085
2086             sp = cp + strlen(shroud);
2087             *cp++ = '*';
2088             while (*sp)
2089                 *cp++ = *sp++;
2090             *cp = '\0';
2091         }
2092         buf[strlen(buf)-2] = '\0';
2093         error(0, 0, "%s> %s", protocol->name, buf);
2094     }
2095 }
2096
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 */
2102 {
2103     if (SockRead(sock, buf, size) == -1)
2104         return(PS_SOCKET);
2105     else
2106     {
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);
2113         return(PS_SUCCESS);
2114     }
2115 }
2116
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 */
2120 #else
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 */
2125 va_dcl
2126 #endif
2127 {
2128     int ok;
2129     char buf [POPBUFSIZE+1];
2130     va_list ap;
2131
2132     if (protocol->tagged)
2133         (void) sprintf(buf, "%s ", GENSYM);
2134     else
2135         buf[0] = '\0';
2136
2137 #if defined(HAVE_STDARG_H)
2138     va_start(ap, fmt) ;
2139 #else
2140     va_start(ap);
2141 #endif
2142 #ifdef HAVE_VSNPRINTF
2143     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2144 #else
2145     vsprintf(buf + strlen(buf), fmt, ap);
2146 #endif
2147     va_end(ap);
2148
2149     strcat(buf, "\r\n");
2150     SockWrite(sock, buf, strlen(buf));
2151
2152     if (outlevel == O_VERBOSE)
2153     {
2154         char *cp;
2155
2156         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2157         {
2158             char        *sp;
2159
2160             sp = cp + strlen(shroud);
2161             *cp++ = '*';
2162             while (*sp)
2163                 *cp++ = *sp++;
2164             *cp = '\0';
2165         }
2166         buf[strlen(buf)-1] = '\0';
2167         error(0, 0, "%s> %s", protocol->name, buf);
2168     }
2169
2170     /* we presume this does its own response echoing */
2171     ok = (protocol->parse_response)(sock, buf);
2172     set_timeout(mytimeout);
2173
2174     return(ok);
2175 }
2176
2177 /* driver.c ends here */