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