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