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