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