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