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