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