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