]> Pileus Git - ~andy/fetchmail/blob - transact.c
Free fix to re-enable some text in error messages.
[~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     free_str_list(&msgblk.recipients);
392
393     /* initially, no message ID */
394     if (ctl->thisid)
395         free(ctl->thisid);
396     ctl->thisid = NULL;
397
398     msgblk.headers = received_for = delivered_to = NULL;
399     from_offs = reply_to_offs = resent_from_offs = app_from_offs = 
400         sender_offs = resent_sender_offs = env_offs = -1;
401     oldlen = 0;
402     msgblk.msglen = 0;
403     skipcount = 0;
404     ctl->mimemsg = 0;
405
406     for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
407     {
408         char *line;
409         int overlong = FALSE;
410
411         line = xmalloc(sizeof(buf));
412         linelen = 0;
413         line[0] = '\0';
414         do {
415             set_timeout(mytimeout);
416             if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
417                 set_timeout(0);
418                 free(line);
419                 free(msgblk.headers);
420                 msgblk.headers = NULL;
421                 return(PS_SOCKET);
422             }
423             set_timeout(0);
424             linelen += n;
425             msgblk.msglen += n;
426
427                 /*
428                  * Try to gracefully handle the case, where the length of a
429                  * line exceeds MSGBUFSIZE.
430                  */
431                 if ( n && buf[n-1] != '\n' ) {
432                         unsigned int llen = strlen(line);
433                         overlong = TRUE;
434                         line = realloc(line, llen + n + 1);
435                         strcpy(line + llen, buf);
436                         ch = ' '; /* So the next iteration starts */
437                         continue;
438                 }
439
440             /* lines may not be properly CRLF terminated; fix this for qmail */
441             if (ctl->forcecr)
442             {
443                 cp = buf + strlen(buf) - 1;
444                 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
445                 {
446                     *cp++ = '\r';
447                     *cp++ = '\n';
448                     *cp++ = '\0';
449                 }
450             }
451
452                 /*
453                  * Decode MIME encoded headers. We MUST do this before
454                  * looking at the Content-Type / Content-Transfer-Encoding
455                  * headers (RFC 2046).
456                  */
457                 if ( ctl->mimedecode && overlong ) {
458                         /*
459                          * If we received an overlong line, we have to decode the
460                          * whole line at once.
461                          */
462                         line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
463                         strcat(line, buf);
464                         UnMimeHeader(line);
465                 }
466                 else {
467                         if ( ctl->mimedecode )
468                                 UnMimeHeader(buf);
469
470                         line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
471                         strcat(line, buf);
472                 }
473
474             /* check for end of headers */
475             if (EMPTYLINE(line))
476             {
477                 headers_ok = TRUE;
478                 has_nuls = (linelen != strlen(line));
479                 free(line);
480                 goto process_headers;
481             }
482
483             /*
484              * Check for end of message immediately.  If one of your folders
485              * has been mangled, the delimiter may occur directly after the
486              * header.
487              */
488             if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
489             {
490                 headers_ok = FALSE;
491                 has_nuls = (linelen != strlen(line));
492                 free(line);
493                 goto process_headers;
494             }
495
496             /*
497              * At least one brain-dead website (netmind.com) is known to
498              * send out robotmail that's missing the RFC822 delimiter blank
499              * line before the body! Without this check fetchmail segfaults.
500              * With it, we treat such messages as though they had the missing
501              * blank line.
502              */
503             if (!isspace(line[0]) && !strchr(line, ':'))
504             {
505                 headers_ok = FALSE;
506                 has_nuls = (linelen != strlen(line));
507                 free(line);
508                 goto process_headers;
509             }
510
511             /* check for RFC822 continuations */
512             set_timeout(mytimeout);
513             ch = SockPeek(sock);
514             set_timeout(0);
515         } while
516             (ch == ' ' || ch == '\t');  /* continuation to next line? */
517
518         /* write the message size dots */
519         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
520         {
521             sizeticker += linelen;
522             while (sizeticker >= SIZETICKER)
523             {
524                 if ((!run.use_syslog && !isafile(1)) || run.showdots)
525                 {
526                     fputc('.', stdout);
527                     fflush(stdout);
528                 }
529                 sizeticker -= SIZETICKER;
530             }
531         }
532
533         /* we see an ordinary (non-header, non-message-delimiter line */
534         has_nuls = (linelen != strlen(line));
535
536         /* save the message's ID, we may use it for killing duplicates later */
537         if (MULTIDROP(ctl) && !strncasecmp(line, "Message-ID:", 11))
538             ctl->thisid = xstrdup(line);
539
540         /*
541          * The University of Washington IMAP server (the reference
542          * implementation of IMAP4 written by Mark Crispin) relies
543          * on being able to keep base-UID information in a special
544          * message at the head of the mailbox.  This message should
545          * neither be deleted nor forwarded.
546          */
547 #ifdef POP2_ENABLE
548         /*
549          * We disable this check under POP2 because there's no way to
550          * prevent deletion of the message.  So at least we ought to 
551          * forward it to the user so he or she will have some clue
552          * that things have gone awry.
553          */
554 #if INET6_ENABLE
555         if (strncmp(protocol->service, "pop2", 4))
556 #else /* INET6_ENABLE */
557         if (protocol->port != 109)
558 #endif /* INET6_ENABLE */
559 #endif /* POP2_ENABLE */
560             if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
561                 free(line);
562                 free(msgblk.headers);
563                 msgblk.headers = NULL;
564                 return(PS_RETAINED);
565             }
566
567         /*
568          * This code prevents fetchmail from becoming an accessory after
569          * the fact to upstream sendmails with the `E' option on.  It also
570          * copes with certain brain-dead POP servers (like NT's) that pass
571          * through Unix from_ lines.
572          *
573          * Either of these bugs can result in a non-RFC822 line at the
574          * beginning of the headers.  If fetchmail just passes it
575          * through, the client listener may think the message has *no*
576          * headers (since the first) line it sees doesn't look
577          * RFC822-conformant) and fake up a set.
578          *
579          * What the user would see in this case is bogus (synthesized)
580          * headers, followed by a blank line, followed by the >From, 
581          * followed by the real headers, followed by a blank line,
582          * followed by text.
583          *
584          * We forestall this lossage by tossing anything that looks
585          * like an escaped or passed-through From_ line in headers.
586          * These aren't RFC822 so our conscience is clear...
587          */
588         if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
589         {
590             free(line);
591             continue;
592         }
593
594         /*
595          * We remove all Delivered-To: headers.
596          * 
597          * This is to avoid false mail loops messages when delivering
598          * local messages to and from a Postfix/qmail mailserver. 
599          */
600         if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13)) 
601         {
602             if (delivered_to)
603                 free(line);
604             else 
605                 delivered_to = line;
606             continue;
607         }
608
609         /*
610          * If we see a Status line, it may have been inserted by an MUA
611          * on the mail host, or it may have been inserted by the server
612          * program after the headers in the transaction stream.  This
613          * can actually hose some new-mail notifiers such as xbuffy,
614          * which assumes any Status line came from a *local* MDA and
615          * therefore indicates that the message has been seen.
616          *
617          * Some buggy POP servers (including at least the 3.3(20)
618          * version of the one distributed with IMAP) insert empty
619          * Status lines in the transaction stream; we'll chuck those
620          * unconditionally.  Nonempty ones get chucked if the user
621          * turns on the dropstatus flag.
622          */
623         {
624             char        *cp;
625
626             if (!strncasecmp(line, "Status:", 7))
627                 cp = line + 7;
628             else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
629                 cp = line + 17;
630             else
631                 cp = NULL;
632             if (cp) {
633                 while (*cp && isspace(*cp)) cp++;
634                 if (!*cp || ctl->dropstatus)
635                 {
636                     free(line);
637                     continue;
638                 }
639             }
640         }
641
642         if (ctl->rewrite)
643             line = reply_hack(line, ctl->server.truename);
644
645         /*
646          * OK, this is messy.  If we're forwarding by SMTP, it's the
647          * SMTP-receiver's job (according to RFC821, page 22, section
648          * 4.1.1) to generate a Return-Path line on final delivery.
649          * The trouble is, we've already got one because the
650          * mailserver's SMTP thought *it* was responsible for final
651          * delivery.
652          *
653          * Stash away the contents of Return-Path (as modified by reply_hack)
654          * for use in generating MAIL FROM later on, then prevent the header
655          * from being saved with the others.  In effect, we strip it off here.
656          *
657          * If the SMTP server conforms to the standards, and fetchmail gets the
658          * envelope sender from the Return-Path, the new Return-Path should be
659          * exactly the same as the original one.
660          *
661          * We do *not* want to ignore empty Return-Path headers.  These should
662          * be passed through as a way of indicating that a message should
663          * not trigger bounces if delivery fails.  What we *do* need to do is
664          * make sure we never try to rewrite such a blank Return-Path.  We
665          * handle this with a check for <> in the rewrite logic above.
666          */
667         if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
668         {
669             strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
670             msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
671             if (!ctl->mda) {
672                 free(line);
673                 continue;
674             }
675         }
676
677         if (!msgblk.headers)
678         {
679             oldlen = strlen(line);
680             msgblk.headers = xmalloc(oldlen + 1);
681             (void) strcpy(msgblk.headers, line);
682             free(line);
683             line = msgblk.headers;
684         }
685         else
686         {
687             char *newhdrs;
688             int newlen;
689
690             newlen = oldlen + strlen(line);
691             newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
692             if (newhdrs == NULL) {
693                 free(line);
694                 return(PS_IOERR);
695             }
696             msgblk.headers = newhdrs;
697             strcpy(msgblk.headers + oldlen, line);
698             free(line);
699             line = msgblk.headers + oldlen;
700             oldlen = newlen;
701         }
702
703         /* find offsets of various special headers */
704         if (!strncasecmp("From:", line, 5))
705             from_offs = (line - msgblk.headers);
706         else if (!strncasecmp("Reply-To:", line, 9))
707             reply_to_offs = (line - msgblk.headers);
708         else if (!strncasecmp("Resent-From:", line, 12))
709             resent_from_offs = (line - msgblk.headers);
710         else if (!strncasecmp("Apparently-From:", line, 16))
711             app_from_offs = (line - msgblk.headers);
712         /*
713          * Netscape 4.7 puts "Sender: zap" in mail headers.  Perverse...
714          *
715          * But a literal reading of RFC822 sec. 4.4.2 supports the idea
716          * that Sender: *doesn't* have to be a working email address.
717          *
718          * The definition of the Sender header in RFC822 says, in
719          * part, "The Sender mailbox specification includes a word
720          * sequence which must correspond to a specific agent (i.e., a
721          * human user or a computer program) rather than a standard
722          * address."  That implies that the contents of the Sender
723          * field don't need to be a legal email address at all So
724          * ignore any Sender or Resent-Semnder lines unless they
725          * contain @.
726          *
727          * (RFC2822 says the condents of Sender must be a valid mailbox
728          * address, which is also what RFC822 4.4.4 implies.)
729          */
730         else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
731             sender_offs = (line - msgblk.headers);
732         else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
733             resent_sender_offs = (line - msgblk.headers);
734
735 #ifdef __UNUSED__
736         else if (!strncasecmp("Message-Id:", line, 11))
737         {
738             if (ctl->server.uidl)
739             {
740                 char id[IDLEN+1];
741
742                 line[IDLEN+12] = 0;             /* prevent stack overflow */
743                 sscanf(line+12, "%s", id);
744                 if (!str_find( &ctl->newsaved, num))
745                 {
746                     struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
747                     new->val.status.num = num;
748                 }
749             }
750         }
751 #endif /* __UNUSED__ */
752
753         /* if multidrop is on, gather addressee headers */
754         if (MULTIDROP(ctl))
755         {
756             if (!strncasecmp("To:", line, 3)
757                 || !strncasecmp("Cc:", line, 3)
758                 || !strncasecmp("Bcc:", line, 4)
759                 || !strncasecmp("Apparently-To:", line, 14))
760             {
761                 *to_chainptr = xmalloc(sizeof(struct addrblk));
762                 (*to_chainptr)->offset = (line - msgblk.headers);
763                 to_chainptr = &(*to_chainptr)->next; 
764                 *to_chainptr = NULL;
765             }
766
767             else if (!strncasecmp("Resent-To:", line, 10)
768                      || !strncasecmp("Resent-Cc:", line, 10)
769                      || !strncasecmp("Resent-Bcc:", line, 11))
770             {
771                 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
772                 (*resent_to_chainptr)->offset = (line - msgblk.headers);
773                 resent_to_chainptr = &(*resent_to_chainptr)->next; 
774                 *resent_to_chainptr = NULL;
775             }
776
777             else if (ctl->server.envelope != STRING_DISABLED)
778             {
779                 if (ctl->server.envelope 
780                     && strcasecmp(ctl->server.envelope, "Received"))
781                 {
782                     if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
783                                                        line,
784                                                        strlen(ctl->server.envelope)))
785                     {                           
786                         if (skipcount++ < ctl->server.envskip)
787                             continue;
788                         env_offs = (line - msgblk.headers);
789                     }    
790                 }
791                 else if (!received_for && !strncasecmp("Received:", line, 9))
792                 {
793                     if (skipcount++ < ctl->server.envskip)
794                         continue;
795                     received_for = parse_received(ctl, line);
796                 }
797             }
798         }
799     }
800
801  process_headers:    
802     /*
803      * When mail delivered to a multidrop mailbox on the server is
804      * addressed to multiple people on the client machine, there will
805      * be one copy left in the box for each recipient.  This is not a
806      * problem if we have the actual recipient address to dispatch on
807      * (e.g. because we've mined it out of sendmail trace headers, or
808      * a qmail Delivered-To line, or a declared sender envelope line).
809      *
810      * But if we're mining addressees out of the To/Cc/Bcc fields, and
811      * if the mail is addressed to N people, each recipient will
812      * get N copies.  This is bad when N > 1.
813      *
814      * Foil this by suppressing all but one copy of a message with
815      * a given Message-ID.  The accept_count test ensures that
816      * multiple pieces of email with the same Message-ID, each
817      * with a *single* addressee (the N == 1 case), won't be 
818      * suppressed.
819      *
820      * Note: This implementation only catches runs of successive
821      * messages with the same ID, but that should be good
822      * enough. A more general implementation would have to store
823      * ever-growing lists of seen message-IDs; in a long-running
824      * daemon this would turn into a memory leak even if the 
825      * implementation were perfect.
826      * 
827      * Don't mess with this code casually.  It would be way too easy
828      * to break it in a way that blackholed mail.  Better to pass
829      * the occasional duplicate than to do that...
830      */
831     if (!received_for && env_offs == -1 && !delivered_to)
832     {
833         if (ctl->lastid && ctl->thisid && !strcasecmp(ctl->lastid, ctl->thisid))
834         {
835             if (accept_count > 1)
836                 return(PS_REFUSED);
837         }
838         else
839         {
840             if (ctl->lastid)
841                 free(ctl->lastid);
842             ctl->lastid = ctl->thisid;
843             ctl->thisid = NULL;
844         }
845     }
846
847     /*
848      * We want to detect this early in case there are so few headers that the
849      * dispatch logic barfs.
850      */
851     if (!headers_ok)
852     {
853         if (outlevel > O_SILENT)
854             report(stdout,
855                    GT_("message delimiter found while scanning headers\n"));
856     }
857
858     /*
859      * Hack time.  If the first line of the message was blank, with no headers
860      * (this happens occasionally due to bad gatewaying software) cons up
861      * a set of fake headers.  
862      *
863      * If you modify the fake header template below, be sure you don't
864      * make either From or To address @-less, otherwise the reply_hack
865      * logic will do bad things.
866      */
867     if (msgblk.headers == (char *)NULL)
868     {
869 #ifdef HAVE_SNPRINTF
870         snprintf(buf, sizeof(buf),
871 #else
872         sprintf(buf, 
873 #endif /* HAVE_SNPRINTF */
874         "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
875                 user, fetchmailhost, ctl->remotename, ctl->server.truename);
876         msgblk.headers = xstrdup(buf);
877     }
878
879     /*
880      * We can now process message headers before reading the text.
881      * In fact we have to, as this will tell us where to forward to.
882      */
883
884     /* Check for MIME headers indicating possible 8-bit data */
885     ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
886
887 #ifdef SDPS_ENABLE
888     if (ctl->server.sdps && sdps_envfrom)
889     {
890         /* We have the real envelope return-path, stored out of band by
891          * SDPS - that's more accurate than any header is going to be.
892          */
893         strcpy(msgblk.return_path, sdps_envfrom);
894         free(sdps_envfrom);
895     } else
896 #endif /* SDPS_ENABLE */
897     /*
898      * If there is a Return-Path address on the message, this was
899      * almost certainly the MAIL FROM address given the originating
900      * sendmail.  This is the best thing to use for logging the
901      * message origin (it sets up the right behavior for bounces and
902      * mailing lists).  Otherwise, fall down to the next available 
903      * envelope address (which is the most probable real sender).
904      * *** The order is important! ***
905      * This is especially useful when receiving mailing list
906      * messages in multidrop mode.  if a local address doesn't
907      * exist, the bounce message won't be returned blindly to the 
908      * author or to the list itself but rather to the list manager
909      * (ex: specified by "Sender:") which is much less annoying.  This 
910      * is true for most mailing list packages.
911      */
912     if( !msgblk.return_path[0] ){
913         char *ap = NULL;
914         if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
915         else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
916         else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
917         else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
918         else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
919         else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
920         /* multi-line MAIL FROM addresses confuse SMTP terribly */
921         if (ap && !strchr(ap, '\n')) {
922             strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
923             msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
924         }
925     }
926
927     /* cons up a list of local recipients */
928     msgblk.recipients = (struct idlist *)NULL;
929     accept_count = reject_count = 0;
930     /* is this a multidrop box? */
931     if (MULTIDROP(ctl))
932     {
933 #ifdef SDPS_ENABLE
934         if (ctl->server.sdps && sdps_envto)
935         {
936             /* We have the real envelope recipient, stored out of band by
937              * SDPS - that's more accurate than any header is going to be.
938              */
939             find_server_names(sdps_envto, ctl, &msgblk.recipients);
940             free(sdps_envto);
941         } else
942 #endif /* SDPS_ENABLE */ 
943         if (env_offs > -1)          /* We have the actual envelope addressee */
944             find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
945         else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
946       ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
947    {
948             find_server_names(delivered_to, ctl, &msgblk.recipients);
949        free(delivered_to);
950    }
951         else if (received_for)
952             /*
953              * We have the Received for addressee.  
954              * It has to be a mailserver address, or we
955              * wouldn't have got here.
956              * We use find_server_names() to let local 
957              * hostnames go through.
958              */
959             find_server_names(received_for, ctl, &msgblk.recipients);
960         else
961         {
962             /*
963              * We haven't extracted the envelope address.
964              * So check all the "Resent-To" header addresses if 
965              * they exist.  If and only if they don't, consider
966              * the "To" addresses.
967              */
968             register struct addrblk *nextptr;
969             if (resent_to_addrchain) {
970                 /* delete the "To" chain and substitute it 
971                  * with the "Resent-To" list 
972                  */
973                 while (to_addrchain) {
974                     nextptr = to_addrchain->next;
975                     free(to_addrchain);
976                     to_addrchain = nextptr;
977                 }
978                 to_addrchain = resent_to_addrchain;
979                 resent_to_addrchain = NULL;
980             }
981             /* now look for remaining adresses */
982             while (to_addrchain) {
983                 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
984                 nextptr = to_addrchain->next;
985                 free(to_addrchain);
986                 to_addrchain = nextptr;
987             }
988         }
989         if (!accept_count)
990         {
991             no_local_matches = TRUE;
992             save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
993             if (outlevel >= O_DEBUG)
994                 report(stdout,
995                       GT_("no local matches, forwarding to %s\n"),
996                       run.postmaster);
997         }
998     }
999     else        /* it's a single-drop box, use first localname */
1000         save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1001
1002
1003     /*
1004      * Time to either address the message or decide we can't deliver it yet.
1005      */
1006     if (ctl->errcount > olderrs)        /* there were DNS errors above */
1007     {
1008         if (outlevel >= O_DEBUG)
1009             report(stdout,
1010                    GT_("forwarding and deletion suppressed due to DNS errors\n"));
1011         free(msgblk.headers);
1012         msgblk.headers = NULL;
1013         free_str_list(&msgblk.recipients);
1014         return(PS_TRANSIENT);
1015     }
1016     else
1017     {
1018         /* set up stuffline() so we can deliver the message body through it */ 
1019         if ((n = open_sink(ctl, &msgblk,
1020                            &good_addresses, &bad_addresses)) != PS_SUCCESS)
1021         {
1022             free(msgblk.headers);
1023             msgblk.headers = NULL;
1024             free_str_list(&msgblk.recipients);
1025             return(n);
1026         }
1027     }
1028
1029     n = 0;
1030     /*
1031      * Some server/sendmail combinations cause problems when our
1032      * synthetic Received line is before the From header.  Cope
1033      * with this...
1034      */
1035     if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1036         rcv = msgblk.headers;
1037     /* handle ">Received:" lines too */
1038     while (rcv > msgblk.headers && rcv[-1] != '\n')
1039         rcv--;
1040     if (rcv > msgblk.headers)
1041     {
1042         char    c = *rcv;
1043
1044         *rcv = '\0';
1045         n = stuffline(ctl, msgblk.headers);
1046         *rcv = c;
1047     }
1048     if (!run.invisible && n != -1)
1049     {
1050         /* utter any per-message Received information we need here */
1051         if (ctl->server.trueaddr) {
1052 #ifdef HAVE_SNPRINTF
1053             snprintf(buf, sizeof(buf),
1054 #else
1055             sprintf(buf, 
1056 #endif /* HAVE_SNPRINTF */
1057                     "Received: from %s [%u.%u.%u.%u]\r\n", 
1058                     ctl->server.truename,
1059                     (unsigned char)ctl->server.trueaddr[0],
1060                     (unsigned char)ctl->server.trueaddr[1],
1061                     (unsigned char)ctl->server.trueaddr[2],
1062                     (unsigned char)ctl->server.trueaddr[3]);
1063         } else {
1064 #ifdef HAVE_SNPRINTF
1065           snprintf(buf, sizeof(buf),
1066 #else                       
1067           sprintf(buf,
1068 #endif /* HAVE_SNPRINTF */
1069                   "Received: from %s\r\n", ctl->server.truename);
1070         }
1071         n = stuffline(ctl, buf);
1072         if (n != -1)
1073         {
1074             /*
1075              * This header is technically invalid under RFC822.
1076              * POP3, IMAP, etc. are not legal mail-parameter values.
1077              */
1078 #ifdef HAVE_SNPRINTF
1079             snprintf(buf, sizeof(buf),
1080 #else
1081             sprintf(buf,
1082 #endif /* HAVE_SNPRINTF */
1083                     "\tby %s with %s (fetchmail-%s",
1084                     fetchmailhost,
1085                     protocol->name,
1086                     VERSION);
1087             if (ctl->tracepolls)
1088             {
1089                 sprintf(buf + strlen(buf), " polling %s account %s",
1090                         ctl->server.pollname, 
1091                         ctl->remotename);
1092             }
1093 #ifdef HAVE_SNPRINTF
1094             snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1095 #else
1096             strcat(buf, ")\r\n");
1097 #endif /* HAVE_SNPRINTF */
1098             n = stuffline(ctl, buf);
1099             if (n != -1)
1100             {
1101                 buf[0] = '\t';
1102                 if (good_addresses == 0)
1103                 {
1104 #ifdef HAVE_SNPRINTF
1105                     snprintf(buf+1, sizeof(buf)-1,
1106 #else
1107                     sprintf(buf+1,
1108 #endif /* HAVE_SNPRINTF */
1109                             "for %s (by default); ",
1110                             rcpt_address (ctl, run.postmaster, 0));
1111                 }
1112                 else if (good_addresses == 1)
1113                 {
1114                     for (idp = msgblk.recipients; idp; idp = idp->next)
1115                         if (idp->val.status.mark == XMIT_ACCEPT)
1116                             break;      /* only report first address */
1117 #ifdef HAVE_SNPRINTF
1118                     snprintf(buf+1, sizeof(buf)-1,
1119 #else                       
1120                     sprintf(buf+1,
1121 #endif /* HAVE_SNPRINTF */
1122                             "for %s", rcpt_address (ctl, idp->id, 1));
1123                     sprintf(buf+strlen(buf), " (%s); ",
1124                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1125                 }
1126                 else
1127                     buf[1] = '\0';
1128
1129 #ifdef HAVE_SNPRINTF
1130                 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1131                         rfc822timestamp());
1132 #else
1133                 strcat(buf, rfc822timestamp());
1134                 strcat(buf, "\r\n");
1135 #endif /* HAVE_SNPRINTF */
1136                 n = stuffline(ctl, buf);
1137             }
1138         }
1139     }
1140
1141     if (n != -1)
1142         n = stuffline(ctl, rcv);        /* ship out rest of msgblk.headers */
1143
1144     if (n == -1)
1145     {
1146         report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1147         release_sink(ctl);
1148         free(msgblk.headers);
1149         msgblk.headers = NULL;
1150         free_str_list(&msgblk.recipients);
1151         return(PS_IOERR);
1152     }
1153     else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !isafile(2))
1154         fputs("#", stdout);
1155
1156     /* write error notifications */
1157     if (no_local_matches || has_nuls || bad_addresses)
1158     {
1159         int     errlen = 0;
1160         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1161
1162         errmsg = errhd;
1163         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1164         if (no_local_matches)
1165         {
1166             if (reject_count != 1)
1167                 strcat(errhd, GT_("no recipient addresses matched declared local names"));
1168             else
1169             {
1170                 for (idp = msgblk.recipients; idp; idp = idp->next)
1171                     if (idp->val.status.mark == XMIT_REJECT)
1172                         break;
1173 #ifdef HAVE_SNPRINTF
1174                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1175 #else
1176                 sprintf(errhd+strlen(errhd),
1177 #endif /* HAVE_SNPRINTF */
1178                         GT_("recipient address %s didn't match any local name"), idp->id);
1179             }
1180         }
1181
1182         if (has_nuls)
1183         {
1184             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1185 #ifdef HAVE_SNPRINTF
1186                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1187             snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1188 #else
1189                 strcat(errhd, "; ");
1190             strcat(errhd,
1191 #endif /* HAVE_SNPRINTF */
1192                         GT_("message has embedded NULs"));
1193         }
1194
1195         if (bad_addresses)
1196         {
1197             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1198 #ifdef HAVE_SNPRINTF
1199                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1200             snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1201 #else
1202                 strcat(errhd, "; ");
1203             strcat(errhd,
1204 #endif /* HAVE_SNPRINTF */
1205                         GT_("SMTP listener rejected local recipient addresses: "));
1206             errlen = strlen(errhd);
1207             for (idp = msgblk.recipients; idp; idp = idp->next)
1208                 if (idp->val.status.mark == XMIT_RCPTBAD)
1209                     errlen += strlen(idp->id) + 2;
1210
1211             xalloca(errmsg, char *, errlen+3);
1212             (void) strcpy(errmsg, errhd);
1213             for (idp = msgblk.recipients; idp; idp = idp->next)
1214                 if (idp->val.status.mark == XMIT_RCPTBAD)
1215                 {
1216                     strcat(errmsg, idp->id);
1217                     if (idp->next)
1218                         strcat(errmsg, ", ");
1219                 }
1220
1221         }
1222
1223         strcat(errmsg, "\r\n");
1224
1225         /* ship out the error line */
1226         stuffline(ctl, errmsg);
1227     }
1228
1229     /* issue the delimiter line */
1230     cp = buf;
1231     *cp++ = '\r';
1232     *cp++ = '\n';
1233     *cp++ = '\0';
1234     stuffline(ctl, buf);
1235
1236     return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1237 }
1238
1239 int readbody(int sock, struct query *ctl, flag forward, int len)
1240 /* read and dispose of a message body presented on sock */
1241 /*   ctl:               query control record */
1242 /*   sock:              to which the server is connected */
1243 /*   len:               length of message */
1244 /*   forward:           TRUE to forward */
1245 {
1246     int linelen;
1247     unsigned char buf[MSGBUFSIZE+4];
1248     unsigned char *inbufp = buf;
1249     flag issoftline = FALSE;
1250
1251     /*
1252      * Pass through the text lines in the body.
1253      *
1254      * Yes, this wants to be ||, not &&.  The problem is that in the most
1255      * important delimited protocol, POP3, the length is not reliable.
1256      * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1257      * So, for delimited protocols we need to ignore the length here and
1258      * instead drop out of the loop with a break statement when we see
1259      * the message delimiter.
1260      */
1261     while (protocol->delimited || len > 0)
1262     {
1263         set_timeout(mytimeout);
1264         if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1265         {
1266             set_timeout(0);
1267             release_sink(ctl);
1268             return(PS_SOCKET);
1269         }
1270         set_timeout(0);
1271
1272         /* write the message size dots */
1273         if (linelen > 0)
1274         {
1275             sizeticker += linelen;
1276             while (sizeticker >= SIZETICKER)
1277             {
1278                 if (outlevel > O_SILENT && (((run.poll_interval == 0 || nodetach) && !isafile(1)) || run.showdots))
1279                 {
1280                     fputc('.', stdout);
1281                     fflush(stdout);
1282                 }
1283                 sizeticker -= SIZETICKER;
1284             }
1285         }
1286         len -= linelen;
1287
1288         /* check for end of message */
1289         if (protocol->delimited && *inbufp == '.')
1290         {
1291             if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1292                 break;
1293             else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1294                 break;
1295             else
1296                 msgblk.msglen--;        /* subtract the size of the dot escape */
1297         }
1298
1299         msgblk.msglen += linelen;
1300
1301         if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1302             issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1303             if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1304             {
1305                 /*
1306                  * Soft linebreak, but less than 200 bytes left in
1307                  * input buffer. Rather than doing a buffer overrun,
1308                  * ignore the soft linebreak, NL-terminate data and
1309                  * deliver what we have now.
1310                  * (Who writes lines longer than 2K anyway?)
1311                  */
1312                 *inbufp = '\n'; *(inbufp+1) = '\0';
1313                 issoftline = 0;
1314             }
1315         }
1316
1317         /* ship out the text line */
1318         if (forward && (!issoftline))
1319         {
1320             int n;
1321             inbufp = buf;
1322
1323             /* guard against very long lines */
1324             buf[MSGBUFSIZE+1] = '\r';
1325             buf[MSGBUFSIZE+2] = '\n';
1326             buf[MSGBUFSIZE+3] = '\0';
1327
1328             n = stuffline(ctl, buf);
1329
1330             if (n < 0)
1331             {
1332                 report(stdout, GT_("writing message text\n"));
1333                 release_sink(ctl);
1334                 return(PS_IOERR);
1335             }
1336             else if (outlevel >= O_VERBOSE && !isafile(1))
1337             {
1338                 fputc('*', stdout);
1339                 fflush(stdout);
1340             }
1341         }
1342     }
1343
1344     return(PS_SUCCESS);
1345 }
1346
1347 void init_transact(const struct method *proto)
1348 /* initialize state for the send and receive functions */
1349 {
1350     tagnum = 0;
1351     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1352     protocol = (struct method *)proto;
1353 }
1354
1355 static void enshroud(char *buf)
1356 /* shroud a password in the given buffer */
1357 {
1358     char *cp;
1359
1360     if (shroud[0] && (cp = strstr(buf, shroud)))
1361     {
1362        char    *sp;
1363
1364        sp = cp + strlen(shroud);
1365        *cp = '*';
1366        while (*sp)
1367            *cp++ = *sp++;
1368        *cp = '\0';
1369     }
1370 }
1371
1372 #if defined(HAVE_STDARG_H)
1373 void gen_send(int sock, const char *fmt, ... )
1374 #else
1375 void gen_send(sock, fmt, va_alist)
1376 int sock;               /* socket to which server is connected */
1377 const char *fmt;        /* printf-style format */
1378 va_dcl
1379 #endif
1380 /* assemble command in printf(3) style and send to the server */
1381 {
1382     char buf [MSGBUFSIZE+1];
1383     va_list ap;
1384
1385     if (protocol->tagged && !suppress_tags)
1386         (void) sprintf(buf, "%s ", GENSYM);
1387     else
1388         buf[0] = '\0';
1389
1390 #if defined(HAVE_STDARG_H)
1391     va_start(ap, fmt);
1392 #else
1393     va_start(ap);
1394 #endif
1395 #ifdef HAVE_VSNPRINTF
1396     vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1397 #else
1398     vsprintf(buf + strlen(buf), fmt, ap);
1399 #endif
1400     va_end(ap);
1401
1402 #ifdef HAVE_SNPRINTF
1403     snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1404 #else
1405     strcat(buf, "\r\n");
1406 #endif /* HAVE_SNPRINTF */
1407     SockWrite(sock, buf, strlen(buf));
1408
1409     if (outlevel >= O_MONITOR)
1410     {
1411         enshroud(buf);
1412         buf[strlen(buf)-2] = '\0';
1413         report(stdout, "%s> %s\n", protocol->name, buf);
1414     }
1415 }
1416
1417 int gen_recv(sock, buf, size)
1418 /* get one line of input from the server */
1419 int sock;       /* socket to which server is connected */
1420 char *buf;      /* buffer to receive input */
1421 int size;       /* length of buffer */
1422 {
1423     int oldphase = phase;       /* we don't have to be re-entrant */
1424
1425     phase = SERVER_WAIT;
1426     set_timeout(mytimeout);
1427     if (SockRead(sock, buf, size) == -1)
1428     {
1429         set_timeout(0);
1430         phase = oldphase;
1431         return(PS_SOCKET);
1432     }
1433     else
1434     {
1435         set_timeout(0);
1436         if (buf[strlen(buf)-1] == '\n')
1437             buf[strlen(buf)-1] = '\0';
1438         if (buf[strlen(buf)-1] == '\r')
1439             buf[strlen(buf)-1] = '\0';
1440         if (outlevel >= O_MONITOR)
1441             report(stdout, "%s< %s\n", protocol->name, buf);
1442         phase = oldphase;
1443         return(PS_SUCCESS);
1444     }
1445 }
1446
1447 #if defined(HAVE_STDARG_H)
1448 int gen_transact(int sock, const char *fmt, ... )
1449 #else
1450 int gen_transact(int sock, fmt, va_alist)
1451 int sock;               /* socket to which server is connected */
1452 const char *fmt;        /* printf-style format */
1453 va_dcl
1454 #endif
1455 /* assemble command in printf(3) style, send to server, accept a response */
1456 {
1457     int ok;
1458     char buf [MSGBUFSIZE+1];
1459     va_list ap;
1460     int oldphase = phase;       /* we don't have to be re-entrant */
1461
1462     phase = SERVER_WAIT;
1463
1464     if (protocol->tagged && !suppress_tags)
1465         (void) sprintf(buf, "%s ", GENSYM);
1466     else
1467         buf[0] = '\0';
1468
1469 #if defined(HAVE_STDARG_H)
1470     va_start(ap, fmt) ;
1471 #else
1472     va_start(ap);
1473 #endif
1474 #ifdef HAVE_VSNPRINTF
1475     vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1476 #else
1477     vsprintf(buf + strlen(buf), fmt, ap);
1478 #endif
1479     va_end(ap);
1480
1481 #ifdef HAVE_SNPRINTF
1482     snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1483 #else
1484     strcat(buf, "\r\n");
1485 #endif /* HAVE_SNPRINTF */
1486     SockWrite(sock, buf, strlen(buf));
1487
1488     if (outlevel >= O_MONITOR)
1489     {
1490         enshroud(buf);
1491         buf[strlen(buf)-2] = '\0';
1492         report(stdout, "%s> %s\n", protocol->name, buf);
1493     }
1494
1495     /* we presume this does its own response echoing */
1496     ok = (protocol->parse_response)(sock, buf);
1497
1498     phase = oldphase;
1499     return(ok);
1500 }
1501
1502 /* transact.c ends here */