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