]> Pileus Git - ~andy/fetchmail/blob - transact.c
Fix a few compiler warnings around implicit conversion or extra ";".
[~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 #define EMPTYLINE(s)   (((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0') \
365                        || ((s)[0] == '\n' && (s)[1] == '\0'))
366
367 static int end_of_header (const char *s)
368 /* accept "\r*\n" as EOH in order to be bulletproof against broken survers */
369 {
370     while (s[0] == '\r')
371         s++;
372     return (s[0] == '\n' && s[1] == '\0');
373 }
374
375 int readheaders(int sock,
376                        long fetchlen,
377                        long reallen,
378                        struct query *ctl,
379                        int num,
380                        flag *suppress_readbody)
381 /* read message headers and ship to SMTP or MDA */
382 /*   sock:              to which the server is connected */
383 /*   fetchlen:          length of message according to fetch response */
384 /*   reallen:           length of message according to getsizes */
385 /*   ctl:               query control record */
386 /*   num:               index of message */
387 /*   suppress_readbody: whether call to readbody() should be supressed */
388 {
389     struct addrblk
390     {
391         int             offset;
392         struct addrblk  *next;
393     };
394     struct addrblk      *to_addrchain = NULL;
395     struct addrblk      **to_chainptr = &to_addrchain;
396     struct addrblk      *resent_to_addrchain = NULL;
397     struct addrblk      **resent_to_chainptr = &resent_to_addrchain;
398
399     char                buf[MSGBUFSIZE+1];
400     int                 from_offs, reply_to_offs, resent_from_offs;
401     int                 app_from_offs, sender_offs, resent_sender_offs;
402     int                 env_offs;
403     char                *received_for, *rcv, *cp;
404     static char         *delivered_to = NULL;
405     int                 n, oldlen, ch, remaining, skipcount;
406     size_t              linelen;
407     int                 delivered_to_count;
408     struct idlist       *idp;
409     flag                no_local_matches = FALSE;
410     flag                has_nuls;
411     int                 olderrs, good_addresses, bad_addresses;
412     int                 retain_mail = 0, refuse_mail = 0;
413     flag                already_has_return_path = FALSE;
414
415     sizeticker = 0;
416     has_nuls = FALSE;
417     msgblk.return_path[0] = '\0';
418     olderrs = ctl->errcount;
419
420     /* read message headers */
421     msgblk.reallen = reallen;
422
423     /*
424      * We used to free the header block unconditionally at the end of 
425      * readheaders, but it turns out that if close_sink() hits an error
426      * condition the code for sending bouncemail will actually look
427      * at the freed storage and coredump...
428      */
429     xfree(msgblk.headers);
430     free_str_list(&msgblk.recipients);
431     xfree(delivered_to);
432
433     /* initially, no message digest */
434     memset(ctl->digest, '\0', sizeof(ctl->digest));
435
436     received_for = NULL;
437     from_offs = reply_to_offs = resent_from_offs = app_from_offs = 
438         sender_offs = resent_sender_offs = env_offs = -1;
439     oldlen = 0;
440     msgblk.msglen = 0;
441     skipcount = 0;
442     delivered_to_count = 0;
443     ctl->mimemsg = 0;
444
445     for (remaining = fetchlen; remaining > 0 || protocol->delimited; )
446     {
447         char *line, *rline;
448
449         line = (char *)xmalloc(sizeof(buf));
450         linelen = 0;
451         line[0] = '\0';
452         do {
453             do {
454                 char    *sp, *tp;
455
456                 set_timeout(mytimeout);
457                 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
458                     set_timeout(0);
459                     free(line);
460                     return(PS_SOCKET);
461                 }
462                 set_timeout(0);
463
464                 /*
465                  * Smash out any NULs, they could wreak havoc later on.
466                  * Some network stacks seem to generate these at random,
467                  * especially (according to reports) at the beginning of the
468                  * first read.  NULs are illegal in RFC822 format.
469                  */
470                 for (sp = tp = buf; sp < buf + n; sp++)
471                     if (*sp)
472                         *tp++ = *sp;
473                 *tp = '\0';
474                 n = tp - buf;
475             } while
476                   (n == 0);
477
478             remaining -= n;
479             linelen += n;
480             msgblk.msglen += n;
481
482             /*
483              * Try to gracefully handle the case where the length of a
484              * line exceeds MSGBUFSIZE.
485              */
486             if (n && buf[n-1] != '\n') 
487             {
488                 rline = (char *) realloc(line, linelen + 1);
489                 if (rline == NULL)
490                 {
491                     free (line);
492                     return(PS_IOERR);
493                 }
494                 line = rline;
495                 memcpy(line + linelen - n, buf, n);
496                 line[linelen] = '\0';
497                 ch = ' '; /* So the next iteration starts */
498                 continue;
499             }
500
501             /* lines may not be properly CRLF terminated; fix this for qmail */
502             /* we don't want to overflow the buffer here */
503             if (ctl->forcecr && buf[n-1]=='\n' && (n==1 || buf[n-2]!='\r'))
504             {
505                 char * tcp;
506                 rline = (char *) realloc(line, linelen + 2);
507                 if (rline == NULL)
508                 {
509                     free (line);
510                     return(PS_IOERR);
511                 }
512                 line = rline;
513                 memcpy(line + linelen - n, buf, n - 1);
514                 tcp = line + linelen - 1;
515                 *tcp++ = '\r';
516                 *tcp++ = '\n';
517                 *tcp++ = '\0';
518                 n++;
519                 linelen++;
520             }
521             else
522             {
523                 rline = (char *) realloc(line, linelen + 1);
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             }
532
533             /* check for end of headers */
534             if (end_of_header(line))
535             {
536                 if (linelen != strlen (line))
537                     has_nuls = TRUE;
538                 free(line);
539                 goto process_headers;
540             }
541
542             /*
543              * Check for end of message immediately.  If one of your folders
544              * has been mangled, the delimiter may occur directly after the
545              * header.
546              */
547             if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
548             {
549                 if (outlevel > O_SILENT)
550                     report(stdout,
551                            GT_("message delimiter found while scanning headers\n"));
552                 if (suppress_readbody)
553                     *suppress_readbody = TRUE;
554                 if (linelen != strlen (line))
555                     has_nuls = TRUE;
556                 free(line);
557                 goto process_headers;
558             }
559
560             /*
561              * At least one brain-dead website (netmind.com) is known to
562              * send out robotmail that's missing the RFC822 delimiter blank
563              * line before the body! Without this check fetchmail segfaults.
564              * With it, we treat such messages as spam and refuse them.
565              *
566              * Frederic Marchal reported in February 2006 that hotmail
567              * or something improperly wrapped a very long TO header
568              * (wrapped without inserting whitespace in the continuation
569              * line) and found that this code thus refused a message
570              * that should have been delivered.
571              *
572              * XXX FIXME: we should probably wrap the message up as
573              * message/rfc822 attachment and forward to postmaster (Rob
574              * MacGregor)
575              */
576             if (!refuse_mail && !isspace((unsigned char)line[0]) && !strchr(line, ':'))
577             {
578                 if (linelen != strlen (line))
579                     has_nuls = TRUE;
580                 if (outlevel > O_SILENT)
581                     report(stdout,
582                            GT_("incorrect header line found while scanning headers\n"));
583                 if (outlevel >= O_VERBOSE)
584                     report (stdout, GT_("line: %s"), line);
585                 refuse_mail = 1;
586             }
587
588             /* check for RFC822 continuations */
589             set_timeout(mytimeout);
590             ch = SockPeek(sock);
591             set_timeout(0);
592         } while
593             (ch == ' ' || ch == '\t');  /* continuation to next line? */
594
595         /* write the message size dots */
596         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
597         {
598             sizeticker += linelen;
599             while (sizeticker >= SIZETICKER)
600             {
601                 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
602                 {
603                     fputc('.', stdout);
604                     fflush(stdout);
605                 }
606                 sizeticker -= SIZETICKER;
607             }
608         }
609                 /*
610                  * Decode MIME encoded headers. We MUST do this before
611                  * looking at the Content-Type / Content-Transfer-Encoding
612                  * headers (RFC 2046).
613                  */
614                 if ( ctl->mimedecode )
615                 {
616                     char *tcp;
617                     UnMimeHeader(line);
618                     /* the line is now shorter. So we retrace back till we find our terminating
619                      * combination \n\0, we move backwards to make sure that we don't catch som
620                      * \n\0 stored in the decoded part of the message */
621                     for(tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--);
622                     if(tcp > line) linelen = tcp - line;
623                 }
624
625
626         /* skip processing if we are going to retain or refuse this mail */
627         if (retain_mail || refuse_mail)
628         {
629             free(line);
630             continue;
631         }
632
633         /* we see an ordinary (non-header, non-message-delimiter) line */
634         if (linelen != strlen (line))
635             has_nuls = TRUE;
636
637         /*
638          * The University of Washington IMAP server (the reference
639          * implementation of IMAP4 written by Mark Crispin) relies
640          * on being able to keep base-UID information in a special
641          * message at the head of the mailbox.  This message should
642          * neither be deleted nor forwarded.
643          *
644          * An example for such a message is (keep this in so people
645          * find it when looking where the special code is to handle the
646          * data):
647          *
648          *   From MAILER-DAEMON Wed Nov 23 11:38:42 2005
649          *   Date: 23 Nov 2005 11:38:42 +0100
650          *   From: Mail System Internal Data <MAILER-DAEMON@mail.example.org>
651          *   Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
652          *   Message-ID: <1132742322@mail.example.org>
653          *   X-IMAP: 1132742306 0000000001
654          *   Status: RO
655          *
656          *   This text is part of the internal format of your mail folder, and is not
657          *   a real message.  It is created automatically by the mail system software.
658          *   If deleted, important folder data will be lost, and it will be re-created
659          *   with the data reset to initial values.
660          *
661          * This message is only visible if a POP3 server that is unaware
662          * of these UWIMAP messages is used besides UWIMAP or PINE.
663          *
664          * We will just check if the first message in the mailbox has an
665          * X-IMAP: header.
666          */
667 #ifdef POP2_ENABLE
668         /*
669          * We disable this check under POP2 because there's no way to
670          * prevent deletion of the message.  So at least we ought to
671          * forward it to the user so he or she will have some clue
672          * that things have gone awry.
673          */
674         if (servport("pop2") != servport(protocol->service))
675 #endif /* POP2_ENABLE */
676             if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
677                 free(line);
678                 retain_mail = 1;
679                 continue;
680             }
681
682         /*
683          * This code prevents fetchmail from becoming an accessory after
684          * the fact to upstream sendmails with the `E' option on.  It also
685          * copes with certain brain-dead POP servers (like NT's) that pass
686          * through Unix from_ lines.
687          *
688          * Either of these bugs can result in a non-RFC822 line at the
689          * beginning of the headers.  If fetchmail just passes it
690          * through, the client listener may think the message has *no*
691          * headers (since the first) line it sees doesn't look
692          * RFC822-conformant) and fake up a set.
693          *
694          * What the user would see in this case is bogus (synthesized)
695          * headers, followed by a blank line, followed by the >From, 
696          * followed by the real headers, followed by a blank line,
697          * followed by text.
698          *
699          * We forestall this lossage by tossing anything that looks
700          * like an escaped or passed-through From_ line in headers.
701          * These aren't RFC822 so our conscience is clear...
702          */
703         if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
704         {
705             free(line);
706             continue;
707         }
708
709         /*
710          * We remove all Delivered-To: headers if dropdelivered is set
711          * - special care must be taken if Delivered-To: is also used
712          * as envelope at the same time.
713          *
714          * This is to avoid false mail loops errors when delivering
715          * local messages to and from a Postfix or qmail mailserver.
716          */
717         if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13)) 
718         {
719             if (delivered_to ||
720                 ctl->server.envelope == STRING_DISABLED ||
721                 !ctl->server.envelope ||
722                 strcasecmp(ctl->server.envelope, "Delivered-To") ||
723                 delivered_to_count != ctl->server.envskip)
724                 free(line);
725             else 
726                 delivered_to = line;
727             delivered_to_count++;
728             continue;
729         }
730
731         /*
732          * If we see a Status line, it may have been inserted by an MUA
733          * on the mail host, or it may have been inserted by the server
734          * program after the headers in the transaction stream.  This
735          * can actually hose some new-mail notifiers such as xbuffy,
736          * which assumes any Status line came from a *local* MDA and
737          * therefore indicates that the message has been seen.
738          *
739          * Some buggy POP servers (including at least the 3.3(20)
740          * version of the one distributed with IMAP) insert empty
741          * Status lines in the transaction stream; we'll chuck those
742          * unconditionally.  Nonempty ones get chucked if the user
743          * turns on the dropstatus flag.
744          */
745         {
746             char        *cp;
747
748             if (!strncasecmp(line, "Status:", 7))
749                 cp = line + 7;
750             else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
751                 cp = line + 17;
752             else
753                 cp = NULL;
754             if (cp) {
755                 while (*cp && isspace((unsigned char)*cp)) cp++;
756                 if (!*cp || ctl->dropstatus)
757                 {
758                     free(line);
759                     continue;
760                 }
761             }
762         }
763
764         if (ctl->rewrite)
765             line = reply_hack(line, ctl->server.truename, &linelen);
766
767         /*
768          * OK, this is messy.  If we're forwarding by SMTP, it's the
769          * SMTP-receiver's job (according to RFC821, page 22, section
770          * 4.1.1) to generate a Return-Path line on final delivery.
771          * The trouble is, we've already got one because the
772          * mailserver's SMTP thought *it* was responsible for final
773          * delivery.
774          *
775          * Stash away the contents of Return-Path (as modified by reply_hack)
776          * for use in generating MAIL FROM later on, then prevent the header
777          * from being saved with the others.  In effect, we strip it off here.
778          *
779          * If the SMTP server conforms to the standards, and fetchmail gets the
780          * envelope sender from the Return-Path, the new Return-Path should be
781          * exactly the same as the original one.
782          *
783          * We do *not* want to ignore empty Return-Path headers.  These should
784          * be passed through as a way of indicating that a message should
785          * not trigger bounces if delivery fails.  What we *do* need to do is
786          * make sure we never try to rewrite such a blank Return-Path.  We
787          * handle this with a check for <> in the rewrite logic above.
788          *
789          * Also, if an email has multiple Return-Path: headers, we only
790          * read the first occurance, as some spam email has more than one
791          * Return-Path.
792          *
793          */
794         if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
795         {
796             already_has_return_path = TRUE;
797             if (cp[0]=='\0')    /* nxtaddr() strips the brackets... */
798                 cp="<>";
799             strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
800             msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
801             if (!ctl->mda) {
802                 free(line);
803                 continue;
804             }
805         }
806
807         if (!msgblk.headers)
808         {
809             oldlen = linelen;
810             msgblk.headers = (char *)xmalloc(oldlen + 1);
811             (void) memcpy(msgblk.headers, line, linelen);
812             msgblk.headers[oldlen] = '\0';
813             free(line);
814             line = msgblk.headers;
815         }
816         else
817         {
818             char *newhdrs;
819             int newlen;
820
821             newlen = oldlen + linelen;
822             newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
823             if (newhdrs == NULL) {
824                 free(line);
825                 return(PS_IOERR);
826             }
827             msgblk.headers = newhdrs;
828             memcpy(msgblk.headers + oldlen, line, linelen);
829             msgblk.headers[newlen] = '\0';
830             free(line);
831             line = msgblk.headers + oldlen;
832             oldlen = newlen;
833         }
834
835         /* find offsets of various special headers */
836         if (!strncasecmp("From:", line, 5))
837             from_offs = (line - msgblk.headers);
838         else if (!strncasecmp("Reply-To:", line, 9))
839             reply_to_offs = (line - msgblk.headers);
840         else if (!strncasecmp("Resent-From:", line, 12))
841             resent_from_offs = (line - msgblk.headers);
842         else if (!strncasecmp("Apparently-From:", line, 16))
843             app_from_offs = (line - msgblk.headers);
844         /*
845          * Netscape 4.7 puts "Sender: zap" in mail headers.  Perverse...
846          *
847          * But a literal reading of RFC822 sec. 4.4.2 supports the idea
848          * that Sender: *doesn't* have to be a working email address.
849          *
850          * The definition of the Sender header in RFC822 says, in
851          * part, "The Sender mailbox specification includes a word
852          * sequence which must correspond to a specific agent (i.e., a
853          * human user or a computer program) rather than a standard
854          * address."  That implies that the contents of the Sender
855          * field don't need to be a legal email address at all So
856          * ignore any Sender or Resent-Sender lines unless they
857          * contain @.
858          *
859          * (RFC2822 says the contents of Sender must be a valid mailbox
860          * address, which is also what RFC822 4.4.4 implies.)
861          */
862         else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
863             sender_offs = (line - msgblk.headers);
864         else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
865             resent_sender_offs = (line - msgblk.headers);
866
867 #ifdef __UNUSED__
868         else if (!strncasecmp("Message-Id:", line, 11))
869         {
870             if (ctl->server.uidl)
871             {
872                 char id[IDLEN+1];
873
874                 line[IDLEN+12] = 0;             /* prevent stack overflow */
875                 sscanf(line+12, "%s", id);
876                 if (!str_find( &ctl->newsaved, num))
877                 {
878                     struct idlist *newl = save_str(&ctl->newsaved,id,UID_SEEN);
879                     newl->val.status.num = num;
880                 }
881             }
882         }
883 #endif /* __UNUSED__ */
884
885         /* if multidrop is on, gather addressee headers */
886         if (MULTIDROP(ctl))
887         {
888             if (!strncasecmp("To:", line, 3)
889                 || !strncasecmp("Cc:", line, 3)
890                 || !strncasecmp("Bcc:", line, 4)
891                 || !strncasecmp("Apparently-To:", line, 14))
892             {
893                 *to_chainptr = (struct addrblk *)xmalloc(sizeof(struct addrblk));
894                 (*to_chainptr)->offset = (line - msgblk.headers);
895                 to_chainptr = &(*to_chainptr)->next; 
896                 *to_chainptr = NULL;
897             }
898
899             else if (!strncasecmp("Resent-To:", line, 10)
900                      || !strncasecmp("Resent-Cc:", line, 10)
901                      || !strncasecmp("Resent-Bcc:", line, 11))
902             {
903                 *resent_to_chainptr = (struct addrblk *)xmalloc(sizeof(struct addrblk));
904                 (*resent_to_chainptr)->offset = (line - msgblk.headers);
905                 resent_to_chainptr = &(*resent_to_chainptr)->next; 
906                 *resent_to_chainptr = NULL;
907             }
908
909             else if (ctl->server.envelope != STRING_DISABLED)
910             {
911                 if (ctl->server.envelope 
912                     && strcasecmp(ctl->server.envelope, "Received"))
913                 {
914                     if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
915                                                        line,
916                                                        strlen(ctl->server.envelope)))
917                     {                           
918                         if (skipcount++ < ctl->server.envskip)
919                             continue;
920                         env_offs = (line - msgblk.headers);
921                     }    
922                 }
923                 else if (!received_for && !strncasecmp("Received:", line, 9))
924                 {
925                     if (skipcount++ < ctl->server.envskip)
926                         continue;
927                     received_for = parse_received(ctl, line);
928                 }
929             }
930         }
931     }
932
933  process_headers:    
934
935     if (retain_mail)
936     {
937         return(PS_RETAINED);
938     }
939     if (refuse_mail)
940         return(PS_REFUSED);
941     /*
942      * This is the duplicate-message killer code.
943      *
944      * When mail delivered to a multidrop mailbox on the server is
945      * addressed to multiple people on the client machine, there will
946      * be one copy left in the box for each recipient.  This is not a
947      * problem if we have the actual recipient address to dispatch on
948      * (e.g. because we've mined it out of sendmail trace headers, or
949      * a qmail Delivered-To line, or a declared sender envelope line).
950      *
951      * But if we're mining addressees out of the To/Cc/Bcc fields, and
952      * if the mail is addressed to N people, each recipient will
953      * get N copies.  This is bad when N > 1.
954      *
955      * Foil this by suppressing all but one copy of a message with a
956      * given set of headers.
957      *
958      * Note: This implementation only catches runs of successive
959      * messages with the same ID, but that should be good
960      * enough. A more general implementation would have to store
961      * ever-growing lists of seen message-IDs; in a long-running
962      * daemon this would turn into a memory leak even if the 
963      * implementation were perfect.
964      * 
965      * Don't mess with this code casually.  It would be way too easy
966      * to break it in a way that blackholed mail.  Better to pass
967      * the occasional duplicate than to do that...
968      *
969      * Matthias Andree:
970      * The real fix however is to insist on Delivered-To: or similar
971      * headers and require that one copy per recipient be dropped.
972      * Everything else breaks sooner or later.
973      */
974     if (MULTIDROP(ctl) && msgblk.headers)
975     {
976         MD5_CTX context;
977
978         MD5Init(&context);
979         MD5Update(&context, msgblk.headers, strlen(msgblk.headers));
980         MD5Final(ctl->digest, &context);
981
982         if (!received_for && env_offs == -1 && !delivered_to)
983         {
984             /*
985              * Hmmm...can MD5 ever yield all zeroes as a hash value?
986              * If so there is a one in 18-quadrillion chance this 
987              * code will incorrectly nuke the first message.
988              */
989             if (!memcmp(ctl->lastdigest, ctl->digest, DIGESTLEN))
990                 return(PS_REFUSED);
991         }
992         memcpy(ctl->lastdigest, ctl->digest, DIGESTLEN);
993     }
994
995     /*
996      * Hack time.  If the first line of the message was blank, with no headers
997      * (this happens occasionally due to bad gatewaying software) cons up
998      * a set of fake headers.  
999      *
1000      * If you modify the fake header template below, be sure you don't
1001      * make either From or To address @-less, otherwise the reply_hack
1002      * logic will do bad things.
1003      */
1004     if (msgblk.headers == (char *)NULL)
1005     {
1006         snprintf(buf, sizeof(buf),
1007                 "From: FETCHMAIL-DAEMON\r\n"
1008                 "To: %s@%s\r\n"
1009                 "Subject: Headerless mail from %s's mailbox on %s\r\n",
1010                 user, fetchmailhost, ctl->remotename, ctl->server.truename);
1011         msgblk.headers = xstrdup(buf);
1012     }
1013
1014     /*
1015      * We can now process message headers before reading the text.
1016      * In fact we have to, as this will tell us where to forward to.
1017      */
1018
1019     /* Check for MIME headers indicating possible 8-bit data */
1020     ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
1021
1022 #ifdef SDPS_ENABLE
1023     if (ctl->server.sdps && sdps_envfrom)
1024     {
1025         /* We have the real envelope return-path, stored out of band by
1026          * SDPS - that's more accurate than any header is going to be.
1027          */
1028         strlcpy(msgblk.return_path, sdps_envfrom, sizeof(msgblk.return_path));
1029         free(sdps_envfrom);
1030     } else
1031 #endif /* SDPS_ENABLE */
1032     /*
1033      * If there is a Return-Path address on the message, this was
1034      * almost certainly the MAIL FROM address given the originating
1035      * sendmail.  This is the best thing to use for logging the
1036      * message origin (it sets up the right behavior for bounces and
1037      * mailing lists).  Otherwise, fall down to the next available 
1038      * envelope address (which is the most probable real sender).
1039      * *** The order is important! ***
1040      * This is especially useful when receiving mailing list
1041      * messages in multidrop mode.  if a local address doesn't
1042      * exist, the bounce message won't be returned blindly to the 
1043      * author or to the list itself but rather to the list manager
1044      * (ex: specified by "Sender:") which is much less annoying.  This 
1045      * is true for most mailing list packages.
1046      */
1047     if( !msgblk.return_path[0] ){
1048         char *ap = NULL;
1049         if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
1050         else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
1051         else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
1052         else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
1053         else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
1054         else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs))) {}
1055         /* multi-line MAIL FROM addresses confuse SMTP terribly */
1056         if (ap && !strchr(ap, '\n')) {
1057             strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
1058             msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
1059         }
1060     }
1061
1062     /* cons up a list of local recipients */
1063     msgblk.recipients = (struct idlist *)NULL;
1064     accept_count = reject_count = 0;
1065     /* is this a multidrop box? */
1066     if (MULTIDROP(ctl))
1067     {
1068 #ifdef SDPS_ENABLE
1069         if (ctl->server.sdps && sdps_envto)
1070         {
1071             /* We have the real envelope recipient, stored out of band by
1072              * SDPS - that's more accurate than any header is going to be.
1073              */
1074             find_server_names(sdps_envto, ctl, &msgblk.recipients);
1075             free(sdps_envto);
1076         } else
1077 #endif /* SDPS_ENABLE */ 
1078         if (env_offs > -1)          /* We have the actual envelope addressee */
1079             find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1080         else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1081       ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1082    {
1083             find_server_names(delivered_to, ctl, &msgblk.recipients);
1084             xfree(delivered_to);
1085    }
1086         else if (received_for)
1087             /*
1088              * We have the Received for addressee.  
1089              * It has to be a mailserver address, or we
1090              * wouldn't have got here.
1091              * We use find_server_names() to let local 
1092              * hostnames go through.
1093              */
1094             find_server_names(received_for, ctl, &msgblk.recipients);
1095         else
1096         {
1097             /*
1098              * We haven't extracted the envelope address.
1099              * So check all the "Resent-To" header addresses if 
1100              * they exist.  If and only if they don't, consider
1101              * the "To" addresses.
1102              */
1103             register struct addrblk *nextptr;
1104             if (resent_to_addrchain) {
1105                 /* delete the "To" chain and substitute it 
1106                  * with the "Resent-To" list 
1107                  */
1108                 while (to_addrchain) {
1109                     nextptr = to_addrchain->next;
1110                     free(to_addrchain);
1111                     to_addrchain = nextptr;
1112                 }
1113                 to_addrchain = resent_to_addrchain;
1114                 resent_to_addrchain = NULL;
1115             }
1116             /* now look for remaining adresses */
1117             while (to_addrchain) {
1118                 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1119                 nextptr = to_addrchain->next;
1120                 free(to_addrchain);
1121                 to_addrchain = nextptr;
1122             }
1123         }
1124         if (!accept_count)
1125         {
1126             no_local_matches = TRUE;
1127             save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1128             if (outlevel >= O_DEBUG)
1129                 report(stdout,
1130                       GT_("no local matches, forwarding to %s\n"),
1131                       run.postmaster);
1132         }
1133     }
1134     else        /* it's a single-drop box, use first localname */
1135         save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1136
1137
1138     /*
1139      * Time to either address the message or decide we can't deliver it yet.
1140      */
1141     if (ctl->errcount > olderrs)        /* there were DNS errors above */
1142     {
1143         if (outlevel >= O_DEBUG)
1144             report(stdout,
1145                    GT_("forwarding and deletion suppressed due to DNS errors\n"));
1146         return(PS_TRANSIENT);
1147     }
1148     else
1149     {
1150         /* set up stuffline() so we can deliver the message body through it */ 
1151         if ((n = open_sink(ctl, &msgblk,
1152                            &good_addresses, &bad_addresses)) != PS_SUCCESS)
1153         {
1154             return(n);
1155         }
1156     }
1157
1158     n = 0;
1159     /*
1160      * Some server/sendmail combinations cause problems when our
1161      * synthetic Received line is before the From header.  Cope
1162      * with this...
1163      */
1164     if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1165         rcv = msgblk.headers;
1166     /* handle ">Received:" lines too */
1167     while (rcv > msgblk.headers && rcv[-1] != '\n')
1168         rcv--;
1169     if (rcv > msgblk.headers)
1170     {
1171         char    c = *rcv;
1172
1173         *rcv = '\0';
1174         n = stuffline(ctl, msgblk.headers);
1175         *rcv = c;
1176     }
1177     if (!run.invisible && n != -1)
1178     {
1179         /* utter any per-message Received information we need here */
1180         if (ctl->server.trueaddr) {
1181             char saddr[50];
1182             int e;
1183
1184             e = getnameinfo(ctl->server.trueaddr, ctl->server.trueaddr_len,
1185                     saddr, sizeof(saddr), NULL, 0,
1186                     NI_NUMERICHOST);
1187             if (e)
1188                 snprintf(saddr, sizeof(saddr), "(%-.*s)", (int)(sizeof(saddr) - 3), gai_strerror(e));
1189             snprintf(buf, sizeof(buf),
1190                     "Received: from %s [%s]\r\n", 
1191                     ctl->server.truename, saddr);
1192         } else {
1193             snprintf(buf, sizeof(buf),
1194                   "Received: from %s\r\n", ctl->server.truename);
1195         }
1196         n = stuffline(ctl, buf);
1197         if (n != -1)
1198         {
1199             /*
1200              * We SHOULD (RFC-2821 sec. 4.4/p. 53) make sure to only use
1201              * IANA registered protocol names here.
1202              */
1203             snprintf(buf, sizeof(buf),
1204                     "\tby %s with %s (fetchmail-%s",
1205                     fetchmailhost,
1206                     protocol->name,
1207                     VERSION);
1208             if (ctl->server.tracepolls)
1209             {
1210                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1211                         " polling %s account %s",
1212                         ctl->server.pollname,
1213                         ctl->remotename);
1214                 if (ctl->folder)
1215                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1216                             " folder %s",
1217                             ctl->folder);
1218             }
1219             snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1220             n = stuffline(ctl, buf);
1221             if (n != -1)
1222             {
1223                 buf[0] = '\t';
1224                 if (good_addresses == 0)
1225                 {
1226                     snprintf(buf+1, sizeof(buf)-1, "for <%s> (by default); ",
1227                             rcpt_address (ctl, run.postmaster, 0));
1228                 }
1229                 else if (good_addresses == 1)
1230                 {
1231                     for (idp = msgblk.recipients; idp; idp = idp->next)
1232                         if (idp->val.status.mark == XMIT_ACCEPT)
1233                             break;      /* only report first address */
1234                     snprintf(buf+1, sizeof(buf)-1,
1235                             "for <%s>", rcpt_address (ctl, idp->id, 1));
1236                     snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf)-1,
1237                             " (%s); ",
1238                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1239                 }
1240                 else
1241                     buf[1] = '\0';
1242
1243                 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1244                         rfc822timestamp());
1245                 n = stuffline(ctl, buf);
1246             }
1247         }
1248     }
1249
1250     if (n != -1)
1251         n = stuffline(ctl, rcv);        /* ship out rest of msgblk.headers */
1252
1253     if (n == -1)
1254     {
1255         report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1256         release_sink(ctl);
1257         return(PS_IOERR);
1258     }
1259     else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
1260         fputc('#', stdout);
1261
1262     /* write error notifications */
1263     if (no_local_matches || has_nuls || bad_addresses)
1264     {
1265         int     errlen = 0;
1266         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1267
1268         errmsg = errhd;
1269         strlcpy(errhd, "X-Fetchmail-Warning: ", sizeof(errhd));
1270         if (no_local_matches)
1271         {
1272             if (reject_count != 1)
1273                 strlcat(errhd, GT_("no recipient addresses matched declared local names"), sizeof(errhd));
1274             else
1275             {
1276                 for (idp = msgblk.recipients; idp; idp = idp->next)
1277                     if (idp->val.status.mark == XMIT_REJECT)
1278                         break;
1279                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1280                         GT_("recipient address %s didn't match any local name"), idp->id);
1281             }
1282         }
1283
1284         if (has_nuls)
1285         {
1286             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1287                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1288             snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1289                         GT_("message has embedded NULs"));
1290         }
1291
1292         if (bad_addresses)
1293         {
1294             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1295                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1296             snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1297                         GT_("SMTP listener rejected local recipient addresses: "));
1298             errlen = strlen(errhd);
1299             for (idp = msgblk.recipients; idp; idp = idp->next)
1300                 if (idp->val.status.mark == XMIT_RCPTBAD)
1301                     errlen += strlen(idp->id) + 2;
1302
1303             errmsg = (char *)xmalloc(errlen + 3);
1304             strcpy(errmsg, errhd);
1305             for (idp = msgblk.recipients; idp; idp = idp->next)
1306                 if (idp->val.status.mark == XMIT_RCPTBAD)
1307                 {
1308                     strcat(errmsg, idp->id);
1309                     if (idp->next)
1310                         strcat(errmsg, ", ");
1311                 }
1312
1313         }
1314
1315         strcat(errmsg, "\r\n");
1316
1317         /* ship out the error line */
1318         stuffline(ctl, errmsg);
1319
1320         if (errmsg != errhd)
1321             free(errmsg);
1322     }
1323
1324     /* issue the delimiter line */
1325     cp = buf;
1326     *cp++ = '\r';
1327     *cp++ = '\n';
1328     *cp++ = '\0';
1329     n = stuffline(ctl, buf);
1330
1331     if (n == strlen(buf))
1332         return PS_SUCCESS;
1333     else
1334         return PS_SOCKET;
1335 }
1336
1337 int readbody(int sock, struct query *ctl, flag forward, int len)
1338 /* read and dispose of a message body presented on sock */
1339 /*   ctl:               query control record */
1340 /*   sock:              to which the server is connected */
1341 /*   len:               length of message */
1342 /*   forward:           TRUE to forward */
1343 {
1344     int linelen;
1345     char buf[MSGBUFSIZE+4];
1346     char *inbufp = buf;
1347     flag issoftline = FALSE;
1348
1349     /*
1350      * Pass through the text lines in the body.
1351      *
1352      * Yes, this wants to be ||, not &&.  The problem is that in the most
1353      * important delimited protocol, POP3, the length is not reliable.
1354      * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1355      * So, for delimited protocols we need to ignore the length here and
1356      * instead drop out of the loop with a break statement when we see
1357      * the message delimiter.
1358      */
1359     while (protocol->delimited || len > 0)
1360     {
1361         set_timeout(mytimeout);
1362         /* XXX FIXME: for undelimited protocols that ship the size, such
1363          * as IMAP, we might want to use the count of remaining characters
1364          * instead of the buffer size -- not for fetchmail 6.3.X though */
1365         if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1366         {
1367             set_timeout(0);
1368             release_sink(ctl);
1369             return(PS_SOCKET);
1370         }
1371         set_timeout(0);
1372
1373         /* write the message size dots */
1374         if (linelen > 0)
1375         {
1376             sizeticker += linelen;
1377             while (sizeticker >= SIZETICKER)
1378             {
1379                 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
1380                 {
1381                     fputc('.', stdout);
1382                     fflush(stdout);
1383                 }
1384                 sizeticker -= SIZETICKER;
1385             }
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 */