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