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