]> Pileus Git - ~andy/fetchmail/blob - transact.c
Stefan Esser's security patch.
[~andy/fetchmail] / transact.c
1 /*
2  * transact.c -- transaction primitives for the fetchmail driver loop
3  *
4  * Copyright 2001 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  *
7  * 
8  */
9
10 #include  "config.h"
11 #include  <stdio.h>
12 #include  <string.h>
13 #include  <ctype.h> /* isspace() */
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
29 #ifdef HAVE_NET_SOCKET_H
30 #include <net/socket.h>
31 #endif
32
33 #include "i18n.h"
34 #include "socket.h"
35 #include "fetchmail.h"
36
37 #ifndef strstr          /* glibc-2.1 declares this as a macro */
38 extern char *strstr();  /* needed on sysV68 R3V7.1. */
39 #endif /* strstr */
40
41 int mytimeout;          /* value of nonreponse timeout */
42 int suppress_tags;      /* emit tags? */
43 char shroud[PASSWORDLEN*2+1];   /* string to shroud in debug output */
44 struct msgblk msgblk;
45
46 char tag[TAGLEN];
47 static int tagnum;
48 #define GENSYM  (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
49
50 static int accept_count, reject_count;
51 static struct method *protocol;
52
53 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
54 /* add given name to xmit_names if it matches declared localnames */
55 /*   name:       name to map */
56 /*   ctl:        list of permissible aliases */
57 /*   xmit_names: list of recipient names parsed out */
58 {
59     const char  *lname;
60     int off = 0;
61     
62     lname = idpair_find(&ctl->localnames, name+off);
63     if (!lname && ctl->wildcard)
64         lname = name+off;
65
66     if (lname != (char *)NULL)
67     {
68         if (outlevel >= O_DEBUG)
69             report(stdout, GT_("mapped %s to local %s\n"), name, lname);
70         save_str(xmit_names, lname, XMIT_ACCEPT);
71         accept_count++;
72     }
73 }
74
75 static void find_server_names(const char *hdr,
76                               struct query *ctl,
77                               struct idlist **xmit_names)
78 /* parse names out of a RFC822 header into an ID list */
79 /*   hdr:               RFC822 header in question */
80 /*   ctl:               list of permissible aliases */
81 /*   xmit_names:        list of recipient names parsed out */
82 {
83     if (hdr == (char *)NULL)
84         return;
85     else
86     {
87         char    *cp;
88
89         for (cp = nxtaddr(hdr);
90              cp != NULL;
91              cp = nxtaddr(NULL))
92         {
93             char        *atsign;
94
95             /* 
96              * Handle empty address from a To: header containing only 
97              * a comment.
98              */
99             if (!*cp)
100                 continue;
101
102             /*
103              * If the name of the user begins with a qmail virtual
104              * domain prefix, ignore the prefix.  Doing this here
105              * means qvirtual will work either with ordinary name
106              * mapping or with a localdomains option.
107              */
108             if (ctl->server.qvirtual)
109             {
110                 int sl = strlen(ctl->server.qvirtual);
111  
112                 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
113                     cp += sl;
114             }
115
116             if ((atsign = strchr(cp, '@'))) {
117                 struct idlist   *idp;
118
119                 /*
120                  * Does a trailing segment of the hostname match something
121                  * on the localdomains list?  If so, save the whole name
122                  * and keep going.
123                  */
124                 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
125                     char        *rhs;
126
127                     rhs = atsign + (strlen(atsign) - strlen(idp->id));
128                     if (rhs > atsign &&
129                         (rhs[-1] == '.' || rhs[-1] == '@') &&
130                         strcasecmp(rhs, idp->id) == 0)
131                     {
132                         if (outlevel >= O_DEBUG)
133                             report(stdout, GT_("passed through %s matching %s\n"), 
134                                   cp, idp->id);
135                         save_str(xmit_names, cp, XMIT_ACCEPT);
136                         accept_count++;
137                         goto nomap;
138                     }
139                 }
140
141                 /* if we matched a local domain, idp != NULL */
142                 if (!idp)
143                 {
144                     /*
145                      * Check to see if the right-hand part is an alias
146                      * or MX equivalent of the mailserver.  If it's
147                      * not, skip this name.  If it is, we'll keep
148                      * going and try to find a mapping to a client name.
149                      */
150                     if (!is_host_alias(atsign+1, ctl))
151                     {
152                         save_str(xmit_names, cp, XMIT_REJECT);
153                         reject_count++;
154                         continue;
155                     }
156                 }
157                 atsign[0] = '\0';
158                 map_name(cp, ctl, xmit_names);
159             nomap:;
160             }
161         }
162     }
163 }
164
165 /*
166  * Return zero on a syntactically invalid address, nz on a valid one.
167  *
168  * This used to be strchr(a, '.'), but it turns out that lines like this
169  *
170  * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
171  *          id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
172  *
173  * are not uncommon.  So now we just check that the following token is
174  * not itself an email address.
175  */
176 #define VALID_ADDRESS(a)        !strchr(a, '@')
177
178 static char *parse_received(struct query *ctl, char *bufp)
179 /* try to extract real address from the Received line */
180 /* If a valid Received: line is found, we return the full address in
181  * a buffer which can be parsed from nxtaddr().  This is to ansure that
182  * the local domain part of the address can be passed along in 
183  * find_server_names() if it contains one.
184  * Note: We should return a dummy header containing the address 
185  * which makes nxtaddr() behave correctly. 
186  */
187 {
188     char *base, *ok = (char *)NULL;
189     static char rbuf[HOSTLEN + USERNAMELEN + 4]; 
190
191 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
192
193     /*
194      * Try to extract the real envelope addressee.  We look here
195      * specifically for the mailserver's Received line.
196      * Note: this will only work for sendmail, or an MTA that
197      * shares sendmail's convention for embedding the envelope
198      * address in the Received line.  Sendmail itself only
199      * does this when the mail has a single recipient.
200      */
201     if (outlevel >= O_DEBUG)
202         report(stdout, GT_("analyzing Received line:\n%s"), bufp);
203
204     /* search for whitepace-surrounded "by" followed by valid address */
205     for (base = bufp;  ; base = ok + 2)
206     {
207         if (!(ok = strstr(base, "by")))
208             break;
209         else if (!isspace(ok[-1]) || !isspace(ok[2]))
210             continue;
211         else
212         {
213             char        *sp, *tp;
214
215             /* extract space-delimited token after "by" */
216             for (sp = ok + 2; isspace(*sp); sp++)
217                 continue;
218             tp = rbuf;
219             for (; !isspace(*sp); sp++)
220                 RBUF_WRITE(*sp);
221             *tp = '\0';
222
223             /* look for valid address */
224             if (VALID_ADDRESS(rbuf))
225                 break;
226             else
227                 ok = sp - 1;    /* arrange to skip this token */
228         }
229     }
230     if (ok)
231     {
232         /*
233          * If it's a DNS name of the mail server, look for the
234          * recipient name after a following "for".  Otherwise
235          * punt.
236          */
237         if (is_host_alias(rbuf, ctl))
238         {
239             if (outlevel >= O_DEBUG)
240                 report(stdout, 
241                       GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
242         }
243         else
244         {
245             if (outlevel >= O_DEBUG)
246                 report(stdout, 
247                       GT_("line rejected, %s is not an alias of the mailserver\n"), 
248                       rbuf);
249             return(NULL);
250         }
251
252         /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
253         for (base = ok + 4 + strlen(rbuf);  ; base = ok + 2)
254         {
255             if (!(ok = strstr(base, "for")))
256                 break;
257             else if (!isspace(ok[-1]) || !isspace(ok[3]))
258                 continue;
259             else
260             {
261                 char    *sp, *tp;
262
263                 /* extract space-delimited token after "for" */
264                 for (sp = ok + 3; isspace(*sp); sp++)
265                     continue;
266                 tp = rbuf;
267                 for (; !isspace(*sp); sp++)
268                     RBUF_WRITE(*sp);
269                 *tp = '\0';
270
271                 if (strchr(rbuf, '@'))
272                     break;
273                 else
274                     ok = sp - 1;        /* arrange to skip this token */
275             }
276         }
277         if (ok)
278         {
279             flag        want_gt = FALSE;
280             char        *sp, *tp;
281
282             /* char after "for" could be space or a continuation newline */
283             for (sp = ok + 4; isspace(*sp); sp++)
284                 continue;
285             tp = rbuf;
286             RBUF_WRITE(':');    /* Here is the hack.  This is to be friends */
287             RBUF_WRITE(' ');    /* with nxtaddr()... */
288             if (*sp == '<')
289             {
290                 want_gt = TRUE;
291                 sp++;
292             }
293             while (*sp == '@')          /* skip routes */
294                 while (*sp && *sp++ != ':')
295                     continue;
296             while (*sp
297                    && (want_gt ? (*sp != '>') : !isspace(*sp))
298                    && *sp != ';')
299                 if (!isspace(*sp))
300                 {
301                     RBUF_WRITE(*sp);
302                     sp++;
303                 }    
304                 else
305                 {
306                     /* uh oh -- whitespace here can't be right! */
307                     ok = (char *)NULL;
308                     break;
309                 }
310             RBUF_WRITE('\n');
311             *tp = '\0';
312             if (strlen(rbuf) <= 3)      /* apparently nothing has been found */
313                 ok = NULL;
314         } else
315             ok = (char *)NULL;
316     }
317
318     if (!ok)
319     {
320         if (outlevel >= O_DEBUG)
321             report(stdout, GT_("no Received address found\n"));
322         return(NULL);
323     }
324     else
325     {
326         if (outlevel >= O_DEBUG) {
327             char *lf = rbuf + strlen(rbuf)-1;
328             *lf = '\0';
329             if (outlevel >= O_DEBUG)
330                 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
331             *lf = '\n';
332         }
333         return(rbuf);
334     }
335 }
336
337 /* shared by readheaders and readbody */
338 static int sizeticker;
339
340 #define EMPTYLINE(s)    ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
341
342 int readheaders(int sock,
343                        long fetchlen,
344                        long reallen,
345                        struct query *ctl,
346                        int num)
347 /* read message headers and ship to SMTP or MDA */
348 /*   sock:              to which the server is connected */
349 /*   fetchlen:          length of message according to fetch response */
350 /*   reallen:           length of message according to getsizes */
351 /*   ctl:               query control record */
352 /*   num:               index of message */
353 {
354     struct addrblk
355     {
356         int             offset;
357         struct addrblk  *next;
358     };
359     struct addrblk      *to_addrchain = NULL;
360     struct addrblk      **to_chainptr = &to_addrchain;
361     struct addrblk      *resent_to_addrchain = NULL;
362     struct addrblk      **resent_to_chainptr = &resent_to_addrchain;
363
364     char                buf[MSGBUFSIZE+1];
365     int                 from_offs, reply_to_offs, resent_from_offs;
366     int                 app_from_offs, sender_offs, resent_sender_offs;
367     int                 env_offs;
368     char                *received_for, *rcv, *cp, *delivered_to;
369     int                 n, linelen, oldlen, ch, remaining, skipcount;
370     struct idlist       *idp;
371     flag                no_local_matches = FALSE;
372     flag                headers_ok, has_nuls;
373     int                 olderrs, good_addresses, bad_addresses;
374
375     sizeticker = 0;
376     has_nuls = headers_ok = FALSE;
377     msgblk.return_path[0] = '\0';
378     olderrs = ctl->errcount;
379
380     /* read message headers */
381     msgblk.reallen = reallen;
382
383     /*
384      * We used to free the header block unconditionally at the end of 
385      * readheaders, but it turns out that if close_sink() hits an error
386      * condition the code for sending bouncemail will actually look
387      * at the freed storage and coredump...
388      */
389     if (msgblk.headers)
390        free(msgblk.headers);
391
392     /* initially, no message ID */
393     if (ctl->thisid)
394         free(ctl->thisid);
395     ctl->thisid = NULL;
396
397     msgblk.headers = received_for = delivered_to = NULL;
398     from_offs = reply_to_offs = resent_from_offs = app_from_offs = 
399         sender_offs = resent_sender_offs = env_offs = -1;
400     oldlen = 0;
401     msgblk.msglen = 0;
402     skipcount = 0;
403     ctl->mimemsg = 0;
404
405     for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
406     {
407         char *line;
408         int overlong = FALSE;
409
410         line = xmalloc(sizeof(buf));
411         linelen = 0;
412         line[0] = '\0';
413         do {
414             set_timeout(mytimeout);
415             if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
416                 set_timeout(0);
417                 free(line);
418                 free(msgblk.headers);
419                 msgblk.headers = NULL;
420                 return(PS_SOCKET);
421             }
422             set_timeout(0);
423             linelen += n;
424             msgblk.msglen += n;
425
426                 /*
427                  * Try to gracefully handle the case, where the length of a
428                  * line exceeds MSGBUFSIZE.
429                  */
430                 if ( n && buf[n-1] != '\n' ) {
431                         unsigned int llen = strlen(line);
432                         overlong = TRUE;
433                         line = realloc(line, llen + n + 1);
434                         strcpy(line + llen, buf);
435                         ch = ' '; /* So the next iteration starts */
436                         continue;
437                 }
438
439             /* lines may not be properly CRLF terminated; fix this for qmail */
440             if (ctl->forcecr)
441             {
442                 cp = buf + strlen(buf) - 1;
443                 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
444                 {
445                     *cp++ = '\r';
446                     *cp++ = '\n';
447                     *cp++ = '\0';
448                 }
449             }
450
451                 /*
452                  * Decode MIME encoded headers. We MUST do this before
453                  * looking at the Content-Type / Content-Transfer-Encoding
454                  * headers (RFC 2046).
455                  */
456                 if ( ctl->mimedecode && overlong ) {
457                         /*
458                          * If we received an overlong line, we have to decode the
459                          * whole line at once.
460                          */
461                         line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
462                         strcat(line, buf);
463                         UnMimeHeader(line);
464                 }
465                 else {
466                         if ( ctl->mimedecode )
467                                 UnMimeHeader(buf);
468
469                         line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
470                         strcat(line, buf);
471                 }
472
473             /* check for end of headers */
474             if (EMPTYLINE(line))
475             {
476                 headers_ok = TRUE;
477                 has_nuls = (linelen != strlen(line));
478                 free(line);
479                 goto process_headers;
480             }
481
482             /*
483              * Check for end of message immediately.  If one of your folders
484              * has been mangled, the delimiter may occur directly after the
485              * header.
486              */
487             if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
488             {
489                 headers_ok = FALSE;
490                 has_nuls = (linelen != strlen(line));
491                 free(line);
492                 goto process_headers;
493             }
494
495             /*
496              * At least one brain-dead website (netmind.com) is known to
497              * send out robotmail that's missing the RFC822 delimiter blank
498              * line before the body! Without this check fetchmail segfaults.
499              * With it, we treat such messages as though they had the missing
500              * blank line.
501              */
502             if (!isspace(line[0]) && !strchr(line, ':'))
503             {
504                 headers_ok = FALSE;
505                 has_nuls = (linelen != strlen(line));
506                 free(line);
507                 goto process_headers;
508             }
509
510             /* check for RFC822 continuations */
511             set_timeout(mytimeout);
512             ch = SockPeek(sock);
513             set_timeout(0);
514         } while
515             (ch == ' ' || ch == '\t');  /* continuation to next line? */
516
517         /* write the message size dots */
518         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
519         {
520             sizeticker += linelen;
521             while (sizeticker >= SIZETICKER)
522             {
523                 if ((!run.use_syslog && !isafile(1)) || run.showdots)
524                 {
525                     fputc('.', stdout);
526                     fflush(stdout);
527                 }
528                 sizeticker -= SIZETICKER;
529             }
530         }
531
532         /* we see an ordinary (non-header, non-message-delimiter line */
533         has_nuls = (linelen != strlen(line));
534
535         /* save the message's ID, we may use it for killing duplicates later */
536         if (MULTIDROP(ctl) && !strncasecmp(line, "Message-ID:", 11))
537             ctl->thisid = xstrdup(line);
538
539         /*
540          * The University of Washington IMAP server (the reference
541          * implementation of IMAP4 written by Mark Crispin) relies
542          * on being able to keep base-UID information in a special
543          * message at the head of the mailbox.  This message should
544          * neither be deleted nor forwarded.
545          */
546 #ifdef POP2_ENABLE
547         /*
548          * We disable this check under POP2 because there's no way to
549          * prevent deletion of the message.  So at least we ought to 
550          * forward it to the user so he or she will have some clue
551          * that things have gone awry.
552          */
553 #if INET6_ENABLE
554         if (strncmp(protocol->service, "pop2", 4))
555 #else /* INET6_ENABLE */
556         if (protocol->port != 109)
557 #endif /* INET6_ENABLE */
558 #endif /* POP2_ENABLE */
559             if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
560                 free(line);
561                 free(msgblk.headers);
562                 msgblk.headers = NULL;
563                 return(PS_RETAINED);
564             }
565
566         /*
567          * This code prevents fetchmail from becoming an accessory after
568          * the fact to upstream sendmails with the `E' option on.  It also
569          * copes with certain brain-dead POP servers (like NT's) that pass
570          * through Unix from_ lines.
571          *
572          * Either of these bugs can result in a non-RFC822 line at the
573          * beginning of the headers.  If fetchmail just passes it
574          * through, the client listener may think the message has *no*
575          * headers (since the first) line it sees doesn't look
576          * RFC822-conformant) and fake up a set.
577          *
578          * What the user would see in this case is bogus (synthesized)
579          * headers, followed by a blank line, followed by the >From, 
580          * followed by the real headers, followed by a blank line,
581          * followed by text.
582          *
583          * We forestall this lossage by tossing anything that looks
584          * like an escaped or passed-through From_ line in headers.
585          * These aren't RFC822 so our conscience is clear...
586          */
587         if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
588         {
589             free(line);
590             continue;
591         }
592
593         /*
594          * We remove all Delivered-To: headers.
595          * 
596          * This is to avoid false mail loops messages when delivering
597          * local messages to and from a Postfix/qmail mailserver. 
598          */
599         if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13)) 
600         {
601             if (delivered_to)
602                 free(line);
603             else 
604                 delivered_to = line;
605             continue;
606         }
607
608         /*
609          * If we see a Status line, it may have been inserted by an MUA
610          * on the mail host, or it may have been inserted by the server
611          * program after the headers in the transaction stream.  This
612          * can actually hose some new-mail notifiers such as xbuffy,
613          * which assumes any Status line came from a *local* MDA and
614          * therefore indicates that the message has been seen.
615          *
616          * Some buggy POP servers (including at least the 3.3(20)
617          * version of the one distributed with IMAP) insert empty
618          * Status lines in the transaction stream; we'll chuck those
619          * unconditionally.  Nonempty ones get chucked if the user
620          * turns on the dropstatus flag.
621          */
622         {
623             char        *cp;
624
625             if (!strncasecmp(line, "Status:", 7))
626                 cp = line + 7;
627             else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
628                 cp = line + 17;
629             else
630                 cp = NULL;
631             if (cp) {
632                 while (*cp && isspace(*cp)) cp++;
633                 if (!*cp || ctl->dropstatus)
634                 {
635                     free(line);
636                     continue;
637                 }
638             }
639         }
640
641         if (ctl->rewrite)
642             line = reply_hack(line, ctl->server.truename);
643
644         /*
645          * OK, this is messy.  If we're forwarding by SMTP, it's the
646          * SMTP-receiver's job (according to RFC821, page 22, section
647          * 4.1.1) to generate a Return-Path line on final delivery.
648          * The trouble is, we've already got one because the
649          * mailserver's SMTP thought *it* was responsible for final
650          * delivery.
651          *
652          * Stash away the contents of Return-Path (as modified by reply_hack)
653          * for use in generating MAIL FROM later on, then prevent the header
654          * from being saved with the others.  In effect, we strip it off here.
655          *
656          * If the SMTP server conforms to the standards, and fetchmail gets the
657          * envelope sender from the Return-Path, the new Return-Path should be
658          * exactly the same as the original one.
659          *
660          * We do *not* want to ignore empty Return-Path headers.  These should
661          * be passed through as a way of indicating that a message should
662          * not trigger bounces if delivery fails.  What we *do* need to do is
663          * make sure we never try to rewrite such a blank Return-Path.  We
664          * handle this with a check for <> in the rewrite logic above.
665          */
666         if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
667         {
668             strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
669             msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
670             if (!ctl->mda) {
671                 free(line);
672                 continue;
673             }
674         }
675
676         if (!msgblk.headers)
677         {
678             oldlen = strlen(line);
679             msgblk.headers = xmalloc(oldlen + 1);
680             (void) strcpy(msgblk.headers, line);
681             free(line);
682             line = msgblk.headers;
683         }
684         else
685         {
686             char *newhdrs;
687             int newlen;
688
689             newlen = oldlen + strlen(line);
690             newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
691             if (newhdrs == NULL) {
692                 free(line);
693                 return(PS_IOERR);
694             }
695             msgblk.headers = newhdrs;
696             strcpy(msgblk.headers + oldlen, line);
697             free(line);
698             line = msgblk.headers + oldlen;
699             oldlen = newlen;
700         }
701
702         /* find offsets of various special headers */
703         if (!strncasecmp("From:", line, 5))
704             from_offs = (line - msgblk.headers);
705         else if (!strncasecmp("Reply-To:", line, 9))
706             reply_to_offs = (line - msgblk.headers);
707         else if (!strncasecmp("Resent-From:", line, 12))
708             resent_from_offs = (line - msgblk.headers);
709         else if (!strncasecmp("Apparently-From:", line, 16))
710             app_from_offs = (line - msgblk.headers);
711         /*
712          * Netscape 4.7 puts "Sender: zap" in mail headers.  Perverse...
713          *
714          * But a literal reading of RFC822 sec. 4.4.2 supports the idea
715          * that Sender: *doesn't* have to be a working email address.
716          *
717          * The definition of the Sender header in RFC822 says, in
718          * part, "The Sender mailbox specification includes a word
719          * sequence which must correspond to a specific agent (i.e., a
720          * human user or a computer program) rather than a standard
721          * address."  That implies that the contents of the Sender
722          * field don't need to be a legal email address at all So
723          * ignore any Sender or Resent-Semnder lines unless they
724          * contain @.
725          *
726          * (RFC2822 says the condents of Sender must be a valid mailbox
727          * address, which is also what RFC822 4.4.4 implies.)
728          */
729         else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
730             sender_offs = (line - msgblk.headers);
731         else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
732             resent_sender_offs = (line - msgblk.headers);
733
734 #ifdef __UNUSED__
735         else if (!strncasecmp("Message-Id:", line, 11))
736         {
737             if (ctl->server.uidl)
738             {
739                 char id[IDLEN+1];
740
741                 line[IDLEN+12] = 0;             /* prevent stack overflow */
742                 sscanf(line+12, "%s", id);
743                 if (!str_find( &ctl->newsaved, num))
744                 {
745                     struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
746                     new->val.status.num = num;
747                 }
748             }
749         }
750 #endif /* __UNUSED__ */
751
752         /* if multidrop is on, gather addressee headers */
753         if (MULTIDROP(ctl))
754         {
755             if (!strncasecmp("To:", line, 3)
756                 || !strncasecmp("Cc:", line, 3)
757                 || !strncasecmp("Bcc:", line, 4)
758                 || !strncasecmp("Apparently-To:", line, 14))
759             {
760                 *to_chainptr = xmalloc(sizeof(struct addrblk));
761                 (*to_chainptr)->offset = (line - msgblk.headers);
762                 to_chainptr = &(*to_chainptr)->next; 
763                 *to_chainptr = NULL;
764             }
765
766             else if (!strncasecmp("Resent-To:", line, 10)
767                      || !strncasecmp("Resent-Cc:", line, 10)
768                      || !strncasecmp("Resent-Bcc:", line, 11))
769             {
770                 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
771                 (*resent_to_chainptr)->offset = (line - msgblk.headers);
772                 resent_to_chainptr = &(*resent_to_chainptr)->next; 
773                 *resent_to_chainptr = NULL;
774             }
775
776             else if (ctl->server.envelope != STRING_DISABLED)
777             {
778                 if (ctl->server.envelope 
779                     && strcasecmp(ctl->server.envelope, "Received"))
780                 {
781                     if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
782                                                        line,
783                                                        strlen(ctl->server.envelope)))
784                     {                           
785                         if (skipcount++ < ctl->server.envskip)
786                             continue;
787                         env_offs = (line - msgblk.headers);
788                     }    
789                 }
790                 else if (!received_for && !strncasecmp("Received:", line, 9))
791                 {
792                     if (skipcount++ < ctl->server.envskip)
793                         continue;
794                     received_for = parse_received(ctl, line);
795                 }
796             }
797         }
798     }
799
800  process_headers:    
801     /*
802      * When mail delivered to a multidrop mailbox on the server is
803      * addressed to multiple people on the client machine, there will
804      * be one copy left in the box for each recipient.  This is not a
805      * problem if we have the actual recipient address to dispatch on
806      * (e.g. because we've mined it out of sendmail trace headers, or
807      * a qmail Delivered-To line, or a declared sender envelope line).
808      *
809      * But if we're mining addressees out of the To/Cc/Bcc fields, and
810      * if the mail is addressed to N people, each recipient will
811      * get N copies.  This is bad when N > 1.
812      *
813      * Foil this by suppressing all but one copy of a message with
814      * a given Message-ID.  The accept_count test ensures that
815      * multiple pieces of email with the same Message-ID, each
816      * with a *single* addressee (the N == 1 case), won't be 
817      * suppressed.
818      *
819      * Note: This implementation only catches runs of successive
820      * messages with the same ID, but that should be good
821      * enough. A more general implementation would have to store
822      * ever-growing lists of seen message-IDs; in a long-running
823      * daemon this would turn into a memory leak even if the 
824      * implementation were perfect.
825      * 
826      * Don't mess with this code casually.  It would be way too easy
827      * to break it in a way that blackholed mail.  Better to pass
828      * the occasional duplicate than to do that...
829      */
830     if (!received_for && env_offs == -1 && !delivered_to)
831     {
832         if (ctl->lastid && ctl->thisid && !strcasecmp(ctl->lastid, ctl->thisid))
833         {
834             if (accept_count > 1)
835                 return(PS_REFUSED);
836         }
837         else
838         {
839             if (ctl->lastid)
840                 free(ctl->lastid);
841             ctl->lastid = ctl->thisid;
842             ctl->thisid = NULL;
843         }
844     }
845
846     /*
847      * We want to detect this early in case there are so few headers that the
848      * dispatch logic barfs.
849      */
850     if (!headers_ok)
851     {
852         if (outlevel > O_SILENT)
853             report(stdout,
854                    GT_("message delimiter found while scanning headers\n"));
855     }
856
857     /*
858      * Hack time.  If the first line of the message was blank, with no headers
859      * (this happens occasionally due to bad gatewaying software) cons up
860      * a set of fake headers.  
861      *
862      * If you modify the fake header template below, be sure you don't
863      * make either From or To address @-less, otherwise the reply_hack
864      * logic will do bad things.
865      */
866     if (msgblk.headers == (char *)NULL)
867     {
868 #ifdef HAVE_SNPRINTF
869         snprintf(buf, sizeof(buf),
870 #else
871         sprintf(buf, 
872 #endif /* HAVE_SNPRINTF */
873         "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
874                 user, fetchmailhost, ctl->remotename, ctl->server.truename);
875         msgblk.headers = xstrdup(buf);
876     }
877
878     /*
879      * We can now process message headers before reading the text.
880      * In fact we have to, as this will tell us where to forward to.
881      */
882
883     /* Check for MIME headers indicating possible 8-bit data */
884     ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
885
886 #ifdef SDPS_ENABLE
887     if (ctl->server.sdps && sdps_envfrom)
888     {
889         /* We have the real envelope return-path, stored out of band by
890          * SDPS - that's more accurate than any header is going to be.
891          */
892         strcpy(msgblk.return_path, sdps_envfrom);
893         free(sdps_envfrom);
894     } else
895 #endif /* SDPS_ENABLE */
896     /*
897      * If there is a Return-Path address on the message, this was
898      * almost certainly the MAIL FROM address given the originating
899      * sendmail.  This is the best thing to use for logging the
900      * message origin (it sets up the right behavior for bounces and
901      * mailing lists).  Otherwise, fall down to the next available 
902      * envelope address (which is the most probable real sender).
903      * *** The order is important! ***
904      * This is especially useful when receiving mailing list
905      * messages in multidrop mode.  if a local address doesn't
906      * exist, the bounce message won't be returned blindly to the 
907      * author or to the list itself but rather to the list manager
908      * (ex: specified by "Sender:") which is much less annoying.  This 
909      * is true for most mailing list packages.
910      */
911     if( !msgblk.return_path[0] ){
912         char *ap = NULL;
913         if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
914         else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
915         else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
916         else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
917         else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
918         else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
919         /* multi-line MAIL FROM addresses confuse SMTP terribly */
920         if (ap && !strchr(ap, '\n')) {
921             strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
922             msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
923         }
924     }
925
926     /* cons up a list of local recipients */
927     msgblk.recipients = (struct idlist *)NULL;
928     accept_count = reject_count = 0;
929     /* is this a multidrop box? */
930     if (MULTIDROP(ctl))
931     {
932 #ifdef SDPS_ENABLE
933         if (ctl->server.sdps && sdps_envto)
934         {
935             /* We have the real envelope recipient, stored out of band by
936              * SDPS - that's more accurate than any header is going to be.
937              */
938             find_server_names(sdps_envto, ctl, &msgblk.recipients);
939             free(sdps_envto);
940         } else
941 #endif /* SDPS_ENABLE */ 
942         if (env_offs > -1)          /* We have the actual envelope addressee */
943             find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
944         else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
945       ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
946    {
947             find_server_names(delivered_to, ctl, &msgblk.recipients);
948        free(delivered_to);
949    }
950         else if (received_for)
951             /*
952              * We have the Received for addressee.  
953              * It has to be a mailserver address, or we
954              * wouldn't have got here.
955              * We use find_server_names() to let local 
956              * hostnames go through.
957              */
958             find_server_names(received_for, ctl, &msgblk.recipients);
959         else
960         {
961             /*
962              * We haven't extracted the envelope address.
963              * So check all the "Resent-To" header addresses if 
964              * they exist.  If and only if they don't, consider
965              * the "To" addresses.
966              */
967             register struct addrblk *nextptr;
968             if (resent_to_addrchain) {
969                 /* delete the "To" chain and substitute it 
970                  * with the "Resent-To" list 
971                  */
972                 while (to_addrchain) {
973                     nextptr = to_addrchain->next;
974                     free(to_addrchain);
975                     to_addrchain = nextptr;
976                 }
977                 to_addrchain = resent_to_addrchain;
978                 resent_to_addrchain = NULL;
979             }
980             /* now look for remaining adresses */
981             while (to_addrchain) {
982                 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
983                 nextptr = to_addrchain->next;
984                 free(to_addrchain);
985                 to_addrchain = nextptr;
986             }
987         }
988         if (!accept_count)
989         {
990             no_local_matches = TRUE;
991             save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
992             if (outlevel >= O_DEBUG)
993                 report(stdout,
994                       GT_("no local matches, forwarding to %s\n"),
995                       run.postmaster);
996         }
997     }
998     else        /* it's a single-drop box, use first localname */
999         save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1000
1001
1002     /*
1003      * Time to either address the message or decide we can't deliver it yet.
1004      */
1005     if (ctl->errcount > olderrs)        /* there were DNS errors above */
1006     {
1007         if (outlevel >= O_DEBUG)
1008             report(stdout,
1009                    GT_("forwarding and deletion suppressed due to DNS errors\n"));
1010         free(msgblk.headers);
1011         msgblk.headers = NULL;
1012         free_str_list(&msgblk.recipients);
1013         return(PS_TRANSIENT);
1014     }
1015     else
1016     {
1017         /* set up stuffline() so we can deliver the message body through it */ 
1018         if ((n = open_sink(ctl, &msgblk,
1019                            &good_addresses, &bad_addresses)) != PS_SUCCESS)
1020         {
1021             free(msgblk.headers);
1022             msgblk.headers = NULL;
1023             free_str_list(&msgblk.recipients);
1024             return(n);
1025         }
1026     }
1027
1028     n = 0;
1029     /*
1030      * Some server/sendmail combinations cause problems when our
1031      * synthetic Received line is before the From header.  Cope
1032      * with this...
1033      */
1034     if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1035         rcv = msgblk.headers;
1036     /* handle ">Received:" lines too */
1037     while (rcv > msgblk.headers && rcv[-1] != '\n')
1038         rcv--;
1039     if (rcv > msgblk.headers)
1040     {
1041         char    c = *rcv;
1042
1043         *rcv = '\0';
1044         n = stuffline(ctl, msgblk.headers);
1045         *rcv = c;
1046     }
1047     if (!run.invisible && n != -1)
1048     {
1049         /* utter any per-message Received information we need here */
1050         if (ctl->server.trueaddr) {
1051 #ifdef HAVE_SNPRINTF
1052             snprintf(buf, sizeof(buf),
1053 #else
1054             sprintf(buf, 
1055 #endif /* HAVE_SNPRINTF */
1056                     "Received: from %s [%u.%u.%u.%u]\r\n", 
1057                     ctl->server.truename,
1058                     (unsigned char)ctl->server.trueaddr[0],
1059                     (unsigned char)ctl->server.trueaddr[1],
1060                     (unsigned char)ctl->server.trueaddr[2],
1061                     (unsigned char)ctl->server.trueaddr[3]);
1062         } else {
1063 #ifdef HAVE_SNPRINTF
1064           snprintf(buf, sizeof(buf),
1065 #else                       
1066           sprintf(buf,
1067 #endif /* HAVE_SNPRINTF */
1068                   "Received: from %s\r\n", ctl->server.truename);
1069         }
1070         n = stuffline(ctl, buf);
1071         if (n != -1)
1072         {
1073             /*
1074              * This header is technically invalid under RFC822.
1075              * POP3, IMAP, etc. are not legal mail-parameter values.
1076              */
1077 #ifdef HAVE_SNPRINTF
1078             snprintf(buf, sizeof(buf),
1079 #else
1080             sprintf(buf,
1081 #endif /* HAVE_SNPRINTF */
1082                     "\tby %s with %s (fetchmail-%s",
1083                     fetchmailhost,
1084                     protocol->name,
1085                     VERSION);
1086             if (ctl->tracepolls)
1087             {
1088                 sprintf(buf + strlen(buf), " polling %s account %s",
1089                         ctl->server.pollname, 
1090                         ctl->remotename);
1091             }
1092 #ifdef HAVE_SNPRINTF
1093             snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1094 #else
1095             strcat(buf, ")\r\n");
1096 #endif /* HAVE_SNPRINTF */
1097             n = stuffline(ctl, buf);
1098             if (n != -1)
1099             {
1100                 buf[0] = '\t';
1101                 if (good_addresses == 0)
1102                 {
1103 #ifdef HAVE_SNPRINTF
1104                     snprintf(buf+1, sizeof(buf)-1,
1105 #else
1106                     sprintf(buf+1,
1107 #endif /* HAVE_SNPRINTF */
1108                             "for %s (by default); ",
1109                             rcpt_address (ctl, run.postmaster, 0));
1110                 }
1111                 else if (good_addresses == 1)
1112                 {
1113                     for (idp = msgblk.recipients; idp; idp = idp->next)
1114                         if (idp->val.status.mark == XMIT_ACCEPT)
1115                             break;      /* only report first address */
1116 #ifdef HAVE_SNPRINTF
1117                     snprintf(buf+1, sizeof(buf)-1,
1118 #else                       
1119                     sprintf(buf+1,
1120 #endif /* HAVE_SNPRINTF */
1121                             "for %s", rcpt_address (ctl, idp->id, 1));
1122                     sprintf(buf+strlen(buf), " (%s); ",
1123                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1124                 }
1125                 else
1126                     buf[1] = '\0';
1127
1128 #ifdef HAVE_SNPRINTF
1129                 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1130                         rfc822timestamp());
1131 #else
1132                 strcat(buf, rfc822timestamp());
1133                 strcat(buf, "\r\n");
1134 #endif /* HAVE_SNPRINTF */
1135                 n = stuffline(ctl, buf);
1136             }
1137         }
1138     }
1139
1140     if (n != -1)
1141         n = stuffline(ctl, rcv);        /* ship out rest of msgblk.headers */
1142
1143     if (n == -1)
1144     {
1145         report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1146         release_sink(ctl);
1147         free(msgblk.headers);
1148         msgblk.headers = NULL;
1149         free_str_list(&msgblk.recipients);
1150         return(PS_IOERR);
1151     }
1152     else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !isafile(2))
1153         fputs("#", stdout);
1154
1155     /* write error notifications */
1156     if (no_local_matches || has_nuls || bad_addresses)
1157     {
1158         int     errlen = 0;
1159         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1160
1161         errmsg = errhd;
1162         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1163         if (no_local_matches)
1164         {
1165             if (reject_count != 1)
1166                 strcat(errhd, GT_("no recipient addresses matched declared local names"));
1167             else
1168             {
1169                 for (idp = msgblk.recipients; idp; idp = idp->next)
1170                     if (idp->val.status.mark == XMIT_REJECT)
1171                         break;
1172 #ifdef HAVE_SNPRINTF
1173                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1174 #else
1175                 sprintf(errhd+strlen(errhd),
1176 #endif /* HAVE_SNPRINTF */
1177                         GT_("recipient address %s didn't match any local name"), idp->id);
1178             }
1179         }
1180
1181         if (has_nuls)
1182         {
1183             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1184 #ifdef HAVE_SNPRINTF
1185                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1186             snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1187 #else
1188                 strcat(errhd, "; ");
1189             strcat(errhd,
1190 #endif /* HAVE_SNPRINTF */
1191                         GT_("message has embedded NULs"));
1192         }
1193
1194         if (bad_addresses)
1195         {
1196             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1197 #ifdef HAVE_SNPRINTF
1198                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1199             snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1200 #else
1201                 strcat(errhd, "; ");
1202             strcat(errhd,
1203 #endif /* HAVE_SNPRINTF */
1204                         GT_("SMTP listener rejected local recipient addresses: "));
1205             errlen = strlen(errhd);
1206             for (idp = msgblk.recipients; idp; idp = idp->next)
1207                 if (idp->val.status.mark == XMIT_RCPTBAD)
1208                     errlen += strlen(idp->id) + 2;
1209
1210             xalloca(errmsg, char *, errlen+3);
1211             (void) strcpy(errmsg, errhd);
1212             for (idp = msgblk.recipients; idp; idp = idp->next)
1213                 if (idp->val.status.mark == XMIT_RCPTBAD)
1214                 {
1215                     strcat(errmsg, idp->id);
1216                     if (idp->next)
1217                         strcat(errmsg, ", ");
1218                 }
1219
1220         }
1221
1222         strcat(errmsg, "\r\n");
1223
1224         /* ship out the error line */
1225         stuffline(ctl, errmsg);
1226     }
1227
1228     /* issue the delimiter line */
1229     cp = buf;
1230     *cp++ = '\r';
1231     *cp++ = '\n';
1232     *cp++ = '\0';
1233     stuffline(ctl, buf);
1234
1235 /*    free(msgblk.headers); */
1236     free_str_list(&msgblk.recipients);
1237     return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1238 }
1239
1240 int readbody(int sock, struct query *ctl, flag forward, int len)
1241 /* read and dispose of a message body presented on sock */
1242 /*   ctl:               query control record */
1243 /*   sock:              to which the server is connected */
1244 /*   len:               length of message */
1245 /*   forward:           TRUE to forward */
1246 {
1247     int linelen;
1248     unsigned char buf[MSGBUFSIZE+4];
1249     unsigned char *inbufp = buf;
1250     flag issoftline = FALSE;
1251
1252     /*
1253      * Pass through the text lines in the body.
1254      *
1255      * Yes, this wants to be ||, not &&.  The problem is that in the most
1256      * important delimited protocol, POP3, the length is not reliable.
1257      * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1258      * So, for delimited protocols we need to ignore the length here and
1259      * instead drop out of the loop with a break statement when we see
1260      * the message delimiter.
1261      */
1262     while (protocol->delimited || len > 0)
1263     {
1264         set_timeout(mytimeout);
1265         if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1266         {
1267             set_timeout(0);
1268             release_sink(ctl);
1269             return(PS_SOCKET);
1270         }
1271         set_timeout(0);
1272
1273         /* write the message size dots */
1274         if (linelen > 0)
1275         {
1276             sizeticker += linelen;
1277             while (sizeticker >= SIZETICKER)
1278             {
1279                 if (outlevel > O_SILENT && (((run.poll_interval == 0 || nodetach) && !isafile(1)) || run.showdots))
1280                 {
1281                     fputc('.', stdout);
1282                     fflush(stdout);
1283                 }
1284                 sizeticker -= SIZETICKER;
1285             }
1286         }
1287         len -= linelen;
1288
1289         /* check for end of message */
1290         if (protocol->delimited && *inbufp == '.')
1291         {
1292             if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1293                 break;
1294             else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1295                 break;
1296             else
1297                 msgblk.msglen--;        /* subtract the size of the dot escape */
1298         }
1299
1300         msgblk.msglen += linelen;
1301
1302         if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1303             issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1304             if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1305             {
1306                 /*
1307                  * Soft linebreak, but less than 200 bytes left in
1308                  * input buffer. Rather than doing a buffer overrun,
1309                  * ignore the soft linebreak, NL-terminate data and
1310                  * deliver what we have now.
1311                  * (Who writes lines longer than 2K anyway?)
1312                  */
1313                 *inbufp = '\n'; *(inbufp+1) = '\0';
1314                 issoftline = 0;
1315             }
1316         }
1317
1318         /* ship out the text line */
1319         if (forward && (!issoftline))
1320         {
1321             int n;
1322             inbufp = buf;
1323
1324             /* guard against very long lines */
1325             buf[MSGBUFSIZE+1] = '\r';
1326             buf[MSGBUFSIZE+2] = '\n';
1327             buf[MSGBUFSIZE+3] = '\0';
1328
1329             n = stuffline(ctl, buf);
1330
1331             if (n < 0)
1332             {
1333                 report(stdout, GT_("writing message text\n"));
1334                 release_sink(ctl);
1335                 return(PS_IOERR);
1336             }
1337             else if (outlevel >= O_VERBOSE && !isafile(1))
1338             {
1339                 fputc('*', stdout);
1340                 fflush(stdout);
1341             }
1342         }
1343     }
1344
1345     return(PS_SUCCESS);
1346 }
1347
1348 void init_transact(const struct method *proto)
1349 /* initialize state for the send and receive functions */
1350 {
1351     tagnum = 0;
1352     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1353     protocol = (struct method *)proto;
1354 }
1355
1356 static void enshroud(char *buf)
1357 /* shroud a password in the given buffer */
1358 {
1359     char *cp;
1360
1361     if (shroud[0] && (cp = strstr(buf, shroud)))
1362     {
1363        char    *sp;
1364
1365        sp = cp + strlen(shroud);
1366        *cp = '*';
1367        while (*sp)
1368            *cp++ = *sp++;
1369        *cp = '\0';
1370     }
1371 }
1372
1373 #if defined(HAVE_STDARG_H)
1374 void gen_send(int sock, const char *fmt, ... )
1375 #else
1376 void gen_send(sock, fmt, va_alist)
1377 int sock;               /* socket to which server is connected */
1378 const char *fmt;        /* printf-style format */
1379 va_dcl
1380 #endif
1381 /* assemble command in printf(3) style and send to the server */
1382 {
1383     char buf [MSGBUFSIZE+1];
1384     va_list ap;
1385
1386     if (protocol->tagged && !suppress_tags)
1387         (void) sprintf(buf, "%s ", GENSYM);
1388     else
1389         buf[0] = '\0';
1390
1391 #if defined(HAVE_STDARG_H)
1392     va_start(ap, fmt);
1393 #else
1394     va_start(ap);
1395 #endif
1396 #ifdef HAVE_VSNPRINTF
1397     vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1398 #else
1399     vsprintf(buf + strlen(buf), fmt, ap);
1400 #endif
1401     va_end(ap);
1402
1403 #ifdef HAVE_SNPRINTF
1404     snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1405 #else
1406     strcat(buf, "\r\n");
1407 #endif /* HAVE_SNPRINTF */
1408     SockWrite(sock, buf, strlen(buf));
1409
1410     if (outlevel >= O_MONITOR)
1411     {
1412         enshroud(buf);
1413         buf[strlen(buf)-2] = '\0';
1414         report(stdout, "%s> %s\n", protocol->name, buf);
1415     }
1416 }
1417
1418 int gen_recv(sock, buf, size)
1419 /* get one line of input from the server */
1420 int sock;       /* socket to which server is connected */
1421 char *buf;      /* buffer to receive input */
1422 int size;       /* length of buffer */
1423 {
1424     int oldphase = phase;       /* we don't have to be re-entrant */
1425
1426     phase = SERVER_WAIT;
1427     set_timeout(mytimeout);
1428     if (SockRead(sock, buf, size) == -1)
1429     {
1430         set_timeout(0);
1431         phase = oldphase;
1432         return(PS_SOCKET);
1433     }
1434     else
1435     {
1436         set_timeout(0);
1437         if (buf[strlen(buf)-1] == '\n')
1438             buf[strlen(buf)-1] = '\0';
1439         if (buf[strlen(buf)-1] == '\r')
1440             buf[strlen(buf)-1] = '\0';
1441         if (outlevel >= O_MONITOR)
1442             report(stdout, "%s< %s\n", protocol->name, buf);
1443         phase = oldphase;
1444         return(PS_SUCCESS);
1445     }
1446 }
1447
1448 #if defined(HAVE_STDARG_H)
1449 int gen_transact(int sock, const char *fmt, ... )
1450 #else
1451 int gen_transact(int sock, fmt, va_alist)
1452 int sock;               /* socket to which server is connected */
1453 const char *fmt;        /* printf-style format */
1454 va_dcl
1455 #endif
1456 /* assemble command in printf(3) style, send to server, accept a response */
1457 {
1458     int ok;
1459     char buf [MSGBUFSIZE+1];
1460     va_list ap;
1461     int oldphase = phase;       /* we don't have to be re-entrant */
1462
1463     phase = SERVER_WAIT;
1464
1465     if (protocol->tagged && !suppress_tags)
1466         (void) sprintf(buf, "%s ", GENSYM);
1467     else
1468         buf[0] = '\0';
1469
1470 #if defined(HAVE_STDARG_H)
1471     va_start(ap, fmt) ;
1472 #else
1473     va_start(ap);
1474 #endif
1475 #ifdef HAVE_VSNPRINTF
1476     vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1477 #else
1478     vsprintf(buf + strlen(buf), fmt, ap);
1479 #endif
1480     va_end(ap);
1481
1482 #ifdef HAVE_SNPRINTF
1483     snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1484 #else
1485     strcat(buf, "\r\n");
1486 #endif /* HAVE_SNPRINTF */
1487     SockWrite(sock, buf, strlen(buf));
1488
1489     if (outlevel >= O_MONITOR)
1490     {
1491         enshroud(buf);
1492         buf[strlen(buf)-2] = '\0';
1493         report(stdout, "%s> %s\n", protocol->name, buf);
1494     }
1495
1496     /* we presume this does its own response echoing */
1497     ok = (protocol->parse_response)(sock, buf);
1498
1499     phase = oldphase;
1500     return(ok);
1501 }
1502
1503 /* transact.c ends here */