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