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