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