]> Pileus Git - ~andy/fetchmail/blob - driver.c
Added plugin/plugout 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_SYS_ITIMER_H)
29 #include <sys/itimer.h>
30 #endif
31 #include  <sys/time.h>
32 #include  <signal.h>
33
34 #ifdef HAVE_RES_SEARCH
35 #include <netdb.h>
36 #include "mx.h"
37 #endif /* HAVE_RES_SEARCH */
38
39 #ifdef KERBEROS_V4
40 #if defined (__bsdi__)
41 #include <des.h> /* order of includes matters */
42 #include <krb.h>
43 #define krb_get_err_text(e) (krb_err_txt[e])
44 #else
45 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
46 #define krb_get_err_text(e) (krb_err_txt[e])
47 #include <krb.h>
48 #include <des.h>
49 #else
50 #include <krb.h>
51 #include <des.h>
52 #endif /* ! defined (__FreeBSD__) */
53 #endif /* ! defined (__bsdi__) */
54 #include <netinet/in.h>
55 #include <netdb.h>
56 #endif /* KERBEROS_V4 */
57 #ifdef KERBEROS_V5
58 #include <krb5.h>
59 #include <com_err.h>
60 #endif /* KERBEROS_V5 */
61
62 #include "socket.h"
63 #include  "fetchmail.h"
64
65 #if INET6
66 #define SMTP_PORT       "smtp"  /* standard SMTP service port */
67 #else /* INET6 */
68 #define SMTP_PORT       25      /* standard SMTP service port */
69 #endif /* INET6 */
70
71 #ifndef strstr          /* glibc-2.1 declares this as a macro */
72 extern char *strstr();  /* needed on sysV68 R3V7.1. */
73 #endif /* strstr */
74
75 int fetchlimit;         /* how often to tear down the server connection */
76 int batchcount;         /* count of messages sent in current batch */
77 flag peek_capable;      /* can we peek for better error recovery? */
78 int pass;               /* how many times have we re-polled? */
79 int phase;              /* where are we, for error-logging purposes? */
80
81 static const struct method *protocol;
82 static jmp_buf  restart;
83
84 char tag[TAGLEN];
85 static int tagnum;
86 #define GENSYM  (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
87
88 static char shroud[PASSWORDLEN];        /* string to shroud in debug output */
89 static int mytimeout;                   /* value of nonreponse timeout */
90 static int msglen;                      /* actual message length */
91
92 void set_timeout(int timeleft)
93 /* reset the nonresponse-timeout */
94 {
95 #ifndef __EMX__
96     struct itimerval ntimeout;
97
98     ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
99     ntimeout.it_value.tv_sec  = timeleft;
100     ntimeout.it_value.tv_usec = 0;
101     setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
102 #endif
103 }
104
105 static void timeout_handler (int signal)
106 /* handle server-timeout SIGALRM signal */
107 {
108     longjmp(restart, 1);
109 }
110
111 static int accept_count, reject_count;
112
113 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
114 /* add given name to xmit_names if it matches declared localnames */
115 /*   name:       name to map */
116 /*   ctl:        list of permissible aliases */
117 /*   xmit_names: list of recipient names parsed out */
118 {
119     const char  *lname;
120     int off = 0;
121     
122     lname = idpair_find(&ctl->localnames, name+off);
123     if (!lname && ctl->wildcard)
124         lname = name+off;
125
126     if (lname != (char *)NULL)
127     {
128         if (outlevel >= O_DEBUG)
129             error(0, 0, "mapped %s to local %s", name, lname);
130         save_str(xmit_names, lname, XMIT_ACCEPT);
131         accept_count++;
132     }
133 }
134
135 void find_server_names(const char *hdr, struct query *ctl, struct idlist **xmit_names)
136 /* parse names out of a RFC822 header into an ID list */
137 /*   hdr:               RFC822 header in question */
138 /*   ctl:               list of permissible aliases */
139 /*   xmit_names:        list of recipient names parsed out */
140 {
141     if (hdr == (char *)NULL)
142         return;
143     else
144     {
145         char    *cp;
146
147         for (cp = nxtaddr(hdr);
148              cp != NULL;
149              cp = nxtaddr(NULL))
150         {
151             char        *atsign;
152
153             /*
154              * If the name of the user begins with a qmail virtual
155              * domain prefix, ignore the prefix.  Doing this here
156              * means qvirtual will work either with ordinary name
157              * mapping or with a localdomains option.
158              */
159             if (ctl->server.qvirtual)
160             {
161                 int sl = strlen(ctl->server.qvirtual);
162  
163                 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
164                     cp += sl;
165             }
166
167             if ((atsign = strchr(cp, '@'))) {
168                 struct idlist   *idp;
169
170                 /*
171                  * Does a trailing segment of the hostname match something
172                  * on the localdomains list?  If so, save the whole name
173                  * and keep going.
174                  */
175                 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
176                     char        *rhs;
177
178                     rhs = atsign + (strlen(atsign) - strlen(idp->id));
179                     if (rhs > atsign &&
180                         (rhs[-1] == '.' || rhs[-1] == '@') &&
181                         strcasecmp(rhs, idp->id) == 0)
182                     {
183                         if (outlevel >= O_DEBUG)
184                             error(0, 0, "passed through %s matching %s", 
185                                   cp, idp->id);
186                         save_str(xmit_names, cp, XMIT_ACCEPT);
187                         accept_count++;
188                         goto nomap;
189                     }
190                 }
191
192                 /* if we matched a local domain, idp != NULL */
193                 if (!idp)
194                 {
195                     /*
196                      * Check to see if the right-hand part is an alias
197                      * or MX equivalent of the mailserver.  If it's
198                      * not, skip this name.  If it is, we'll keep
199                      * going and try to find a mapping to a client name.
200                      */
201                     if (!is_host_alias(atsign+1, ctl))
202                     {
203                         save_str(xmit_names, cp, XMIT_REJECT);
204                         reject_count++;
205                         continue;
206                     }
207                 }
208                 atsign[0] = '\0';
209                 map_name(cp, ctl, xmit_names);
210             nomap:;
211             }
212         }
213     }
214 }
215
216 static char *parse_received(struct query *ctl, char *bufp)
217 /* try to extract real address from the Received line */
218 /* If a valid Received: line is found, we return the full address in
219  * a buffer which can be parsed from nxtaddr().  This is to ansure that
220  * the local domain part of the address can be passed along in 
221  * find_server_names() if it contains one.
222  * Note: We should return a dummy header containing the address 
223  * which makes nxtaddr() behave correctly. 
224  */
225 {
226     char *ok = (char *)NULL;
227     static char rbuf[HOSTLEN + USERNAMELEN + 4]; 
228
229     if (outlevel >= O_DEBUG)
230         error(0, 0, "analyzing Received line:\n%s", bufp);
231     /*
232      * Try to extract the real envelope addressee.  We look here
233      * specifically for the mailserver's Received line.
234      * Note: this will only work for sendmail, or an MTA that
235      * shares sendmail's convention for embedding the envelope
236      * address in the Received line.  Sendmail itself only
237      * does this when the mail has a single recipient.
238      */
239     if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
240     {
241         char    *sp, *tp;
242
243         /* extract space-delimited token after "by " */
244         for (sp = ok + 3; isspace(*sp); sp++)
245             continue;
246         tp = rbuf;
247         for (; !isspace(*sp); sp++)
248             *tp++ = *sp;
249         *tp = '\0';
250
251         /*
252          * If it's a DNS name of the mail server, look for the
253          * recipient name after a following "for".  Otherwise
254          * punt.
255          */
256         if (is_host_alias(rbuf, ctl))
257         {
258             if (outlevel >= O_DEBUG)
259                 error(0, 0, 
260                       "line accepted, %s is an alias of the mailserver", rbuf);
261         }
262         else
263         {
264             if (outlevel >= O_DEBUG)
265                 error(0, 0, 
266                       "line rejected, %s is not an alias of the mailserver", 
267                       rbuf);
268             return(NULL);
269         }
270
271         if ((ok = strstr(sp, "for ")) && isspace(ok[-1]))
272         {
273             flag        want_gt = FALSE;
274
275             tp = rbuf;
276             sp = ok + 4;
277             *tp++ = ':';        /* Here is the hack.  This is to be friends */
278             *tp++ = ' ';        /* with nxtaddr()... */
279             if (*sp == '<')
280             {
281                 want_gt = TRUE;
282                 sp++;
283             }
284             while (*sp == '@')          /* skip routes */
285                 while (*sp && *sp++ != ':')
286                     continue;
287             while (*sp
288                    && (want_gt ? (*sp != '>') : !isspace(*sp))
289                    && *sp != ';')
290                 if (!isspace(*sp))
291                     *tp++ = *sp++;
292                 else
293                 {
294                     /* uh oh -- whitespace here can't be right! */
295                     ok = (char *)NULL;
296                     break;
297                 }
298             *tp++ = '\n';
299             *tp = '\0';
300             if (strlen(rbuf) <= 3)      /* apparently nothing has been found */
301                 ok = NULL;
302         } else
303             ok = (char *)NULL;
304     }
305
306     if (!ok)
307     {
308         if (outlevel >= O_DEBUG)
309             error(0, 0, "no Received address found");
310         return(NULL);
311     }
312     else
313     {
314         if (outlevel >= O_DEBUG) {
315             char *lf = rbuf + strlen(rbuf)-1;
316             *lf = '\0';
317             if (outlevel >= O_DEBUG)
318                 error(0, 0, "found Received address `%s'", rbuf+2);
319             *lf = '\n';
320         }
321         return(rbuf);
322     }
323 }
324
325 /* shared by readheaders and readbody */
326 static int sizeticker;
327
328 #define EMPTYLINE(s)    ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
329
330 static int readheaders(int sock, long fetchlen, long reallen, struct query *ctl, int num)
331 /* read message headers and ship to SMTP or MDA */
332 /*   sock:              to which the server is connected */
333 /*   fetchlen:          length of message according to fetch response */
334 /*   reallen:           length of message according to getsizes */
335 /*   ctl:               query control record */
336 /*   num:               index of message */
337 {
338     struct addrblk
339     {
340         int             offset;
341         struct addrblk  *next;
342     };
343     struct addrblk      *to_addrchain = NULL;
344     struct addrblk      **to_chainptr = &to_addrchain;
345     struct addrblk      *resent_to_addrchain = NULL;
346     struct addrblk      **resent_to_chainptr = &resent_to_addrchain;
347
348     char                buf[MSGBUFSIZE+1];
349     char                return_path[HOSTLEN + USERNAMELEN + 4]; 
350     int                 from_offs, reply_to_offs, resent_from_offs;
351     int                 app_from_offs, sender_offs, resent_sender_offs;
352     int                 env_offs;
353     char                *headers, *received_for, *rcv, *cp;
354     int                 n, linelen, oldlen, ch, remaining, skipcount;
355     struct idlist       *idp, *xmit_names;
356     flag                no_local_matches = FALSE;
357     flag                headers_ok, has_nuls;
358     int                 olderrs, good_addresses, bad_addresses;
359
360     sizeticker = 0;
361     has_nuls = headers_ok = FALSE;
362     return_path[0] = '\0';
363     olderrs = ctl->errcount;
364
365     /* read message headers */
366     headers = received_for = NULL;
367     from_offs = reply_to_offs = resent_from_offs = app_from_offs = 
368         sender_offs = resent_sender_offs = env_offs = -1;
369     oldlen = 0;
370     msglen = 0;
371     skipcount = 0;
372     ctl->mimemsg = 0;
373
374     for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
375     {
376         char *line;
377
378         line = xmalloc(sizeof(buf));
379         linelen = 0;
380         line[0] = '\0';
381         do {
382             set_timeout(mytimeout);
383             if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
384                 set_timeout(0);
385                 free(line);
386                 free(headers);
387                 return(PS_SOCKET);
388             }
389             set_timeout(0);
390             linelen += n;
391             msglen += n;
392
393             /* lines may not be properly CRLF terminated; fix this for qmail */
394             if (ctl->forcecr)
395             {
396                 cp = buf + strlen(buf) - 1;
397                 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
398                 {
399                     *cp++ = '\r';
400                     *cp++ = '\n';
401                     *cp++ = '\0';
402                 }
403             }
404
405
406             line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
407
408             strcat(line, buf);
409
410             /* check for end of headers */
411             if (EMPTYLINE(line))
412             {
413                 headers_ok = TRUE;
414                 has_nuls = (linelen != strlen(line));
415                 free(line);
416                 goto process_headers;
417             }
418
419             /*
420              * Check for end of message immediately.  If one of your folders
421              * has been mangled, the delimiter may occur directly after the
422              * header.
423              */
424             if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
425             {
426                 free(line);
427                 has_nuls = (linelen != strlen(line));
428                 goto process_headers;
429             }
430         } while
431             /* we may need to grab RFC822 continuations */
432             ((ch = SockPeek(sock)) == ' ' || ch == '\t');
433
434         /* write the message size dots */
435         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
436         {
437             sizeticker += linelen;
438             while (sizeticker >= SIZETICKER)
439             {
440                 error_build(".");
441                 sizeticker -= SIZETICKER;
442             }
443         }
444
445         /* we see an ordinary (non-header, non-message-delimiter line */
446         has_nuls = (linelen != strlen(line));
447
448         /*
449          * The University of Washington IMAP server (the reference
450          * implementation of IMAP4 written by Mark Crispin) relies
451          * on being able to keep base-UID information in a special
452          * message at the head of the mailbox.  This message should
453          * neither be deleted nor forwarded.
454          */
455 #ifdef POP2_ENABLE
456         /*
457          * We disable this check under POP2 because there's no way to
458          * prevent deletion of the message.  So at least we ought to 
459          * forward it to the user so he or she will have some clue
460          * that things have gone awry.
461          */
462         if (protocol->port != 109)
463 #endif /* POP2_ENABLE */
464             if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
465                 free(line);
466                 free(headers);
467                 return(PS_RETAINED);
468             }
469
470         /*
471          * This code prevents fetchmail from becoming an accessory after
472          * the fact to upstream sendmails with the `E' option on.  It also
473          * copes with certain brain-dead POP servers (like NT's) that pass
474          * through Unix from_ lines.
475          *
476          * Either of these bugs can result in a non-RFC822 line at the
477          * beginning of the headers.  If fetchmail just passes it
478          * through, the client listener may think the message has *no*
479          * headers (since the first) line it sees doesn't look
480          * RFC822-conformant) and fake up a set.
481          *
482          * What the user would see in this case is bogus (synthesized)
483          * headers, followed by a blank line, followed by the >From, 
484          * followed by the real headers, followed by a blank line,
485          * followed by text.
486          *
487          * We forestall this lossage by tossing anything that looks
488          * like an escaped or passed-through From_ line in headers.
489          * These aren't RFC822 so our conscience is clear...
490          */
491         if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
492         {
493             free(line);
494             continue;
495         }
496
497         /*
498          * If we see a Status line, it may have been inserted by an MUA
499          * on the mail host, or it may have been inserted by the server
500          * program after the headers in the transaction stream.  This
501          * can actually hose some new-mail notifiers such as xbuffy,
502          * which assumes any Status line came from a *local* MDA and
503          * therefore indicates that the message has been seen.
504          *
505          * Some buggy POP servers (including at least the 3.3(20)
506          * version of the one distributed with IMAP) insert empty
507          * Status lines in the transaction stream; we'll chuck those
508          * unconditionally.  Nonempty ones get chucked if the user
509          * turns on the dropstatus flag.
510          */
511         {
512             char        *cp;
513
514             if (!strncasecmp(line, "Status:", 7))
515                 cp = line + 7;
516             else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
517                 cp = line + 17;
518             else
519                 cp = NULL;
520             if (cp) {
521                 while (*cp && isspace(*cp)) cp++;
522                 if (!*cp || ctl->dropstatus)
523                 {
524                     free(line);
525                     continue;
526                 }
527             }
528         }
529
530         if (ctl->rewrite)
531             line = reply_hack(line, ctl->server.truename);
532
533         /*
534          * OK, this is messy.  If we're forwarding by SMTP, it's the
535          * SMTP-receiver's job (according to RFC821, page 22, section
536          * 4.1.1) to generate a Return-Path line on final delivery.
537          * The trouble is, we've already got one because the
538          * mailserver's SMTP thought *it* was responsible for final
539          * delivery.
540          *
541          * Stash away the contents of Return-Path (as modified by reply_hack)
542          * for use in generating MAIL FROM later on, then prevent the header
543          * from being saved with the others.  In effect, we strip it off here.
544          *
545          * If the SMTP server conforms to the standards, and fetchmail gets the
546          * envelope sender from the Return-Path, the new Return-Path should be
547          * exactly the same as the original one.
548          *
549          * We do *not* want to ignore empty Return-Path headers.  These should
550          * be passed through as a way of indicating that a message should
551          * not trigger bounces if delivery fails.  What we *do* need to do is
552          * make sure we never try to rewrite such a blank Return-Path.  We
553          * handle this with a check for <> in the rewrite logic above.
554          */
555         if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
556         {
557             strcpy(return_path, cp);
558             if (!ctl->mda) {
559                 free(line);
560                 continue;
561             }
562         }
563
564         if (!headers)
565         {
566             oldlen = strlen(line);
567             headers = xmalloc(oldlen + 1);
568             (void) strcpy(headers, line);
569             free(line);
570             line = headers;
571         }
572         else
573         {
574             int newlen;
575
576             newlen = oldlen + strlen(line);
577             headers = (char *) realloc(headers, newlen + 1);
578             if (headers == NULL) {
579                 free(line);
580                 return(PS_IOERR);
581             }
582             strcpy(headers + oldlen, line);
583             free(line);
584             line = headers + oldlen;
585             oldlen = newlen;
586         }
587
588         if (!strncasecmp("From:", line, 5))
589             from_offs = (line - headers);
590         else if (!strncasecmp("Reply-To:", line, 9))
591             reply_to_offs = (line - headers);
592         else if (!strncasecmp("Resent-From:", line, 12))
593             resent_from_offs = (line - headers);
594         else if (!strncasecmp("Apparently-From:", line, 16))
595             app_from_offs = (line - headers);
596         else if (!strncasecmp("Sender:", line, 7))
597             sender_offs = (line - headers);
598         else if (!strncasecmp("Resent_Sender:", line, 14))
599             resent_sender_offs = (line - headers);
600
601         else if (!strncasecmp("Message-Id:", buf, 11))
602         {
603             if (ctl->server.uidl)
604             {
605                 char id[IDLEN+1];
606
607                 buf[IDLEN+12] = 0;              /* prevent stack overflow */
608                 sscanf(buf+12, "%s", id);
609                 if (!str_find( &ctl->newsaved, num))
610                 {
611                     struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
612                     new->val.status.num = num;
613                 }
614             }
615         }
616
617         else if (!MULTIDROP(ctl))
618             continue;
619
620         else if (!strncasecmp("To:", line, 3)
621                         || !strncasecmp("Cc:", line, 3)
622                         || !strncasecmp("Bcc:", line, 4)
623                         || !strncasecmp("Apparently-To:", line, 14))
624         {
625             *to_chainptr = xmalloc(sizeof(struct addrblk));
626             (*to_chainptr)->offset = (line - headers);
627             to_chainptr = &(*to_chainptr)->next; 
628             *to_chainptr = NULL;
629         }
630
631         else if (!strncasecmp("Resent-To:", line, 10)
632                         || !strncasecmp("Resent-Cc:", line, 10)
633                         || !strncasecmp("Resent-Bcc:", line, 11))
634         {
635             *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
636             (*resent_to_chainptr)->offset = (line - headers);
637             resent_to_chainptr = &(*resent_to_chainptr)->next; 
638             *resent_to_chainptr = NULL;
639         }
640
641         else if (ctl->server.envelope != STRING_DISABLED)
642         {
643             if (ctl->server.envelope 
644                         && strcasecmp(ctl->server.envelope, "Received"))
645             {
646                 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
647                                                 line,
648                                                 strlen(ctl->server.envelope)))
649                 {                               
650                     if (skipcount++ != ctl->server.envskip)
651                         continue;
652                     env_offs = (line - headers);
653                 }    
654             }
655             else if (!received_for && !strncasecmp("Received:", line, 9))
656             {
657                 if (skipcount++ != ctl->server.envskip)
658                     continue;
659                 received_for = parse_received(ctl, line);
660             }
661         }
662     }
663
664  process_headers:
665     /*
666      * We want to detect this early in case there are so few headers that the
667      * dispatch logic barfs.
668      */
669     if (!headers_ok)
670     {
671         if (outlevel > O_SILENT)
672             error(0,0,"message delimiter found while scanning headers");
673     }
674
675     /*
676      * Hack time.  If the first line of the message was blank, with no headers
677      * (this happens occasionally due to bad gatewaying software) cons up
678      * a set of fake headers.  
679      *
680      * If you modify the fake header template below, be sure you don't
681      * make either From or To address @-less, otherwise the reply_hack
682      * logic will do bad things.
683      */
684     if (headers == (char *)NULL)
685     {
686 #ifdef HAVE_SNPRINTF
687         snprintf(buf, sizeof(buf),
688 #else
689         sprintf(buf, 
690 #endif /* HAVE_SNPRINTF */
691         "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
692                 user, fetchmailhost, ctl->remotename, ctl->server.truename);
693         headers = xstrdup(buf);
694     }
695
696     /*
697      * We can now process message headers before reading the text.
698      * In fact we have to, as this will tell us where to forward to.
699      */
700
701     /* Decode MIME encoded headers. We MUST do this before
702      * looking at the Content-Type / Content-Transfer-Encoding
703      * headers (RFC 2046).
704      */
705     if (ctl->mimedecode) {
706         UnMimeHeader(headers);
707     }
708     /* Check for MIME headers indicating possible 8-bit data */
709     ctl->mimemsg = MimeBodyType(headers, ctl->mimedecode);
710
711     /*
712      * If there is a Return-Path address on the message, this was
713      * almost certainly the MAIL FROM address given the originating
714      * sendmail.  This is the best thing to use for logging the
715      * message origin (it sets up the right behavior for bounces and
716      * mailing lists).  Otherwise, fall down to the next available 
717      * envelope address (which is the most probable real sender).
718      * *** The order is important! ***
719      * This is especially useful when receiving mailing list
720      * messages in multidrop mode.  if a local address doesn't
721      * exist, the bounce message won't be returned blindly to the 
722      * author or to the list itself but rather to the list manager
723      * (ex: specified by "Sender:") which is much less annoying.  This 
724      * is true for most mailing list packages.
725      */
726     if( !return_path[0] ){
727         char *ap = NULL;
728         if (resent_sender_offs >= 0 && (ap = nxtaddr(headers + resent_sender_offs)));
729         else if (sender_offs >= 0 && (ap = nxtaddr(headers + sender_offs)));
730         else if (resent_from_offs >= 0 && (ap = nxtaddr(headers + resent_from_offs)));
731         else if (from_offs >= 0 && (ap = nxtaddr(headers + from_offs)));
732         else if (reply_to_offs >= 0 && (ap = nxtaddr(headers + reply_to_offs)));
733         else if (app_from_offs >= 0 && (ap = nxtaddr(headers + app_from_offs)));
734         if (ap) strcpy( return_path, ap );
735     }
736
737     /* cons up a list of local recipients */
738     xmit_names = (struct idlist *)NULL;
739     accept_count = reject_count = 0;
740     /* is this a multidrop box? */
741     if (MULTIDROP(ctl))
742     {
743         if (env_offs > -1)          /* We have the actual envelope addressee */
744             find_server_names(headers + env_offs, ctl, &xmit_names);
745         else if (received_for)
746             /*
747              * We have the Received for addressee.  
748              * It has to be a mailserver address, or we
749              * wouldn't have got here.
750              * We use find_server_names() to let local 
751              * hostnames go through.
752              */
753             find_server_names(received_for, ctl, &xmit_names);
754 #ifdef SDPS_ENABLE
755         else if (sdps_envto)
756         {
757             find_server_names(sdps_envto, ctl, &xmit_names);
758             free(sdps_envto);
759         }
760 #endif /* SDPS_ENABLE */ 
761         else
762         {
763             /*
764              * We haven't extracted the envelope address.
765              * So check all the "Resent-To" header addresses if 
766              * they exist.  If and only if they don't, consider
767              * the "To" adresses.
768              */
769             register struct addrblk *nextptr;
770             if (resent_to_addrchain) {
771                 /* delete the "To" chain and substitute it 
772                  * with the "Resent-To" list 
773                  */
774                 while (to_addrchain) {
775                     nextptr = to_addrchain->next;
776                     free(to_addrchain);
777                     to_addrchain = nextptr;
778                 }
779                 to_addrchain = resent_to_addrchain;
780                 resent_to_addrchain = NULL;
781             }
782             /* now look for remaining adresses */
783             while (to_addrchain) {
784                 find_server_names(headers+to_addrchain->offset, ctl, &xmit_names);
785                 nextptr = to_addrchain->next;
786                 free(to_addrchain);
787                 to_addrchain = nextptr;
788             }
789         }
790         if (!accept_count)
791         {
792             no_local_matches = TRUE;
793             save_str(&xmit_names, run.postmaster, XMIT_ACCEPT);
794             if (outlevel >= O_DEBUG)
795                 error(0, 0, 
796                       "no local matches, forwarding to %s",
797                       run.postmaster);
798         }
799     }
800     else        /* it's a single-drop box, use first localname */
801         save_str(&xmit_names, ctl->localnames->id, XMIT_ACCEPT);
802
803
804     /*
805      * Time to either address the message or decide we can't deliver it yet.
806      */
807     if (ctl->errcount > olderrs)        /* there were DNS errors above */
808     {
809         if (outlevel >= O_DEBUG)
810             error(0,0, "forwarding and deletion suppressed due to DNS errors");
811         free(headers);
812         free_str_list(&xmit_names);
813         return(PS_TRANSIENT);
814     }
815     else
816     {
817         /* set up stuffline() so we can deliver the message body through it */ 
818         if ((n = open_sink(ctl, return_path, xmit_names, reallen,
819                            &good_addresses, &bad_addresses)) != PS_SUCCESS)
820         {
821             free(headers);
822             free_str_list(&xmit_names);
823             return(n);
824         }
825     }
826
827     n = 0;
828     /*
829      * Some server/sendmail combinations cause problems when our
830      * synthetic Received line is before the From header.  Cope
831      * with this...
832      */
833     if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
834         rcv = headers;
835     /* handle ">Received:" lines too */
836     while (rcv > headers && rcv[-1] != '\n')
837         rcv--;
838     if (rcv > headers)
839     {
840         char    c = *rcv;
841
842         *rcv = '\0';
843         n = stuffline(ctl, headers);
844         *rcv = c;
845     }
846     if (!run.invisible && n != -1)
847     {
848         /* utter any per-message Received information we need here */
849         sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
850         n = stuffline(ctl, buf);
851         if (n != -1)
852         {
853             /*
854              * We used to include ctl->remotename in this log line,
855              * but this can be secure information that would be bad
856              * to reveal.
857              */
858             sprintf(buf, "\tby fetchmail-%s %s\r\n",
859                     RELEASE_ID,
860                     protocol->name);
861             n = stuffline(ctl, buf);
862             if (n != -1)
863             {
864                 buf[0] = '\t';
865                 if (good_addresses == 0)
866                 {
867                     sprintf(buf+1, 
868                             "for <%s@%s> (by default); ",
869                             user, ctl->destaddr);
870                 }
871                 else if (good_addresses == 1)
872                 {
873                     for (idp = xmit_names; idp; idp = idp->next)
874                         if (idp->val.status.mark == XMIT_ACCEPT)
875                             break;      /* only report first address */
876                     if (strchr(idp->id, '@'))
877                         sprintf(buf+1, "for <%s>", idp->id);
878                     else
879                         sprintf(buf+1, "for <%s/%s>", idp->id, ctl->destaddr);
880                     sprintf(buf+strlen(buf), " (%s); ",
881                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
882                 }
883                 else
884                     buf[1] = '\0';
885
886                 strcat(buf, rfc822timestamp());
887                 strcat(buf, "\r\n");
888                 n = stuffline(ctl, buf);
889             }
890         }
891     }
892
893     if (n != -1)
894         n = stuffline(ctl, rcv);        /* ship out rest of headers */
895
896     if (n == -1)
897     {
898         error(0, errno, "writing RFC822 headers");
899         release_sink(ctl);
900         free(headers);
901         free_str_list(&xmit_names);
902         return(PS_IOERR);
903     }
904     else if (!run.use_syslog && outlevel >= O_VERBOSE)
905         fputs("#", stderr);
906
907     /* write error notifications */
908     if (no_local_matches || has_nuls || bad_addresses)
909     {
910         int     errlen = 0;
911         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
912
913         errmsg = errhd;
914         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
915         if (no_local_matches)
916         {
917             if (reject_count != 1)
918                 strcat(errhd, "no recipient addresses matched declared local names");
919             else
920             {
921                 for (idp = xmit_names; idp; idp = idp->next)
922                     if (idp->val.status.mark == XMIT_REJECT)
923                         break;
924                 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
925             }
926         }
927
928         if (has_nuls)
929         {
930             if (errhd[sizeof("X-Fetchmail-Warning: ")])
931                 strcat(errhd, "; ");
932             strcat(errhd, "message has embedded NULs");
933         }
934
935         if (bad_addresses)
936         {
937             if (errhd[sizeof("X-Fetchmail-Warning: ")])
938                 strcat(errhd, "; ");
939             strcat(errhd, "SMTP listener rejected local recipient addresses: ");
940             errlen = strlen(errhd);
941             for (idp = xmit_names; idp; idp = idp->next)
942                 if (idp->val.status.mark == XMIT_ANTISPAM)
943                     errlen += strlen(idp->id) + 2;
944
945             xalloca(errmsg, char *, errlen+3);
946             (void) strcpy(errmsg, errhd);
947             for (idp = xmit_names; idp; idp = idp->next)
948                 if (idp->val.status.mark == XMIT_ANTISPAM)
949                 {
950                     strcat(errmsg, idp->id);
951                     if (idp->next)
952                         strcat(errmsg, ", ");
953                 }
954
955         }
956
957         strcat(errmsg, "\r\n");
958
959         /* ship out the error line */
960         stuffline(ctl, errmsg);
961     }
962
963     /* issue the delimiter line */
964     cp = buf;
965     *cp++ = '\r';
966     *cp++ = '\n';
967     *cp++ = '\0';
968     stuffline(ctl, buf);
969
970     free(headers);
971     free_str_list(&xmit_names);
972     return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
973 }
974
975 static int readbody(int sock, struct query *ctl, flag forward, int len)
976 /* read and dispose of a message body presented on sock */
977 /*   ctl:               query control record */
978 /*   sock:              to which the server is connected */
979 /*   len:               length of message */
980 /*   forward:           TRUE to forward */
981 {
982     int linelen;
983     unsigned char buf[MSGBUFSIZE+4];
984     unsigned char *inbufp = buf;
985     flag issoftline = FALSE;
986
987     /* pass through the text lines */
988     while (protocol->delimited || len > 0)
989     {
990         set_timeout(mytimeout);
991         if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
992         {
993             set_timeout(0);
994             release_sink(ctl);
995             return(PS_SOCKET);
996         }
997         set_timeout(0);
998
999         /* write the message size dots */
1000         if (linelen > 0)
1001         {
1002             sizeticker += linelen;
1003             while (sizeticker >= SIZETICKER)
1004             {
1005                 if (!run.use_syslog && outlevel > O_SILENT)
1006                     error_build(".");
1007                 sizeticker -= SIZETICKER;
1008             }
1009         }
1010         len -= linelen;
1011
1012         /* check for end of message */
1013         if (protocol->delimited && *inbufp == '.')
1014             if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1015                 break;
1016             else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1017                 break;
1018             else
1019                 msglen--;       /* subtract the size of the dot escape */
1020
1021         msglen += linelen;
1022
1023         if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1024             issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1025             if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1026             {
1027                 /*
1028                  * Soft linebreak, but less than 200 bytes left in
1029                  * input buffer. Rather than doing a buffer overrun,
1030                  * ignore the soft linebreak, NL-terminate data and
1031                  * deliver what we have now.
1032                  * (Who writes lines longer than 2K anyway?)
1033                  */
1034                 *inbufp = '\n'; *(inbufp+1) = '\0';
1035                 issoftline = 0;
1036             }
1037         }
1038
1039         /* ship out the text line */
1040         if (forward && (!issoftline))
1041         {
1042             int n;
1043             inbufp = buf;
1044
1045             /* guard against very long lines */
1046             buf[MSGBUFSIZE+1] = '\r';
1047             buf[MSGBUFSIZE+2] = '\n';
1048             buf[MSGBUFSIZE+3] = '\0';
1049
1050             n = stuffline(ctl, buf);
1051
1052             if (n < 0)
1053             {
1054                 error(0, errno, "writing message text");
1055                 release_sink(ctl);
1056                 return(PS_IOERR);
1057             }
1058             else if (outlevel >= O_VERBOSE)
1059                 fputc('*', stderr);
1060         }
1061     }
1062
1063     return(PS_SUCCESS);
1064 }
1065
1066 #ifdef KERBEROS_V4
1067 int
1068 kerberos_auth (socket, canonical) 
1069 /* authenticate to the server host using Kerberos V4 */
1070 int socket;             /* socket to server host */
1071 #ifdef __FreeBSD__
1072 char *canonical;        /* server name */
1073 #else
1074 const char *canonical;  /* server name */
1075 #endif
1076 {
1077     char * host_primary;
1078     KTEXT ticket;
1079     MSG_DAT msg_data;
1080     CREDENTIALS cred;
1081     Key_schedule schedule;
1082     int rem;
1083   
1084     xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1085     rem = (krb_sendauth (0L, socket, ticket, "pop",
1086                          canonical,
1087                          ((char *) (krb_realmofhost (canonical))),
1088                          ((unsigned long) 0),
1089                          (&msg_data),
1090                          (&cred),
1091                          (schedule),
1092                          ((struct sockaddr_in *) 0),
1093                          ((struct sockaddr_in *) 0),
1094                          "KPOPV0.1"));
1095     if (rem != KSUCCESS)
1096     {
1097         error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1098         return (PS_AUTHFAIL);
1099     }
1100     return (0);
1101 }
1102 #endif /* KERBEROS_V4 */
1103
1104 #ifdef KERBEROS_V5
1105 int
1106 kerberos5_auth(socket, canonical)
1107 /* authenticate to the server host using Kerberos V5 */
1108 int socket;             /* socket to server host */
1109 const char *canonical;  /* server name */
1110 {
1111     krb5_error_code retval;
1112     krb5_context context;
1113     krb5_ccache ccdef;
1114     krb5_principal client = NULL, server = NULL;
1115     krb5_error *err_ret = NULL;
1116
1117     krb5_auth_context auth_context = NULL;
1118
1119     krb5_init_context(&context);
1120     krb5_init_ets(context);
1121     krb5_auth_con_init(context, &auth_context);
1122
1123     if (retval = krb5_cc_default(context, &ccdef)) {
1124         error(0, 0, "krb5_cc_default: %s", error_message(retval));
1125         return(PS_ERROR);
1126     }
1127
1128     if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1129         error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1130         return(PS_ERROR);
1131     }
1132
1133     if (retval = krb5_sname_to_principal(context, canonical, "pop",
1134            KRB5_NT_UNKNOWN,
1135            &server)) {
1136         error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1137         return(PS_ERROR);
1138     }
1139
1140     retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1141          "KPOPV1.0", client, server,
1142          AP_OPTS_MUTUAL_REQUIRED,
1143          NULL,  /* no data to checksum */
1144          0,   /* no creds, use ccache instead */
1145          ccdef,
1146          &err_ret, 0,
1147
1148          NULL); /* don't need reply */
1149
1150     krb5_free_principal(context, server);
1151     krb5_free_principal(context, client);
1152     krb5_auth_con_free(context, auth_context);
1153
1154     if (retval) {
1155       if (err_ret && err_ret->text.length) {
1156           error(0, 0, "krb5_sendauth: %s [server says '%*s'] ",
1157             error_message(retval),
1158             err_ret->text.length,
1159             err_ret->text.data);
1160           krb5_free_error(context, err_ret);
1161       } else
1162           error(0, 0, "krb5_sendauth: %s", error_message(retval));
1163       return(PS_ERROR);
1164     }
1165
1166     return 0;
1167 }
1168 #endif /* KERBEROS_V5 */
1169
1170 static void clean_skipped_list(struct idlist **skipped_list)
1171 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1172 {
1173     struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1174     prev = current = head = *skipped_list;
1175
1176     if (!head)
1177         return;
1178     do
1179     {
1180         /* if item has no reference, remove it */
1181         if (current && current->val.status.mark == 0)
1182         {
1183             if (current == head) /* remove first item (head) */
1184             {
1185                 head = current->next;
1186                 if (current->id) free(current->id);
1187                 free(current);
1188                 prev = current = head;
1189             }
1190             else /* remove middle/last item */
1191             {
1192                 tmp = current->next;
1193                 prev->next = tmp;
1194                 if (current->id) free(current->id);
1195                 free(current);
1196                 current = tmp;
1197             }
1198         }
1199         else /* skip this item */
1200         {
1201             prev = current;
1202             current = current->next;
1203         }
1204     } while(current);
1205
1206     *skipped_list = head;
1207 }
1208
1209 static open_warning_by_mail(struct query *ctl)
1210 /* set up output sink for a mailed warning to calling user */
1211 {
1212     int good, bad;
1213
1214     /*
1215      * We give a null address list as arg 3 because we actually *want*
1216      * this message to go to run.postmaster.  The zero length arg 4 means
1217      * we won't pass a SIZE option to ESMTP; the message length would
1218      * be more trouble than it's worth to compute.
1219      */
1220     return(open_sink(ctl, "FETCHMAIL-DAEMON", NULL, 0, &good, &bad));
1221 }
1222
1223 #if defined(HAVE_STDARG_H)
1224 void stuff_warning_line(struct query *ctl, const char *fmt, ... )
1225 #else
1226 void stuff_warning_line(struct query *ctl, fmt, va_alist)
1227 struct query *ctl;
1228 const char *fmt;        /* printf-style format */
1229 va_dcl
1230 #endif
1231 /* format and ship a warning message line by mail */
1232 {
1233     char        buf[POPBUFSIZE];
1234     va_list ap;
1235
1236     /*
1237      * stuffline() requires its input to be writeable (for CR stripping),
1238      * so we needed to copy the message to a writeable buffer anyway in
1239      * case it was a string constant.  We make a virtue of that necessity
1240      * here by supporting stdargs/varargs.
1241      */
1242 #if defined(HAVE_STDARG_H)
1243     va_start(ap, fmt) ;
1244 #else
1245     va_start(ap);
1246 #endif
1247 #ifdef HAVE_VSNPRINTF
1248     vsnprintf(buf, sizeof(buf), fmt, ap);
1249 #else
1250     vsprintf(buf, fmt, ap);
1251 #endif
1252     va_end(ap);
1253
1254     strcat(buf, "\r\n");
1255
1256     stuffline(ctl, buf);
1257 }
1258
1259 static close_warning_by_mail(struct query *ctl)
1260 /* sign and send mailed warnings */
1261 {
1262     stuff_warning_line(ctl, "--\r\n\t\t\t\tThe Fetchmail Daemon\r\n");
1263     close_sink(ctl, TRUE);
1264 }
1265
1266 static void send_size_warnings(struct query *ctl)
1267 /* send warning mail with skipped msg; reset msg count when user notified */
1268 {
1269     int size, nbr;
1270     int msg_to_send = FALSE;
1271     struct idlist *head=NULL, *current=NULL;
1272     int max_warning_poll_count, good, bad;
1273 #define OVERHD  "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server:"
1274
1275     head = ctl->skipped;
1276     if (!head)
1277         return;
1278
1279     /* don't start a notification message unless we need to */
1280     for (current = head; current; current = current->next)
1281         if (current->val.status.num == 0 && current->val.status.mark)
1282             msg_to_send = TRUE;
1283     if (!msg_to_send)
1284         return;
1285
1286     /*
1287      * There's no good way to recover if we can't send notification mail, 
1288      * but it's not a disaster, either, since the skipped mail will not
1289      * be deleted.
1290      */
1291     if (open_warning_by_mail(ctl))
1292         return;
1293     stuff_warning_line(ctl, OVERHD);
1294  
1295     if (run.poll_interval == 0)
1296         max_warning_poll_count = 0;
1297     else
1298         max_warning_poll_count = ctl->warnings/run.poll_interval;
1299
1300     /* parse list of skipped msg, adding items to the mail */
1301     for (current = head; current; current = current->next)
1302     {
1303         if (current->val.status.num == 0 && current->val.status.mark)
1304         {
1305             nbr = current->val.status.mark;
1306             size = atoi(current->id);
1307             stuff_warning_line(ctl, 
1308                     "\t%d msg %d octets long skipped by fetchmail.",
1309                     nbr, size);
1310         }
1311         current->val.status.num++;
1312         current->val.status.mark = 0;
1313
1314         if (current->val.status.num >= max_warning_poll_count)
1315             current->val.status.num = 0;
1316     }
1317
1318     close_warning_by_mail(ctl);
1319 #undef OVERHD
1320 }
1321
1322 int do_protocol(ctl, proto)
1323 /* retrieve messages from server using given protocol method table */
1324 struct query *ctl;              /* parsed options with merged-in defaults */
1325 const struct method *proto;     /* protocol method table */
1326 {
1327     int ok, js;
1328 #ifdef HAVE_VOLATILE
1329     volatile int sock = -1;     /* pacifies -Wall */
1330 #else
1331     int sock = -1;
1332 #endif /* HAVE_VOLATILE */
1333     const char *msg;
1334     void (*sigsave)(int);
1335     struct idlist *current=NULL, *tmp=NULL;
1336
1337     protocol = proto;
1338     ctl->server.base_protocol = protocol;
1339
1340 #ifndef KERBEROS_V4
1341     if (ctl->server.preauthenticate == A_KERBEROS_V4)
1342     {
1343         error(0, -1, "Kerberos V4 support not linked.");
1344         return(PS_ERROR);
1345     }
1346 #endif /* KERBEROS_V4 */
1347
1348 #ifndef KERBEROS_V5
1349     if (ctl->server.preauthenticate == A_KERBEROS_V5)
1350     {
1351         error(0, -1, "Kerberos V5 support not linked.");
1352         return(PS_ERROR);
1353     }
1354 #endif /* KERBEROS_V5 */
1355
1356     /* lacking methods, there are some options that may fail */
1357     if (!proto->is_old)
1358     {
1359         /* check for unsupported options */
1360         if (ctl->flush) {
1361             error(0, 0,
1362                     "Option --flush is not supported with %s",
1363                     proto->name);
1364             return(PS_SYNTAX);
1365         }
1366         else if (ctl->fetchall) {
1367             error(0, 0,
1368                     "Option --all is not supported with %s",
1369                     proto->name);
1370             return(PS_SYNTAX);
1371         }
1372     }
1373     if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1374     {
1375         error(0, 0,
1376                 "Option --limit is not supported with %s",
1377                 proto->name);
1378         return(PS_SYNTAX);
1379     }
1380
1381     pass = 0;
1382     tagnum = 0;
1383     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1384     ok = 0;
1385
1386     /* set up the server-nonresponse timeout */
1387     sigsave = signal(SIGALRM, timeout_handler);
1388     mytimeout = ctl->server.timeout;
1389
1390     if ((js = setjmp(restart)) == 1)
1391     {
1392         if (phase == OPEN_WAIT)
1393             error(0, 0,
1394                   "timeout after %d seconds waiting to connect to server %s.",
1395                   ctl->server.timeout, ctl->server.pollname);
1396         else if (phase == SERVER_WAIT)
1397             error(0, 0,
1398                   "timeout after %d seconds waiting for server %s.",
1399                   ctl->server.timeout, ctl->server.pollname);
1400         else if (phase == FORWARDING_WAIT)
1401             error(0, 0,
1402                   "timeout after %d seconds waiting for %s.",
1403                   ctl->server.timeout,
1404                   ctl->mda ? "MDA" : "SMTP");
1405         else if (phase == LISTENER_WAIT)
1406             error(0, 0,
1407                   "timeout after %d seconds waiting for listener to respond.");
1408         else
1409             error(0, 0, "timeout after %d seconds.", ctl->server.timeout);
1410
1411         release_sink(ctl);
1412         if (ctl->smtp_socket != -1)
1413             close(ctl->smtp_socket);
1414         if (sock != -1)
1415             SockClose(sock);
1416         ok = PS_ERROR;
1417     }
1418     else
1419     {
1420         char buf [POPBUFSIZE+1], *realhost;
1421         int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1422 #if INET6
1423         int fetches, dispatches;
1424 #else /* INET6 */
1425         int port, fetches, dispatches, oldphase;
1426 #endif /* INET6 */
1427         struct idlist *idp;
1428
1429         /* execute pre-initialization command, if any */
1430         if (ctl->preconnect && (ok = system(ctl->preconnect)))
1431         {
1432             sprintf(buf, "pre-connection command failed with status %d", ok);
1433             error(0, 0, buf);
1434             ok = PS_SYNTAX;
1435             goto closeUp;
1436         }
1437
1438         /* open a socket to the mail server */
1439         oldphase = phase;
1440         phase = OPEN_WAIT;
1441         set_timeout(mytimeout);
1442 #if !INET6
1443         port = ctl->server.port ? ctl->server.port : protocol->port;
1444 #endif /* !INET6 */
1445         realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1446 #if INET6
1447         if ((sock = SockOpen(realhost, 
1448                              ctl->server.service ? ctl->server.service : protocol->service,
1449                              ctl->server.netsec)) == -1, ctl->server.plugin
1450             )
1451 #else /* INET6 */
1452         if ((sock = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1453 #endif /* INET6 */
1454         {
1455 #if !INET6
1456 #ifdef HAVE_RES_SEARCH
1457             if (errno != 0 && h_errno != 0)
1458                 error(0, 0, "fetchmail: internal inconsistency");
1459 #endif
1460             error_build("fetchmail: %s connection to %s failed", 
1461                          protocol->name, ctl->server.pollname);
1462 #ifdef HAVE_RES_SEARCH
1463             if (h_errno != 0)
1464             {
1465                 if (h_errno == HOST_NOT_FOUND)
1466                     error_complete(0, 0, ": host is unknown");
1467                 else if (h_errno == NO_ADDRESS)
1468                     error_complete(0, 0, ": name is valid but has no IP address");
1469                 else if (h_errno == NO_RECOVERY)
1470                     error_complete(0, 0, ": unrecoverable name server error");
1471                 else if (h_errno == TRY_AGAIN)
1472                     error_complete(0, 0, ": temporary name server error");
1473                 else
1474                     error_complete(0, 0, ": unknown DNS error %d", h_errno);
1475             }
1476 #endif /* HAVE_RES_SEARCH */
1477
1478             if (errno != 0)
1479                 error_complete(0, errno, "");
1480 #endif /* INET6 */
1481             ok = PS_SOCKET;
1482             set_timeout(0);
1483             phase = oldphase;
1484             goto closeUp;
1485         }
1486         set_timeout(0);
1487         phase = oldphase;
1488
1489 #ifdef KERBEROS_V4
1490         if (ctl->server.preauthenticate == A_KERBEROS_V4)
1491         {
1492             set_timeout(mytimeout);
1493             ok = kerberos_auth(sock, ctl->server.truename);
1494             set_timeout(0);
1495             if (ok != 0)
1496                 goto cleanUp;
1497         }
1498 #endif /* KERBEROS_V4 */
1499
1500 #ifdef KERBEROS_V5
1501         if (ctl->server.preauthenticate == A_KERBEROS_V5)
1502         {
1503             set_timeout(mytimeout);
1504             ok = kerberos5_auth(sock, ctl->server.truename);
1505             set_timeout(0);
1506             if (ok != 0)
1507                 goto cleanUp;
1508         }
1509 #endif /* KERBEROS_V5 */
1510
1511         /* accept greeting message from mail server */
1512         ok = (protocol->parse_response)(sock, buf);
1513         if (ok != 0)
1514             goto cleanUp;
1515
1516         /* try to get authorized to fetch mail */
1517         if (protocol->getauth)
1518         {
1519             if (protocol->password_canonify)
1520                 (protocol->password_canonify)(shroud, ctl->password);
1521             else
1522                 strcpy(shroud, ctl->password);
1523
1524             ok = (protocol->getauth)(sock, ctl, buf);
1525             if (ok != 0)
1526             {
1527                 if (ok == PS_LOCKBUSY)
1528                     error(0, -1, "Lock-busy error on %s@%s",
1529                           ctl->remotename,
1530                           ctl->server.truename);
1531                 else
1532                 {
1533                     if (ok == PS_ERROR)
1534                         ok = PS_AUTHFAIL;
1535                     error(0, -1, "Authorization failure on %s@%s", 
1536                           ctl->remotename,
1537                           ctl->server.truename);
1538
1539                     /*
1540                      * If we're running in background, try to mail the
1541                      * calling user a heads-up about the authentication 
1542                      * failure the first time it happens.
1543                      */
1544                     if (run.poll_interval && !nodetach 
1545                         && !ctl->authfailcount && !open_warning_by_mail(ctl))
1546                     {
1547                         stuff_warning_line(ctl,
1548                                "Subject: fetchmail authentication failed\r\n");
1549                         stuff_warning_line(ctl,
1550                                 "Fetchmail could not get mail from %s@%s.", 
1551                                 ctl->remotename,
1552                                 ctl->server.truename);
1553                         stuff_warning_line(ctl, 
1554                                "The attempt to get authorization failed.");
1555                         stuff_warning_line(ctl, 
1556                                "This probably means your password is invalid.");
1557                         close_warning_by_mail(ctl);
1558                         ctl->authfailcount++;
1559                     }
1560                 }
1561                 goto cleanUp;
1562             }
1563         }
1564
1565         ctl->errcount = fetches = 0;
1566
1567         /* now iterate over each folder selected */
1568         for (idp = ctl->mailboxes; idp; idp = idp->next)
1569         {
1570             pass = 0;
1571             do {
1572                 dispatches = 0;
1573                 ++pass;
1574
1575                 if (outlevel >= O_DEBUG)
1576                     if (idp->id)
1577                         error(0, 0, "selecting or re-polling folder %s", idp->id);
1578                     else
1579                         error(0, 0, "selecting or re-polling default folder");
1580
1581                 /* compute # of messages and number of new messages waiting */
1582                 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1583                 if (ok != 0)
1584                     goto cleanUp;
1585
1586                 /* 
1587                  * We need the size of each message before it's
1588                  * loaded in order to pass via the ESMTP SIZE
1589                  * option.  If the protocol has a getsizes method,
1590                  * we presume this means it doesn't get reliable
1591                  * sizes from message fetch responses.
1592                  */
1593                 if (count > 0 && proto->getsizes)
1594                 {
1595                     int i;
1596
1597                     xalloca(msgsizes, int *, sizeof(int) * count);
1598                     for (i = 0; i < count; i++)
1599                         msgsizes[i] = -1;
1600
1601                     ok = (proto->getsizes)(sock, count, msgsizes);
1602                     if (ok != 0)
1603                         goto cleanUp;
1604
1605                     if (bytes == -1)
1606                     {
1607                         bytes = 0;
1608                         for (i = 0; i < count; i++)
1609                             bytes += msgsizes[i];
1610                     }
1611                 }
1612
1613                 /* show user how many messages we downloaded */
1614                 if (idp->id)
1615                     (void) sprintf(buf, "%s at %s (folder %s)",
1616                                    ctl->remotename, ctl->server.truename, idp->id);
1617                 else
1618                     (void) sprintf(buf, "%s at %s",
1619                                    ctl->remotename, ctl->server.truename);
1620                 if (outlevel > O_SILENT)
1621                     if (count == -1)            /* only used for ETRN */
1622                         error(0, 0, "Polling %s", ctl->server.truename);
1623                     else if (count != 0)
1624                     {
1625                         if (new != -1 && (count - new) > 0)
1626                             error_build("%d message%s (%d seen) for %s",
1627                                   count, count > 1 ? "s" : "", count-new, buf);
1628                         else
1629                             error_build("%d message%s for %s", 
1630                                   count, count > 1 ? "s" : "", buf);
1631                         if (bytes == -1)
1632                             error_complete(0, 0, ".");
1633                         else
1634                             error_complete(0, 0, " (%d octets).", bytes);
1635                     }
1636                     else
1637                     {
1638                         /* these are pointless in normal daemon mode */
1639                         if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1640                             error(0, 0, "No mail for %s", buf); 
1641                     }
1642
1643                 /* very important, this is where we leave the do loop */ 
1644                 if (count == 0)
1645                     break;
1646
1647                 if (check_only)
1648                 {
1649                     if (new == -1 || ctl->fetchall)
1650                         new = count;
1651                     ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1652                     goto cleanUp;
1653                 }
1654                 else if (count > 0)
1655                 {    
1656                     flag        force_retrieval;
1657
1658                     /*
1659                      * What forces this code is that in POP2 and
1660                      * IMAP2bis you can't fetch a message without
1661                      * having it marked `seen'.  In POP3 and IMAP4, on the
1662                      * other hand, you can (peek_capable is set by 
1663                      * each driver module to convey this; it's not a
1664                      * method constant because of the difference between
1665                      * IMAP2bis and IMAP4).
1666                      *
1667                      * The result of being unable to peek is that if there's
1668                      * any kind of transient error (DNS lookup failure, or
1669                      * sendmail refusing delivery due to process-table limits)
1670                      * the message will be marked "seen" on the server without
1671                      * having been delivered.  This is not a big problem if
1672                      * fetchmail is running in foreground, because the user
1673                      * will see a "skipped" message when it next runs and get
1674                      * clued in.
1675                      *
1676                      * But in daemon mode this leads to the message
1677                      * being silently ignored forever.  This is not
1678                      * acceptable.
1679                      *
1680                      * We compensate for this by checking the error
1681                      * count from the previous pass and forcing all
1682                      * messages to be considered new if it's nonzero.
1683                      */
1684                     force_retrieval = !peek_capable && (ctl->errcount > 0);
1685
1686                     /* read, forward, and delete messages */
1687                     for (num = 1; num <= count; num++)
1688                     {
1689                         flag toolarge = NUM_NONZERO(ctl->limit)
1690                             && msgsizes && (msgsizes[num-1] > ctl->limit);
1691                         flag oldmsg = (protocol->is_old && (protocol->is_old)(sock,ctl,num));
1692                         flag fetch_it = !toolarge 
1693                             && (ctl->fetchall || force_retrieval || !oldmsg);
1694                         flag suppress_delete = FALSE;
1695                         flag suppress_forward = FALSE;
1696                         flag suppress_readbody = FALSE;
1697                         flag retained = FALSE;
1698
1699                         /*
1700                          * This check copes with Post Office/NT's
1701                          * annoying habit of randomly prepending bogus
1702                          * LIST items of length -1.  Patrick Audley
1703                          * <paudley@pobox.com> tells us: LIST shows a
1704                          * size of -1, RETR and TOP return "-ERR
1705                          * System error - couldn't open message", and
1706                          * DELE succeeds but doesn't actually delete
1707                          * the message.
1708                          */
1709                         if (msgsizes && msgsizes[num-1] == -1)
1710                         {
1711                             if (outlevel >= O_VERBOSE)
1712                                 error(0, 0, 
1713                                       "Skipping message %d, length -1",
1714                                       num - 1);
1715                             continue;
1716                         }
1717
1718                         /* we may want to reject this message if it's old */
1719                         if (!fetch_it)
1720                         {
1721                             if (outlevel > O_SILENT)
1722                             {
1723                                 error_build("skipping message %d", num);
1724                                 if (toolarge && !check_only) 
1725                                 {
1726                                     char size[32];
1727                                     int cnt;
1728
1729                                     /* convert sz to string */
1730                                     sprintf(size, "%d", msgsizes[num-1]);
1731
1732                                     /* build a list of skipped messages
1733                                      * val.id = size of msg (string cnvt)
1734                                      * val.status.num = warning_poll_count
1735                                      * val.status.mask = nbr of msg this size
1736                                      */
1737
1738                                     current = ctl->skipped;
1739
1740                                     /* initialise warning_poll_count to the
1741                                      * current value so that all new msg will
1742                                      * be included in the next mail
1743                                      */
1744                                     cnt = current? current->val.status.num : 0;
1745
1746                                     /* if entry exists, increment the count */
1747                                     if (current && 
1748                                         str_in_list(&current, size, FALSE))
1749                                     {
1750                                         for ( ; current; 
1751                                                 current = current->next)
1752                                         {
1753                                             if (strcmp(current->id, size) == 0)
1754                                             {
1755                                                 current->val.status.mark++;
1756                                                 break;
1757                                             }
1758                                         }
1759                                     }
1760                                     /* otherwise, create a new entry */
1761                                     /* initialise with current poll count */
1762                                     else
1763                                     {
1764                                         tmp = save_str(&ctl->skipped, size, 1);
1765                                         tmp->val.status.num = cnt;
1766                                     }
1767
1768                                     error_build(" (oversized, %d octets)",
1769                                                 msgsizes[num-1]);
1770                                 }
1771                             }
1772                         }
1773                         else
1774                         {
1775                             flag wholesize = !protocol->fetch_body;
1776
1777                             /* request a message */
1778                             ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1779                             if (ok != 0)
1780                                 goto cleanUp;
1781
1782                             /* -1 means we didn't see a size in the response */
1783                             if (len == -1 && msgsizes)
1784                             {
1785                                 len = msgsizes[num - 1];
1786                                 wholesize = TRUE;
1787                             }
1788
1789                             if (outlevel > O_SILENT)
1790                             {
1791                                 error_build("reading message %d of %d",
1792                                             num,count);
1793
1794                                 if (len > 0)
1795                                     error_build(" (%d %soctets)",
1796                                         len, wholesize ? "" : "header ");
1797                                 if (outlevel >= O_VERBOSE)
1798                                     error_complete(0, 0, "");
1799                                 else
1800                                     error_build(" ");
1801                             }
1802
1803                             /* 
1804                              * Read the message headers and ship them to the
1805                              * output sink.  
1806                              */
1807                             ok = readheaders(sock, len, msgsizes[num-1],
1808                                              ctl, num);
1809                             if (ok == PS_RETAINED)
1810                                 suppress_forward = retained = TRUE;
1811                             else if (ok == PS_TRANSIENT)
1812                                 suppress_delete = suppress_forward = TRUE;
1813                             else if (ok == PS_REFUSED)
1814                                 suppress_forward = TRUE;
1815                             else if (ok == PS_TRUNCATED)
1816                                 suppress_readbody = TRUE;
1817                             else if (ok)
1818                                 goto cleanUp;
1819
1820                             /* 
1821                              * If we're using IMAP4 or something else that
1822                              * can fetch headers separately from bodies,
1823                              * it's time to request the body now.  This
1824                              * fetch may be skipped if we got an anti-spam
1825                              * or other PS_REFUSED error response during
1826                              * read_headers.
1827                              */
1828                             if (protocol->fetch_body && !suppress_readbody) 
1829                             {
1830                                 if (outlevel >= O_VERBOSE)
1831                                     fputc('\n', stderr);
1832
1833                                 if ((ok = (protocol->trail)(sock, ctl, num)))
1834                                     goto cleanUp;
1835                                 len = 0;
1836                                 if (!suppress_forward)
1837                                 {
1838                                     if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1839                                         goto cleanUp;
1840                                     if (outlevel > O_SILENT && !wholesize)
1841                                         error_build(" (%d body octets) ", len);
1842                                 }
1843                             }
1844
1845                             /* process the body now */
1846                             if (len > 0)
1847                             {
1848                                 if (suppress_readbody)
1849                                 {
1850                                   /* When readheaders returns PS_TRUNCATED,
1851                                      the body (which has no content
1852                                      has already been read by readheaders,
1853                                      so we say readbody returned PS_SUCCESS */
1854                                   ok = PS_SUCCESS;
1855                                 }
1856                                 else
1857                                 {
1858                                   ok = readbody(sock,
1859                                                 ctl,
1860                                                 !suppress_forward,
1861                                                 len);
1862                                 }
1863                                 if (ok == PS_TRANSIENT)
1864                                     suppress_delete = suppress_forward = TRUE;
1865                                 else if (ok)
1866                                     goto cleanUp;
1867
1868                                 /* tell server we got it OK and resynchronize */
1869                                 if (protocol->trail)
1870                                 {
1871                                     if (outlevel >= O_VERBOSE)
1872                                         fputc('\n', stderr);
1873
1874                                     ok = (protocol->trail)(sock, ctl, num);
1875                                     if (ok != 0)
1876                                         goto cleanUp;
1877                                 }
1878                             }
1879
1880                             /* count # messages forwarded on this pass */
1881                             if (!suppress_forward)
1882                                 dispatches++;
1883
1884                             /*
1885                              * Check to see if the numbers matched?
1886                              *
1887                              * Yes, some servers foo this up horribly.
1888                              * All IMAP servers seem to get it right, and
1889                              * so does Eudora QPOP at least in 2.xx
1890                              * versions.
1891                              *
1892                              * Microsoft Exchange gets it completely
1893                              * wrong, reporting compressed rather than
1894                              * actual sizes (so the actual length of
1895                              * message is longer than the reported size).
1896                              * Another fine example of Microsoft brain death!
1897                              *
1898                              * Some older POP servers, like the old UCB
1899                              * POP server and the pre-QPOP QUALCOMM
1900                              * versions, report a longer size in the LIST
1901                              * response than actually gets shipped up.
1902                              * It's unclear what is going on here, as the
1903                              * QUALCOMM server (at least) seems to be
1904                              * reporting the on-disk size correctly.
1905                              */
1906                             if (msgsizes && msglen != msgsizes[num-1])
1907                             {
1908                                 if (outlevel >= O_DEBUG)
1909                                     error(0, 0,
1910                                           "message %d was not the expected length (%d actual != %d expected)",
1911                                           num, msglen, msgsizes[num-1]);
1912                             }
1913
1914                             /* end-of-message processing starts here */
1915                             if (!close_sink(ctl, !suppress_forward))
1916                             {
1917                                 ctl->errcount++;
1918                                 suppress_delete = TRUE;
1919                             }
1920                             fetches++;
1921                         }
1922
1923                         /*
1924                          * At this point in flow of control, either
1925                          * we've bombed on a protocol error or had
1926                          * delivery refused by the SMTP server
1927                          * (unlikely -- I've never seen it) or we've
1928                          * seen `accepted for delivery' and the
1929                          * message is shipped.  It's safe to mark the
1930                          * message seen and delete it on the server
1931                          * now.
1932                          */
1933
1934                         /* tell the UID code we've seen this */
1935                         if (ctl->newsaved)
1936                         {
1937                             struct idlist       *sdp;
1938
1939                             for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
1940                                 if (sdp->val.status.num == num)
1941                                     sdp->val.status.mark = UID_SEEN;
1942                         }
1943
1944                         /* maybe we delete this message now? */
1945                         if (retained)
1946                         {
1947                             if (outlevel > O_SILENT) 
1948                                 error_complete(0, 0, " retained");
1949                         }
1950                         else if (protocol->delete
1951                                  && !suppress_delete
1952                                  && (fetch_it ? !ctl->keep : ctl->flush))
1953                         {
1954                             deletions++;
1955                             if (outlevel > O_SILENT) 
1956                                 error_complete(0, 0, " flushed");
1957                             ok = (protocol->delete)(sock, ctl, num);
1958                             if (ok != 0)
1959                                 goto cleanUp;
1960 #ifdef POP3_ENABLE
1961                             delete_str(&ctl->newsaved, num);
1962 #endif /* POP3_ENABLE */
1963                         }
1964                         else if (outlevel > O_SILENT) 
1965                             error_complete(0, 0, " not flushed");
1966
1967                         /* perhaps this as many as we're ready to handle */
1968                         if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
1969                             goto no_error;
1970                     }
1971
1972                     if (!check_only && ctl->skipped)
1973                     {
1974                         clean_skipped_list(&ctl->skipped);
1975                         send_size_warnings(ctl);
1976                     }
1977                 }
1978             } while
1979                   /*
1980                    * Only re-poll if we had some actual forwards, allowed
1981                    * deletions and had no errors.
1982                    * Otherwise it is far too easy to get into infinite loops.
1983                    */
1984                   (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
1985         }
1986
1987    no_error:
1988         ok = (protocol->logout_cmd)(sock, ctl);
1989         /*
1990          * Hmmmm...arguably this would be incorrect if we had fetches but
1991          * no dispatches (due to oversized messages, etc.)
1992          */
1993         if (ok == 0)
1994             ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1995         SockClose(sock);
1996         goto closeUp;
1997
1998     cleanUp:
1999         if (ok != 0 && ok != PS_SOCKET)
2000             (protocol->logout_cmd)(sock, ctl);
2001         SockClose(sock);
2002     }
2003
2004     msg = (const char *)NULL;   /* sacrifice to -Wall */
2005     switch (ok)
2006     {
2007     case PS_SOCKET:
2008         msg = "socket";
2009         break;
2010     case PS_AUTHFAIL:
2011         msg = "authorization";
2012         break;
2013     case PS_SYNTAX:
2014         msg = "missing or bad RFC822 header";
2015         break;
2016     case PS_IOERR:
2017         msg = "MDA";
2018         break;
2019     case PS_ERROR:
2020         msg = "client/server synchronization";
2021         break;
2022     case PS_PROTOCOL:
2023         msg = "client/server protocol";
2024         break;
2025     case PS_LOCKBUSY:
2026         msg = "lock busy on server";
2027         break;
2028     case PS_SMTP:
2029         msg = "SMTP transaction";
2030         break;
2031     case PS_DNS:
2032         msg = "DNS lookup";
2033         break;
2034     case PS_UNDEFINED:
2035         error(0, 0, "undefined");
2036         break;
2037     }
2038     if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX 
2039                 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL 
2040                 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2041         error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2042
2043 closeUp:
2044     /* execute post-initialization command, if any */
2045     if (ctl->postconnect && (ok = system(ctl->postconnect)))
2046     {
2047         char buf[80];
2048
2049         sprintf(buf, "post-connection command failed with status %d", ok);
2050         error(0, 0, buf);
2051         if (ok == PS_SUCCESS)
2052             ok = PS_SYNTAX;
2053     }
2054
2055     signal(SIGALRM, sigsave);
2056     return(ok);
2057 }
2058
2059 #if defined(HAVE_STDARG_H)
2060 void gen_send(int sock, const char *fmt, ... )
2061 #else
2062 void gen_send(sock, fmt, va_alist)
2063 int sock;               /* socket to which server is connected */
2064 const char *fmt;        /* printf-style format */
2065 va_dcl
2066 #endif
2067 /* assemble command in printf(3) style and send to the server */
2068 {
2069     char buf [MSGBUFSIZE+1];
2070     va_list ap;
2071
2072     if (protocol->tagged)
2073         (void) sprintf(buf, "%s ", GENSYM);
2074     else
2075         buf[0] = '\0';
2076
2077 #if defined(HAVE_STDARG_H)
2078     va_start(ap, fmt) ;
2079 #else
2080     va_start(ap);
2081 #endif
2082 #ifdef HAVE_VSNPRINTF
2083     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2084 #else
2085     vsprintf(buf + strlen(buf), fmt, ap);
2086 #endif
2087     va_end(ap);
2088
2089     strcat(buf, "\r\n");
2090     SockWrite(sock, buf, strlen(buf));
2091
2092     if (outlevel >= O_MONITOR)
2093     {
2094         char *cp;
2095
2096         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2097         {
2098             char        *sp;
2099
2100             sp = cp + strlen(shroud);
2101             *cp++ = '*';
2102             while (*sp)
2103                 *cp++ = *sp++;
2104             *cp = '\0';
2105         }
2106         buf[strlen(buf)-2] = '\0';
2107         error(0, 0, "%s> %s", protocol->name, buf);
2108     }
2109 }
2110
2111 int gen_recv(sock, buf, size)
2112 /* get one line of input from the server */
2113 int sock;       /* socket to which server is connected */
2114 char *buf;      /* buffer to receive input */
2115 int size;       /* length of buffer */
2116 {
2117     int oldphase = phase;       /* we don't have to be re-entrant */
2118
2119     phase = SERVER_WAIT;
2120     set_timeout(mytimeout);
2121     if (SockRead(sock, buf, size) == -1)
2122     {
2123         set_timeout(0);
2124         phase = oldphase;
2125         return(PS_SOCKET);
2126     }
2127     else
2128     {
2129         set_timeout(0);
2130         if (buf[strlen(buf)-1] == '\n')
2131             buf[strlen(buf)-1] = '\0';
2132         if (buf[strlen(buf)-1] == '\r')
2133             buf[strlen(buf)-1] = '\0';
2134         if (outlevel >= O_MONITOR)
2135             error(0, 0, "%s< %s", protocol->name, buf);
2136         phase = oldphase;
2137         return(PS_SUCCESS);
2138     }
2139 }
2140
2141 #if defined(HAVE_STDARG_H)
2142 int gen_transact(int sock, const char *fmt, ... )
2143 #else
2144 int gen_transact(int sock, fmt, va_alist)
2145 int sock;               /* socket to which server is connected */
2146 const char *fmt;        /* printf-style format */
2147 va_dcl
2148 #endif
2149 /* assemble command in printf(3) style, send to server, accept a response */
2150 {
2151     int ok;
2152     char buf [MSGBUFSIZE+1];
2153     va_list ap;
2154     int oldphase = phase;       /* we don't have to be re-entrant */
2155
2156     phase = SERVER_WAIT;
2157
2158     if (protocol->tagged)
2159         (void) sprintf(buf, "%s ", GENSYM);
2160     else
2161         buf[0] = '\0';
2162
2163 #if defined(HAVE_STDARG_H)
2164     va_start(ap, fmt) ;
2165 #else
2166     va_start(ap);
2167 #endif
2168 #ifdef HAVE_VSNPRINTF
2169     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2170 #else
2171     vsprintf(buf + strlen(buf), fmt, ap);
2172 #endif
2173     va_end(ap);
2174
2175     strcat(buf, "\r\n");
2176     SockWrite(sock, buf, strlen(buf));
2177
2178     if (outlevel >= O_MONITOR)
2179     {
2180         char *cp;
2181
2182         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2183         {
2184             char        *sp;
2185
2186             sp = cp + strlen(shroud);
2187             *cp++ = '*';
2188             while (*sp)
2189                 *cp++ = *sp++;
2190             *cp = '\0';
2191         }
2192         buf[strlen(buf)-1] = '\0';
2193         error(0, 0, "%s> %s", protocol->name, buf);
2194     }
2195
2196     /* we presume this does its own response echoing */
2197     ok = (protocol->parse_response)(sock, buf);
2198
2199     phase = oldphase;
2200     return(ok);
2201 }
2202
2203 /* driver.c ends here */