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