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