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