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