]> Pileus Git - ~andy/fetchmail/blob - driver.c
Enclose string dumps in doublequotes to work with visbuf properly.
[~andy/fetchmail] / driver.c
1 /*
2  * driver.c -- generic driver for mail fetch method protocols
3  *
4  * Copyright 1997 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  <setjmp.h>
11 #include  <errno.h>
12 #include  <ctype.h>
13 #include  <string.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 #if defined(HAVE_ALLOCA_H)
29 #include <alloca.h>
30 #else
31 #ifdef _AIX
32  #pragma alloca
33 #endif
34 #endif
35 #if defined(HAVE_SYS_ITIMER_H)
36 #include <sys/itimer.h>
37 #endif
38 #include  <sys/time.h>
39 #include  <signal.h>
40
41 #ifndef HAVE_STRFTIME /* For ctime prototype */
42 #include  <sys/types.h>
43 #include  <time.h>
44 #endif
45
46 #ifdef HAVE_RES_SEARCH
47 #include <netdb.h>
48 #include "mx.h"
49 #endif /* HAVE_RES_SEARCH */
50
51 #ifdef KERBEROS_V4
52 #if defined (__bsdi__)
53 #include <des.h> /* order of includes matters */
54 #include <krb.h>
55 #define krb_get_err_text(e) (krb_err_txt[e])
56 #else
57 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
58 #define krb_get_err_text(e) (krb_err_txt[e])
59 #include <krb.h>
60 #include <des.h>
61 #else
62 #include <krb.h>
63 #include <des.h>
64 #endif /* ! defined (__FreeBSD__) */
65 #endif /* ! defined (__bsdi__) */
66 #include <netinet/in.h>
67 #include <netdb.h>
68 #endif /* KERBEROS_V4 */
69 #ifdef KERBEROS_V5
70 #include <krb5.h>
71 #include <com_err.h>
72 #endif /* KERBEROS_V5 */
73
74 #include  "fetchmail.h"
75 #include  "socket.h"
76 #include  "smtp.h"
77
78 /* BSD portability hack...I know, this is an ugly place to put it */
79 #if !defined(SIGCHLD) && defined(SIGCLD)
80 #define SIGCHLD SIGCLD
81 #endif
82
83 #if INET6
84 #define SMTP_PORT       "smtp"  /* standard SMTP service port */
85 #else /* INET6 */
86 #define SMTP_PORT       25      /* standard SMTP service port */
87 #endif /* INET6 */
88
89 #ifndef strstr          /* glibc-2.1 declares this as a macro */
90 extern char *strstr();  /* needed on sysV68 R3V7.1. */
91 #endif /* strstr */
92
93 int fetchlimit;         /* how often to tear down the server connection */
94 int batchcount;         /* count of messages sent in current batch */
95 flag peek_capable;      /* can we peek for better error recovery? */
96 int pass;               /* how many times have we re-polled? */
97
98 static const struct method *protocol;
99 static jmp_buf  restart;
100
101 char tag[TAGLEN];
102 static int tagnum;
103 #define GENSYM  (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
104
105 static char shroud[PASSWORDLEN];        /* string to shroud in debug output */
106 static int mytimeout;                   /* value of nonreponse timeout */
107 static int msglen;                      /* actual message length */
108 static int mimemsg;                     /* bitmask indicating MIME body-type */
109
110 /* use these to track what was happening when the nonresponse timer fired */
111 #define GENERAL_WAIT    0       /* unknown wait type */
112 #define SERVER_WAIT     1       /* waiting for mailserver response */
113 #define LISTENER_WAIT   2       /* waiting for listener initialization */
114 #define FORWARDING_WAIT 3       /* waiting for listener response */
115 static phase;
116
117 static void set_timeout(int timeleft)
118 /* reset the nonresponse-timeout */
119 {
120 #ifndef __EMX__
121     struct itimerval ntimeout;
122
123     ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
124     ntimeout.it_value.tv_sec  = timeleft;
125     ntimeout.it_value.tv_usec = 0;
126     setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
127 #endif
128 }
129
130 static void timeout_handler (int signal)
131 /* handle server-timeout SIGALRM signal */
132 {
133     longjmp(restart, 1);
134 }
135
136 #define XMIT_ACCEPT             1
137 #define XMIT_REJECT             2
138 #define XMIT_ANTISPAM           3       
139 static int accept_count, reject_count;
140
141 static void map_name(name, ctl, xmit_names)
142 /* add given name to xmit_names if it matches declared localnames */
143 const char *name;               /* name to map */
144 struct query *ctl;              /* list of permissible aliases */
145 struct idlist **xmit_names;     /* list of recipient names parsed out */
146 {
147     const char  *lname;
148     int sl;
149     int off = 0;
150     
151     lname = idpair_find(&ctl->localnames, name+off);
152     if (!lname && ctl->wildcard)
153         lname = name+off;
154
155     if (lname != (char *)NULL)
156     {
157         if (outlevel == O_VERBOSE)
158             error(0, 0, "mapped %s to local %s", name, lname);
159         save_str(xmit_names, lname, XMIT_ACCEPT);
160         accept_count++;
161     }
162 }
163
164 void find_server_names(hdr, ctl, xmit_names)
165 /* parse names out of a RFC822 header into an ID list */
166 const char *hdr;                /* RFC822 header in question */
167 struct query *ctl;              /* list of permissible aliases */
168 struct idlist **xmit_names;     /* list of recipient names parsed out */
169 {
170     if (hdr == (char *)NULL)
171         return;
172     else
173     {
174         char    *cp;
175
176         for (cp = nxtaddr(hdr);
177              cp != NULL;
178              cp = nxtaddr(NULL))
179         {
180             char        *atsign;
181
182             /*
183              * If the name of the user begins with a qmail virtual
184              * domain prefix, ignore the prefix.  Doing this here
185              * means qvirtual will work either with ordinary name
186              * mapping or with a localdomains option.
187              */
188             if (ctl->server.qvirtual)
189             {
190                 int sl = strlen(ctl->server.qvirtual);
191  
192                 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
193                     cp += sl;
194             }
195
196             if ((atsign = strchr(cp, '@'))) {
197                 struct idlist   *idp;
198
199                 /*
200                  * Does a trailing segment of the hostname match something
201                  * on the localdomains list?  If so, save the whole name
202                  * and keep going.
203                  */
204                 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
205                     char        *rhs;
206
207                     rhs = atsign + (strlen(atsign) - strlen(idp->id));
208                     if (rhs > atsign &&
209                         (rhs[-1] == '.' || rhs[-1] == '@') &&
210                         strcasecmp(rhs, idp->id) == 0)
211                     {
212                         if (outlevel == O_VERBOSE)
213                             error(0, 0, "passed through %s matching %s", 
214                                   cp, idp->id);
215                         save_str(xmit_names, cp, XMIT_ACCEPT);
216                         accept_count++;
217                         goto nomap;
218                     }
219                 }
220
221                 /* if we matched a local domain, idp != NULL */
222                 if (!idp)
223                 {
224                     /*
225                      * Check to see if the right-hand part is an alias
226                      * or MX equivalent of the mailserver.  If it's
227                      * not, skip this name.  If it is, we'll keep
228                      * going and try to find a mapping to a client name.
229                      */
230                     if (!is_host_alias(atsign+1, ctl))
231                     {
232                         save_str(xmit_names, cp, XMIT_REJECT);
233                         reject_count++;
234                         continue;
235                     }
236                 }
237                 atsign[0] = '\0';
238                 map_name(cp, ctl, xmit_names);
239             nomap:;
240             }
241         }
242     }
243 }
244
245 static char *parse_received(struct query *ctl, char *bufp)
246 /* try to extract real address from the Received line */
247 /* If a valid Received: line is found, we return the full address in
248  * a buffer which can be parsed from nxtaddr().  This is to ansure that
249  * the local domain part of the address can be passed along in 
250  * find_server_names() if it contains one.
251  * Note: We should return a dummy header containing the address 
252  * which makes nxtaddr() behave correctly. 
253  */
254 {
255     char *ok = (char *)NULL;
256     static char rbuf[HOSTLEN + USERNAMELEN + 4]; 
257
258     /*
259      * Try to extract the real envelope addressee.  We look here
260      * specifically for the mailserver's Received line.
261      * Note: this will only work for sendmail, or an MTA that
262      * shares sendmail's convention for embedding the envelope
263      * address in the Received line.  Sendmail itself only
264      * does this when the mail has a single recipient.
265      */
266     if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
267     {
268         char    *sp, *tp;
269
270         /* extract space-delimited token after "by " */
271         for (sp = ok + 3; isspace(*sp); sp++)
272             continue;
273         tp = rbuf;
274         for (; !isspace(*sp); sp++)
275             *tp++ = *sp;
276         *tp = '\0';
277
278         /*
279          * If it's a DNS name of the mail server, look for the
280          * recipient name after a following "for".  Otherwise
281          * punt.
282          */
283         if (is_host_alias(rbuf, ctl) &&
284             (ok = strstr(sp, "for ")) && 
285             isspace(ok[-1]))
286         {
287             flag        want_gt = FALSE;
288
289             tp = rbuf;
290             sp = ok + 4;
291             *tp++ = ':';        /* Here is the hack.  This is to be friends */
292             *tp++ = ' ';        /* with nxtaddr()... */
293             if (*sp == '<')
294             {
295                 want_gt = TRUE;
296                 sp++;
297             }
298             while (*sp == '@')          /* skip routes */
299                 while (*sp && *sp++ != ':')
300                     continue;
301             while (*sp
302                    && (want_gt ? (*sp != '>') : !isspace(*sp))
303                    && *sp != ';')
304                 if (!isspace(*sp))
305                     *tp++ = *sp++;
306                 else
307                 {
308                     /* uh oh -- whitespace here can't be right! */
309                     ok = (char *)NULL;
310                     break;
311                 }
312             *tp++ = '\n';
313             *tp = '\0';
314             if (strlen(rbuf) <= 3)      /* apparently nothing has been found */
315                 ok = NULL;
316         } else
317             ok = (char *)NULL;
318     }
319
320     if (!ok)
321         return(NULL);
322     else
323     {
324         if (outlevel == O_VERBOSE) {
325             char *lf = rbuf + strlen(rbuf)-1;
326             *lf = '\0';
327             error(0, 0, "found Received address `%s'", rbuf+2);
328             *lf = '\n';
329         }
330         return(rbuf);
331     }
332 }
333
334 static int smtp_open(struct query *ctl)
335 /* try to open a socket to the appropriate SMTP server for this query */ 
336 {
337     /* maybe it's time to close the socket in order to force delivery */
338     if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
339     {
340         close(ctl->smtp_socket);
341         ctl->smtp_socket = -1;
342         batchcount = 0;
343     }
344
345     /* if no socket to any SMTP host is already set up, try to open one */
346     if (ctl->smtp_socket == -1) 
347     {
348         /* 
349          * RFC 1123 requires that the domain name in HELO address is a
350          * "valid principal domain name" for the client host. If we're
351          * running in invisible mode, violate this with malice
352          * aforethought in order to make the Received headers and
353          * logging look right.
354          *
355          * In fact this code relies on the RFC1123 requirement that the
356          * SMTP listener must accept messages even if verification of the
357          * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
358          *
359          * How we compute the true mailhost name to pass to the
360          * listener doesn't affect behavior on RFC1123- violating
361          * listeners that check for name match; we're going to lose
362          * on those anyway because we can never give them a name
363          * that matches the local machine fetchmail is running on.
364          * What it will affect is the listener's logging.
365          */
366         struct idlist   *idp;
367         char *id_me = run.invisible ? ctl->server.truename : "localhost";
368         int oldphase = phase;
369
370         errno = 0;
371
372         /*
373          * Run down the SMTP hunt list looking for a server that's up.
374          * Use both explicit hunt entries (value TRUE) and implicit 
375          * (default) ones (value FALSE).
376          */
377         oldphase = phase;
378         phase = LISTENER_WAIT;
379
380         set_timeout(ctl->server.timeout);
381         for (idp = ctl->smtphunt; idp; idp = idp->next)
382         {
383             char        *cp, *parsed_host = alloca(strlen(idp->id) + 1);
384 #ifdef INET6 
385             char        *portnum = SMTP_PORT;
386 #else
387             int         portnum = SMTP_PORT;
388 #endif /* INET6 */
389
390             ctl->smtphost = idp->id;  /* remember last host tried. */
391
392             strcpy(parsed_host, idp->id);
393             if ((cp = strrchr(parsed_host, '/')))
394             {
395                 *cp++ = 0;
396 #ifdef INET6 
397                 portnum = cp;
398 #else
399                 portnum = atoi(cp);
400 #endif /* INET6 */
401             }
402
403             if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
404                 continue;
405
406             /* first, probe for ESMTP */
407             if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
408                     SMTP_ehlo(ctl->smtp_socket, id_me,
409                           &ctl->server.esmtp_options) == SM_OK)
410                break;  /* success */
411
412             /*
413              * RFC 1869 warns that some listeners hang up on a failed EHLO,
414              * so it's safest not to assume the socket will still be good.
415              */
416             SockClose(ctl->smtp_socket);
417             ctl->smtp_socket = -1;
418
419             /* if opening for ESMTP failed, try SMTP */
420             if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
421                 continue;
422
423             if (SMTP_ok(ctl->smtp_socket) == SM_OK && 
424                     SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
425                 break;  /* success */
426
427             SockClose(ctl->smtp_socket);
428             ctl->smtp_socket = -1;
429         }
430         set_timeout(0);
431         phase = oldphase;
432     }
433
434     if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
435         error(0, 0, "forwarding to %s", ctl->smtphost);
436
437     return(ctl->smtp_socket);
438 }
439
440 /* these are shared by stuffline, readheaders and readbody */
441 static FILE *sinkfp;
442 static RETSIGTYPE (*sigchld)();
443 static int sizeticker;
444
445 static int stuffline(struct query *ctl, char *buf)
446 /* ship a line to the given control block's output sink (SMTP server or MDA) */
447 {
448     int n, oldphase;
449     char *last;
450
451     /* The line may contain NUL characters. Find the last char to use
452      * -- the real line termination is the sequence "\n\0".
453      */
454     last = buf;
455     while ((last += strlen(last)) && (last[-1] != '\n'))
456         last++;
457
458     /* fix message lines that have only \n termination (for qmail) */
459     if (ctl->forcecr)
460     {
461         if (last - 1 == buf || last[-2] != '\r')
462         {
463             last[-1] = '\r';
464             *last++  = '\n';
465             *last    = '\0';
466         }
467     }
468
469     oldphase = phase;
470     phase = FORWARDING_WAIT;
471
472     /*
473      * SMTP byte-stuffing.  We only do this if the protocol does *not*
474      * use .<CR><LF> as EOM.  If it does, the server will already have
475      * decorated any . lines it sends back up.
476      */
477     if (*buf == '.')
478         if (protocol->delimited)        /* server has already byte-stuffed */
479         {
480             if (ctl->mda)
481                 ++buf;
482             else
483                 /* writing to SMTP, leave the byte-stuffing in place */;
484         }
485         else /* if (!protocol->delimited)       -- not byte-stuffed already */
486         {
487             if (!ctl->mda)
488                 SockWrite(ctl->smtp_socket, buf, 1);    /* byte-stuff it */
489             else
490                 /* leave it alone */;
491         }
492
493     /* we may need to strip carriage returns */
494     if (ctl->stripcr)
495     {
496         char    *sp, *tp;
497
498         for (sp = tp = buf; sp < last; sp++)
499             if (*sp != '\r')
500                 *tp++ =  *sp;
501         *tp = '\0';
502         last = tp;
503     }
504
505     n = 0;
506     if (ctl->mda)
507         n = fwrite(buf, 1, last - buf, sinkfp);
508     else if (ctl->smtp_socket != -1)
509         n = SockWrite(ctl->smtp_socket, buf, last - buf);
510
511     phase = oldphase;
512
513     return(n);
514 }
515
516
517 static void sanitize(s)
518 /* replace unsafe shellchars by an _ */
519 char *s;
520 {
521     static char *ok_chars = " 1234567890!@%-_=+:,./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
522     char *cp;
523
524     for (cp = s; *(cp += strspn(cp, ok_chars)); /* NO INCREMENT */)
525         *cp = '_';
526 }
527
528
529 #define EMPTYLINE(s)    ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
530
531 static int readheaders(sock, fetchlen, reallen, ctl, num)
532 /* read message headers and ship to SMTP or MDA */
533 int sock;               /* to which the server is connected */
534 long fetchlen;          /* length of message according to fetch response */
535 long reallen;           /* length of message according to getsizes */
536 struct query *ctl;      /* query control record */
537 int num;                /* index of message */
538 {
539     struct addrblk
540     {
541         int             offset;
542         struct addrblk  *next;
543     };
544     struct addrblk      *to_addrchain = NULL;
545     struct addrblk      **to_chainptr = &to_addrchain;
546     struct addrblk      *resent_to_addrchain = NULL;
547     struct addrblk      **resent_to_chainptr = &resent_to_addrchain;
548
549     char                buf[MSGBUFSIZE+1];
550     char                return_path[HOSTLEN + USERNAMELEN + 4]; 
551     int                 from_offs, reply_to_offs, resent_from_offs;
552     int                 app_from_offs, sender_offs, resent_sender_offs;
553     int                 env_offs;
554     char                *headers, *received_for, *destaddr, *rcv, *cp;
555     int                 n, linelen, oldlen, ch, remaining, skipcount;
556     struct idlist       *idp, *xmit_names;
557     flag                good_addresses, bad_addresses, has_nuls;
558     flag                no_local_matches = FALSE;
559     flag                headers_ok;
560     int                 olderrs;
561
562     sizeticker = 0;
563     has_nuls = headers_ok = FALSE;
564     return_path[0] = '\0';
565     olderrs = ctl->errcount;
566
567     /* read message headers */
568     headers = received_for = NULL;
569     from_offs = reply_to_offs = resent_from_offs = app_from_offs = 
570         sender_offs = resent_sender_offs = env_offs = -1;
571     oldlen = 0;
572     msglen = 0;
573     skipcount = 0;
574     mimemsg = 0;
575
576     for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
577     {
578         char *line;
579
580         line = xmalloc(sizeof(buf));
581         linelen = 0;
582         line[0] = '\0';
583         do {
584             set_timeout(ctl->server.timeout);
585             if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
586                 set_timeout(0);
587                 free(line);
588                 free(headers);
589                 return(PS_SOCKET);
590             }
591             set_timeout(0);
592             linelen += n;
593             msglen += n;
594
595             /* lines may not be properly CRLF terminated; fix this for qmail */
596             if (ctl->forcecr)
597             {
598                 cp = buf + strlen(buf) - 1;
599                 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
600                 {
601                     *cp++ = '\r';
602                     *cp++ = '\n';
603                     *cp++ = '\0';
604                 }
605             }
606
607
608             line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
609
610             strcat(line, buf);
611
612             /* check for end of headers */
613             if (EMPTYLINE(line))
614             {
615                 headers_ok = TRUE;
616                 has_nuls = (linelen != strlen(line));
617                 free(line);
618                 goto process_headers;
619             }
620
621             /*
622              * Check for end of message immediately.  If one of your folders
623              * has been mangled, the delimiter may occur directly after the
624              * header.
625              */
626             if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
627             {
628                 free(line);
629                 has_nuls = (linelen != strlen(line));
630                 goto process_headers;
631             }
632         } while
633             /* we may need to grab RFC822 continuations */
634             ((ch = SockPeek(sock)) == ' ' || ch == '\t');
635
636         /* write the message size dots */
637         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
638         {
639             sizeticker += linelen;
640             while (sizeticker >= SIZETICKER)
641             {
642                 error_build(".");
643                 sizeticker -= SIZETICKER;
644             }
645         }
646
647         /* we see an ordinary (non-header, non-message-delimiter line */
648         has_nuls = (linelen != strlen(line));
649
650         /*
651          * The University of Washington IMAP server (the reference
652          * implementation of IMAP4 written by Mark Crispin) relies
653          * on being able to keep base-UID information in a special
654          * message at the head of the mailbox.  This message should
655          * neither be deleted nor forwarded.
656          */
657 #ifdef POP2_ENABLE
658         /*
659          * We disable this check under POP2 because there's no way to
660          * prevent deletion of the message.  So at least we ought to 
661          * forward it to the user so he or she will have some clue
662          * that things have gone awry.
663          */
664         if (protocol->port != 109)
665 #endif /* POP2_ENABLE */
666             if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
667                 free(line);
668                 free(headers);
669                 return(PS_RETAINED);
670             }
671
672         /*
673          * This code prevents fetchmail from becoming an accessory after
674          * the fact to upstream sendmails with the `E' option on.  It also
675          * copes with certain brain-dead POP servers (like NT's) that pass
676          * through Unix from_ lines.
677          *
678          * Either of these bugs can result in a non-RFC822 line at the
679          * beginning of the headers.  If fetchmail just passes it
680          * through, the client listener may think the message has *no*
681          * headers (since the first) line it sees doesn't look
682          * RFC822-conformant) and fake up a set.
683          *
684          * What the user would see in this case is bogus (synthesized)
685          * headers, followed by a blank line, followed by the >From, 
686          * followed by the real headers, followed by a blank line,
687          * followed by text.
688          *
689          * We forestall this lossage by tossing anything that looks
690          * like an escaped or passed-through From_ line in headers.
691          * These aren't RFC822 so our conscience is clear...
692          */
693         if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
694         {
695             free(line);
696             continue;
697         }
698
699         /*
700          * If we see a Status line, it may have been inserted by an MUA
701          * on the mail host, or it may have been inserted by the server
702          * program after the headers in the transaction stream.  This
703          * can actually hose some new-mail notifiers such as xbuffy,
704          * which assumes any Status line came from a *local* MDA and
705          * therefore indicates that the message has been seen.
706          *
707          * Some buggy POP servers (including at least the 3.3(20)
708          * version of the one distributed with IMAP) insert empty
709          * Status lines in the transaction stream; we'll chuck those
710          * unconditionally.  Nonempty ones get chucked if the user
711          * turns on the dropstatus flag.
712          */
713         {
714             char        *cp;
715
716             if (!strncasecmp(line, "Status:", 7))
717                 cp = line + 7;
718             else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
719                 cp = line + 17;
720             else
721                 cp = NULL;
722             if (cp) {
723                 while (*cp && isspace(*cp)) cp++;
724                 if (!*cp || ctl->dropstatus)
725                 {
726                     free(line);
727                     continue;
728                 }
729             }
730         }
731
732         if (ctl->rewrite)
733             line = reply_hack(line, ctl->server.truename);
734
735         /*
736          * OK, this is messy.  If we're forwarding by SMTP, it's the
737          * SMTP-receiver's job (according to RFC821, page 22, section
738          * 4.1.1) to generate a Return-Path line on final delivery.
739          * The trouble is, we've already got one because the
740          * mailserver's SMTP thought *it* was responsible for final
741          * delivery.
742          *
743          * Stash away the contents of Return-Path for use in generating
744          * MAIL FROM later on, then prevent the header from being saved
745          * with the others.  In effect, we strip it off here.
746          *
747          * If the SMTP server conforms to the standards, and fetchmail gets the
748          * envelope sender from the Return-Path, the new Return-Path should be
749          * exactly the same as the original one.
750          *
751          * We do *not* want to ignore empty Return-Path headers.  These should
752          * be passed through as a way of indicating that a message should
753          * not trigger bounces if delivery fails.  What we *do* need to do is
754          * make sure we never try to rewrite such a blank Return-Path.  We
755          * handle this with a check for <> in the rewrite logic.
756          */
757         if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
758         {
759             strcpy(return_path, cp);
760             if (!ctl->mda) {
761                 free(line);
762                 continue;
763             }
764         }
765
766         if (!headers)
767         {
768             oldlen = strlen(line);
769             headers = xmalloc(oldlen + 1);
770             (void) strcpy(headers, line);
771             free(line);
772             line = headers;
773         }
774         else
775         {
776             int newlen;
777
778             newlen = oldlen + strlen(line);
779             headers = (char *) realloc(headers, newlen + 1);
780             if (headers == NULL) {
781                 free(line);
782                 return(PS_IOERR);
783             }
784             strcpy(headers + oldlen, line);
785             free(line);
786             line = headers + oldlen;
787             oldlen = newlen;
788         }
789
790         if (!strncasecmp("From:", line, 5))
791             from_offs = (line - headers);
792         else if (!strncasecmp("Reply-To:", line, 9))
793             reply_to_offs = (line - headers);
794         else if (!strncasecmp("Resent-From:", line, 12))
795             resent_from_offs = (line - headers);
796         else if (!strncasecmp("Apparently-From:", line, 16))
797             app_from_offs = (line - headers);
798         else if (!strncasecmp("Sender:", line, 7))
799             sender_offs = (line - headers);
800         else if (!strncasecmp("Resent_Sender:", line, 14))
801             resent_sender_offs = (line - headers);
802
803         else if (!strncasecmp("Message-Id:", buf, 11))
804         {
805             if (ctl->server.uidl)
806             {
807                 char id[IDLEN+1];
808
809                 buf[IDLEN+12] = 0;              /* prevent stack overflow */
810                 sscanf(buf+12, "%s", id);
811                 if (!str_find( &ctl->newsaved, num))
812                 {
813                     struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
814                     new->val.status.num = num;
815                 }
816             }
817         }
818
819         else if (!MULTIDROP(ctl))
820             continue;
821
822         else if (!strncasecmp("To:", line, 3)
823                         || !strncasecmp("Cc:", line, 3)
824                         || !strncasecmp("Bcc:", line, 4)
825                         || !strncasecmp("Apparently-To:", line, 14))
826         {
827             *to_chainptr = xmalloc(sizeof(struct addrblk));
828             (*to_chainptr)->offset = (line - headers);
829             to_chainptr = &(*to_chainptr)->next; 
830             *to_chainptr = NULL;
831         }
832
833         else if (!strncasecmp("Resent-To:", line, 10)
834                         || !strncasecmp("Resent-Cc:", line, 10)
835                         || !strncasecmp("Resent-Bcc:", line, 11))
836         {
837             *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
838             (*resent_to_chainptr)->offset = (line - headers);
839             resent_to_chainptr = &(*resent_to_chainptr)->next; 
840             *resent_to_chainptr = NULL;
841         }
842
843         else if (ctl->server.envelope != STRING_DISABLED)
844         {
845             if (ctl->server.envelope 
846                         && strcasecmp(ctl->server.envelope, "Received"))
847             {
848                 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
849                                                 line,
850                                                 strlen(ctl->server.envelope)))
851                 {                               
852                     if (skipcount++ != ctl->server.envskip)
853                         continue;
854                     env_offs = (line - headers);
855                 }    
856             }
857             else if (!received_for && !strncasecmp("Received:", line, 9))
858             {
859                 if (skipcount++ != ctl->server.envskip)
860                     continue;
861                 received_for = parse_received(ctl, line);
862             }
863         }
864     }
865
866  process_headers:
867     /*
868      * We want to detect this early in case there are so few headers that the
869      * dispatch logic barfs.
870      */
871     if (!headers_ok)
872     {
873         if (outlevel > O_SILENT)
874             error(0,0,"message delimiter found while scanning headers");
875     }
876
877     /*
878      * Hack time.  If the first line of the message was blank, with no headers
879      * (this happens occasionally due to bad gatewaying software) cons up
880      * a set of fake headers.  
881      *
882      * If you modify the fake header template below, be sure you don't
883      * make either From or To address @-less, otherwise the reply_hack
884      * logic will do bad things.
885      */
886     if (headers == (char *)NULL)
887     {
888 #ifdef HAVE_SNPRINTF
889         snprintf(buf, sizeof(buf),
890 #else
891         sprintf(buf, 
892 #endif /* HAVE_SNPRINTF */
893         "From: FETCHMAIL-DAEMON\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
894                 user, ctl->remotename, ctl->server.truename);
895         headers = xstrdup(buf);
896     }
897
898     /*
899      * We can now process message headers before reading the text.
900      * In fact we have to, as this will tell us where to forward to.
901      */
902
903     /* Decode MIME encoded headers. We MUST do this before
904      * looking at the Content-Type / Content-Transfer-Encoding
905      * headers (RFC 2046).
906      */
907     if (ctl->mimedecode) {
908         UnMimeHeader(headers);
909     }
910     /* Check for MIME headers indicating possible 8-bit data */
911     mimemsg = MimeBodyType(headers, ctl->mimedecode);
912
913     /*
914      * If there is a Return-Path address on the message, this was
915      * almost certainly the MAIL FROM address given the originating
916      * sendmail.  This is the best thing to use for logging the
917      * message origin (it sets up the right behavior for bounces and
918      * mailing lists).  Otherwise, fall down to the next available 
919      * envelope address (which is the most probable real sender).
920      * *** The order is important! ***
921      * This is especially useful when receiving mailing list
922      * messages in multidrop mode.  if a local address doesn't
923      * exist, the bounce message won't be returned blindly to the 
924      * author or to the list itself but rather to the list manager
925      * (ex: specified by "Sender:") wich is less anoying.  This is
926      * true for most mailing list packages.
927      */
928     if( !return_path[0] ){
929         char *ap = NULL;
930         if (resent_sender_offs >= 0 && (ap = nxtaddr(headers + resent_sender_offs)));
931         else if (sender_offs >= 0 && (ap = nxtaddr(headers + sender_offs)));
932         else if (resent_from_offs >= 0 && (ap = nxtaddr(headers + resent_from_offs)));
933         else if (from_offs >= 0 && (ap = nxtaddr(headers + from_offs)));
934         else if (reply_to_offs >= 0 && (ap = nxtaddr(headers + reply_to_offs)));
935         else if (app_from_offs >= 0 && (ap = nxtaddr(headers + app_from_offs)));
936         if (ap) strcpy( return_path, ap );
937     }
938
939     /* cons up a list of local recipients */
940     xmit_names = (struct idlist *)NULL;
941     bad_addresses = good_addresses = accept_count = reject_count = 0;
942     /* is this a multidrop box? */
943     if (MULTIDROP(ctl))
944     {
945         if (env_offs > -1)          /* We have the actual envelope addressee */
946             find_server_names(headers + env_offs, ctl, &xmit_names);
947         else if (received_for)
948             /*
949              * We have the Received for addressee.  
950              * It has to be a mailserver address, or we
951              * wouldn't have got here.
952              * We use find_server_names() to let local 
953              * hostnames go through.
954              */
955             find_server_names(received_for, ctl, &xmit_names);
956 #ifdef SDPS_ENABLE
957         else if (sdps_envto)
958         {
959             find_server_names(sdps_envto, ctl, &xmit_names);
960             free(sdps_envto);
961         }
962 #endif /* SDPS_ENABLE */ 
963         else
964         {
965             /*
966              * We haven't extracted the envelope address.
967              * So check all the "Resent-To" header addresses if 
968              * they exist.  If and only if they don't, consider
969              * the "To" adresses.
970              */
971             register struct addrblk *nextptr;
972             if (resent_to_addrchain) {
973                 /* delete the "To" chain and substitute it 
974                  * with the "Resent-To" list 
975                  */
976                 while (to_addrchain) {
977                     nextptr = to_addrchain->next;
978                     free(to_addrchain);
979                     to_addrchain = nextptr;
980                 }
981                 to_addrchain = resent_to_addrchain;
982                 resent_to_addrchain = NULL;
983             }
984             /* now look for remaining adresses */
985             while (to_addrchain) {
986                 find_server_names(headers+to_addrchain->offset, ctl, &xmit_names);
987                 nextptr = to_addrchain->next;
988                 free(to_addrchain);
989                 to_addrchain = nextptr;
990             }
991         }
992         if (!accept_count)
993         {
994             no_local_matches = TRUE;
995             save_str(&xmit_names, run.postmaster, XMIT_ACCEPT);
996             if (outlevel == O_VERBOSE)
997                 error(0, 0, 
998                       "no local matches, forwarding to %s",
999                       run.postmaster);
1000         }
1001     }
1002     else        /* it's a single-drop box, use first localname */
1003         save_str(&xmit_names, ctl->localnames->id, XMIT_ACCEPT);
1004
1005
1006     /*
1007      * Time to either address the message or decide we can't deliver it yet.
1008      */
1009     if (ctl->errcount > olderrs)        /* there were DNS errors above */
1010     {
1011         if (outlevel == O_VERBOSE)
1012             error(0,0, "forwarding and deletion suppressed due to DNS errors");
1013         free(headers);
1014         free_str_list(&xmit_names);
1015         return(PS_TRANSIENT);
1016     }
1017     else if (ctl->mda)          /* we have a declared MDA */
1018     {
1019         int     length = 0, fromlen = 0, nameslen = 0;
1020         char    *names = NULL, *before, *after, *from = NULL;
1021
1022         for (idp = xmit_names; idp; idp = idp->next)
1023             if (idp->val.status.mark == XMIT_ACCEPT)
1024                 good_addresses++;
1025
1026         destaddr = "localhost";
1027
1028         length = strlen(ctl->mda);
1029         before = xstrdup(ctl->mda);
1030
1031         /* get user addresses for %T (or %s for backward compatibility) */
1032         if (strstr(before, "%s") || strstr(before, "%T"))
1033         {
1034             /*
1035              * We go through this in order to be able to handle very
1036              * long lists of users and (re)implement %s.
1037              */
1038             nameslen = 0;
1039             for (idp = xmit_names; idp; idp = idp->next)
1040                 if (idp->val.status.mark == XMIT_ACCEPT)
1041                     nameslen += (strlen(idp->id) + 1);  /* string + ' ' */
1042
1043             names = (char *)xmalloc(nameslen + 1);      /* account for '\0' */
1044             names[0] = '\0';
1045             for (idp = xmit_names; idp; idp = idp->next)
1046                 if (idp->val.status.mark == XMIT_ACCEPT)
1047                 {
1048                     strcat(names, idp->id);
1049                     strcat(names, " ");
1050                 }
1051             names[--nameslen] = '\0';   /* chop trailing space */
1052
1053             /* sanitize names in order to contain *only* harmless shell chars */
1054             sanitize(names);
1055         }
1056
1057         /* get From address for %F */
1058         if (strstr(before, "%F"))
1059         {
1060             from = xstrdup(return_path);
1061
1062             /* sanitize from in order to contain *only* harmless shell chars */
1063             sanitize(from);
1064
1065             fromlen = strlen(from);
1066         }
1067
1068         /* do we have to build an mda string? */
1069         if (names || from) {
1070                 
1071                 char    *sp, *dp;
1072
1073
1074                 /* find length of resulting mda string */
1075                 sp = before;
1076                 while (sp = strstr(sp, "%s")) {
1077                         length += nameslen - 2; /* subtract %s */
1078                         sp += 2;
1079                 }
1080                 sp = before;
1081                 while (sp = strstr(sp, "%T")) {
1082                         length += nameslen - 2; /* subtract %T */
1083                         sp += 2;
1084                 }
1085                 sp = before;
1086                 while (sp = strstr(sp, "%F")) {
1087                         length += fromlen - 2;  /* subtract %F */
1088                         sp += 2;
1089                 }
1090                 
1091                 after = xmalloc(length + 1);
1092
1093                 /* copy mda source string to after, while expanding %[sTF] */
1094                 for (dp = after, sp = before; *dp = *sp; dp++, sp++) {
1095                         if (sp[0] != '%')       continue;
1096
1097                         /* need to expand? BTW, no here overflow, because in
1098                         ** the worst case (end of string) sp[1] == '\0' */
1099                         if (sp[1] == 's' || sp[1] == 'T') {
1100                                 strcpy(dp, names);
1101                                 dp += nameslen;
1102                                 sp++;   /* position sp over [sT] */
1103                                 dp--;   /* adjust dp */
1104                         } else if (sp[1] == 'F') {
1105                                 strcpy(dp, from);
1106                                 dp += fromlen;
1107                                 sp++;   /* position sp over F */
1108                                 dp--;   /* adjust dp */
1109                         }
1110                 }
1111
1112                 if (names) {
1113                         free(names);
1114                         names = NULL;
1115                 }
1116                 if (from) {
1117                         free(from);
1118                         from = NULL;
1119                 }
1120
1121                 free(before);
1122
1123                 before = after;
1124         }
1125
1126
1127         if (outlevel == O_VERBOSE)
1128             error(0, 0, "about to deliver with: %s", before);
1129
1130 #ifdef HAVE_SETEUID
1131         /*
1132          * Arrange to run with user's permissions if we're root.
1133          * This will initialize the ownership of any files the
1134          * MDA creates properly.  (The seteuid call is available
1135          * under all BSDs and Linux)
1136          */
1137         seteuid(ctl->uid);
1138 #endif /* HAVE_SETEUID */
1139
1140         sinkfp = popen(before, "w");
1141         free(before);
1142         before = NULL;
1143
1144 #ifdef HAVE_SETEUID
1145         /* this will fail quietly if we didn't start as root */
1146         seteuid(0);
1147 #endif /* HAVE_SETEUID */
1148
1149         if (!sinkfp)
1150         {
1151             error(0, 0, "MDA open failed");
1152             free(headers);
1153             free_str_list(&xmit_names);
1154             return(PS_IOERR);
1155         }
1156
1157         sigchld = signal(SIGCHLD, SIG_DFL);
1158     }
1159     else
1160     {
1161         char    *ap, options[MSGBUFSIZE], addr[128];
1162
1163         /* build a connection to the SMTP listener */
1164         if ((smtp_open(ctl) == -1))
1165         {
1166             error(0, errno, "SMTP connect to %s failed",
1167                   ctl->smtphost ? ctl->smtphost : "localhost");
1168             free(headers);
1169             free_str_list(&xmit_names);
1170             return(PS_SMTP);
1171         }
1172
1173         /*
1174          * Compute ESMTP options.
1175          */
1176         options[0] = '\0';
1177         if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
1178              if (ctl->pass8bits || (mimemsg & MSG_IS_8BIT))
1179                 strcpy(options, " BODY=8BITMIME");
1180              else if (mimemsg & MSG_IS_7BIT)
1181                 strcpy(options, " BODY=7BIT");
1182         }
1183
1184         if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
1185             sprintf(options + strlen(options), " SIZE=%ld", reallen);
1186
1187         /*
1188          * Try to get the SMTP listener to take the Return-Path
1189          * address as MAIL FROM .  If it won't, fall back on the
1190          * calling-user ID.  This won't affect replies, which use the
1191          * header From address anyway.
1192          *
1193          * RFC 1123 requires that the domain name part of the
1194          * MAIL FROM address be "canonicalized", that is a
1195          * FQDN or MX but not a CNAME.  We'll assume the From
1196          * header is already in this form here (it certainly
1197          * is if rewrite is on).  RFC 1123 is silent on whether
1198          * a nonexistent hostname part is considered canonical.
1199          *
1200          * This is a potential problem if the MTAs further upstream
1201          * didn't pass canonicalized From/Return-Path lines, *and* the
1202          * local SMTP listener insists on them.
1203          *
1204          * None of these error conditions generates bouncemail.  Comments
1205          * below explain for each case why this is so.
1206          */
1207         ap = (return_path[0]) ? return_path : user;
1208         if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
1209         {
1210             int smtperr = atoi(smtp_response);
1211
1212             if (str_find(&ctl->antispam, smtperr))
1213             {
1214                 /*
1215                  * SMTP listener explicitly refuses to deliver mail
1216                  * coming from this address, probably due to an
1217                  * anti-spam domain exclusion.  Respect this.  Don't
1218                  * try to ship the message, and don't prevent it from
1219                  * being deleted.  Typical values:
1220                  *
1221                  * 501 = exim's old antispam response
1222                  * 550 = exim's new antispam response (temporary)
1223                  * 553 = sendmail 8.8.7's generic REJECT 
1224                  * 571 = sendmail's "unsolicited email refused"
1225                  *
1226                  * We don't send bouncemail on antispam failures because
1227                  * we don't want the scumbags to know the address is even
1228                  * valid.
1229                  */
1230                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
1231                 free(headers);
1232                 free_str_list(&xmit_names);
1233                 return(PS_REFUSED);
1234             }
1235
1236             /*
1237              * Suppress error message only if the response specifically 
1238              * meant `excluded for policy reasons'.  We *should* see
1239              * an error when the return code is less specific.
1240              */
1241             if (smtperr >= 400)
1242                 error(0, -1, "SMTP error: %s", smtp_response);
1243
1244             switch (smtperr)
1245             {
1246             case 452: /* insufficient system storage */
1247                 /*
1248                  * Temporary out-of-queue-space condition on the
1249                  * ESMTP server.  Don't try to ship the message, 
1250                  * and suppress deletion so it can be retried on
1251                  * a future retrieval cycle. 
1252                  *
1253                  * Bouncemail *might* be appropriate here as a delay
1254                  * notification.  But it's not really necessary because
1255                  * this is not an actual failure, we're very likely to be
1256                  * able to recover on the next cycle.
1257                  */
1258                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
1259                 free(headers);
1260                 free_str_list(&xmit_names);
1261                 return(PS_TRANSIENT);
1262
1263             case 552: /* message exceeds fixed maximum message size */
1264             case 553: /* invalid sending domain */
1265                 /*
1266                  * Permanent no-go condition on the
1267                  * ESMTP server.  Don't try to ship the message, 
1268                  * and allow it to be deleted.
1269                  *
1270                  * Bouncemail would be appropriate for 552, but in these 
1271                  * latter days 553 usually means a spammer is trying to
1272                  * cover his tracks.  We'd rather deny the scumbags any
1273                  * feedback that the address is valid.
1274                  */
1275                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
1276                 free(headers);
1277                 free_str_list(&xmit_names);
1278                 return(PS_REFUSED);
1279
1280             default:    /* retry with invoking user's address */
1281                 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1282                 {
1283                     error(0, -1, "SMTP error: %s", smtp_response);
1284                     free(headers);
1285                     free_str_list(&xmit_names);
1286                     return(PS_SMTP);    /* should never happen */
1287                 }
1288             }
1289         }
1290
1291         /*
1292          * Now list the recipient addressees
1293          *
1294          * RFC 1123 requires that the domain name part of the
1295          * RCPT TO address be "canonicalized", that is a FQDN
1296          * or MX but not a CNAME.  Some listeners (like exim)
1297          * enforce this.
1298          */
1299         destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
1300         
1301         for (idp = xmit_names; idp; idp = idp->next)
1302             if (idp->val.status.mark == XMIT_ACCEPT)
1303             {
1304                 if (strchr(idp->id, '@'))
1305                     strcpy(addr, idp->id);
1306                 else
1307 #ifdef HAVE_SNPRINTF
1308                     snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, destaddr);
1309 #else
1310                     sprintf(addr, "%s@%s", idp->id, destaddr);
1311 #endif /* HAVE_SNPRINTF */
1312
1313                 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1314                     good_addresses++;
1315                 else
1316                 {
1317                     bad_addresses++;
1318                     idp->val.status.mark = XMIT_ANTISPAM;
1319                     error(0, 0, 
1320                           "SMTP listener doesn't like recipient address `%s'",
1321                           addr);
1322                 }
1323             }
1324         if (!good_addresses)
1325         {
1326 #ifdef HAVE_SNPRINTF
1327             snprintf(addr, sizeof(addr)-1, "%s@%s", user, destaddr);
1328 #else
1329             sprintf(addr, "%s@%s", user, destaddr);
1330 #endif /* HAVE_SNPRINTF */
1331
1332             if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1333             {
1334                 error(0, 0, "can't even send to calling user!");
1335                 free(headers);
1336                 free_str_list(&xmit_names);
1337                 return(PS_SMTP);
1338             }
1339         }
1340
1341         /* tell it we're ready to send data */
1342         SMTP_data(ctl->smtp_socket);
1343     }
1344
1345     n = 0;
1346     /*
1347      * Some server/sendmail combinations cause problems when our
1348      * synthetic Received line is before the From header.  Cope
1349      * with this...
1350      */
1351     if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
1352         rcv = headers;
1353     if (rcv > headers)
1354     {
1355         *rcv = '\0';
1356         n = stuffline(ctl, headers);
1357         *rcv = 'R';
1358     }
1359     if (!run.invisible && n != -1)
1360     {
1361         /* utter any per-message Received information we need here */
1362         sprintf(buf, "Received: from %s\n", ctl->server.truename);
1363         n = stuffline(ctl, buf);
1364         if (n != -1)
1365         {
1366             /*
1367              * We used to include ctl->remotename in this log line,
1368              * but this can be secure information that would be bad
1369              * to reveal.
1370              */
1371             sprintf(buf, "\tby fetchmail-%s %s\n",
1372                     RELEASE_ID,
1373                     protocol->name);
1374             n = stuffline(ctl, buf);
1375             if (n != -1)
1376             {
1377                 time_t  now;
1378
1379                 buf[0] = '\t';
1380                 if (good_addresses == 0)
1381                 {
1382                     sprintf(buf+1, 
1383                             "for <%s@%s> (by default); ",
1384                             user, destaddr);
1385                 }
1386                 else if (good_addresses == 1)
1387                 {
1388                     for (idp = xmit_names; idp; idp = idp->next)
1389                         if (idp->val.status.mark == XMIT_ACCEPT)
1390                             break;      /* only report first address */
1391                     if (strchr(idp->id, '@'))
1392                         sprintf(buf+1, "for <%s>", idp->id);
1393                     else
1394                         sprintf(buf+1, "for <%s/%s>", idp->id, destaddr);
1395                     sprintf(buf+strlen(buf), " (%s); ",
1396                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1397                 }
1398                 else
1399                     buf[1] = '\0';
1400
1401                 time(&now);
1402 #ifdef HAVE_STRFTIME
1403                 /*
1404                  * Conform to RFC822.  This is typically going to emit
1405                  * a three-letter timezone for %Z, which is going to
1406                  * be marked "obsolete syntax" in 822bis.  Note that we
1407                  * generate a 4-digit year here.
1408                  */
1409                 strftime(buf + strlen(buf), sizeof(buf) - strlen(buf), 
1410                          "%a, %d %b %Y %H:%M:%S %Z\n", localtime(&now));
1411 #else
1412                 /*
1413                  * This is really just a portability fallback, as the
1414                  * date format ctime(3) emits is not RFC822
1415                  * conformant.
1416                  */
1417                 strcat(buf, ctime(&now));
1418 #endif /* HAVE_STRFTIME */
1419                 n = stuffline(ctl, buf);
1420             }
1421         }
1422     }
1423
1424     if (n != -1)
1425         n = stuffline(ctl, rcv);        /* ship out rest of headers */
1426
1427     if (n == -1)
1428     {
1429         error(0, errno, "writing RFC822 headers");
1430         if (ctl->mda)
1431         {
1432             if (sinkfp)
1433                 pclose(sinkfp);
1434             signal(SIGCHLD, sigchld);
1435         }
1436         free(headers);
1437         free_str_list(&xmit_names);
1438         return(PS_IOERR);
1439     }
1440     else if (!run.use_syslog && outlevel == O_VERBOSE)
1441         fputs("#", stderr);
1442
1443     /* write error notifications */
1444     if (no_local_matches || has_nuls || bad_addresses)
1445     {
1446         int     errlen = 0;
1447         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1448
1449         errmsg = errhd;
1450         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1451         if (no_local_matches)
1452         {
1453             if (reject_count != 1)
1454                 strcat(errhd, "no recipient addresses matched declared local names");
1455             else
1456             {
1457                 for (idp = xmit_names; idp; idp = idp->next)
1458                     if (idp->val.status.mark == XMIT_REJECT)
1459                         break;
1460                 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1461             }
1462         }
1463
1464         if (has_nuls)
1465         {
1466             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1467                 strcat(errhd, "; ");
1468             strcat(errhd, "message has embedded NULs");
1469         }
1470
1471         if (bad_addresses)
1472         {
1473             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1474                 strcat(errhd, "; ");
1475             strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1476             errlen = strlen(errhd);
1477             for (idp = xmit_names; idp; idp = idp->next)
1478                 if (idp->val.status.mark == XMIT_ANTISPAM)
1479                     errlen += strlen(idp->id) + 2;
1480
1481             errmsg = alloca(errlen+3);
1482             (void) strcpy(errmsg, errhd);
1483             for (idp = xmit_names; idp; idp = idp->next)
1484                 if (idp->val.status.mark == XMIT_ANTISPAM)
1485                 {
1486                     strcat(errmsg, idp->id);
1487                     if (idp->next)
1488                         strcat(errmsg, ", ");
1489                 }
1490
1491         }
1492
1493         strcat(errmsg, "\n");
1494
1495         /* ship out the error line */
1496         if (sinkfp)
1497             stuffline(ctl, errmsg);
1498     }
1499
1500     /* issue the delimiter line */
1501     cp = buf;
1502     *cp++ = '\r';
1503     *cp++ = '\n';
1504     *cp++ = '\0';
1505     stuffline(ctl, buf);
1506
1507     free(headers);
1508     free_str_list(&xmit_names);
1509     return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1510 }
1511
1512 static int readbody(sock, ctl, forward, len)
1513 /* read and dispose of a message body presented on sock */
1514 struct query *ctl;      /* query control record */
1515 int sock;               /* to which the server is connected */
1516 int len;                /* length of message */
1517 flag forward;           /* TRUE to forward */
1518 {
1519     int linelen;
1520     unsigned char buf[MSGBUFSIZE+4];
1521     unsigned char *inbufp = buf;
1522     flag issoftline = FALSE;
1523
1524     /* pass through the text lines */
1525     while (protocol->delimited || len > 0)
1526     {
1527         set_timeout(ctl->server.timeout);
1528         if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1529         {
1530             set_timeout(0);
1531             if (ctl->mda)
1532             {
1533                 if (sinkfp)
1534                     pclose(sinkfp);
1535                 signal(SIGCHLD, sigchld);
1536             }
1537             return(PS_SOCKET);
1538         }
1539         set_timeout(0);
1540
1541         /* write the message size dots */
1542         if (linelen > 0)
1543         {
1544             sizeticker += linelen;
1545             while (sizeticker >= SIZETICKER)
1546             {
1547                 if (!run.use_syslog && outlevel > O_SILENT)
1548                     error_build(".");
1549                 sizeticker -= SIZETICKER;
1550             }
1551         }
1552         len -= linelen;
1553
1554         /* check for end of message */
1555         if (protocol->delimited && *inbufp == '.')
1556             if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1557                 break;
1558             else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1559                 break;
1560             else
1561                 msglen--;       /* subtract the size of the dot escape */
1562
1563         msglen += linelen;
1564
1565         if (ctl->mimedecode && (mimemsg & MSG_NEEDS_DECODE)) {
1566             issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1567             if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1568             {
1569                 /*
1570                  * Soft linebreak, but less than 200 bytes left in
1571                  * input buffer. Rather than doing a buffer overrun,
1572                  * ignore the soft linebreak, NL-terminate data and
1573                  * deliver what we have now.
1574                  * (Who writes lines longer than 2K anyway?)
1575                  */
1576                 *inbufp = '\n'; *(inbufp+1) = '\0';
1577                 issoftline = 0;
1578             }
1579         }
1580
1581         /* ship out the text line */
1582         if (forward && (!issoftline))
1583         {
1584             int n;
1585             inbufp = buf;
1586
1587             /* guard against very long lines */
1588             buf[MSGBUFSIZE+1] = '\r';
1589             buf[MSGBUFSIZE+2] = '\n';
1590             buf[MSGBUFSIZE+3] = '\0';
1591
1592             n = stuffline(ctl, buf);
1593
1594             if (n < 0)
1595             {
1596                 error(0, errno, "writing message text");
1597                 if (ctl->mda)
1598                 {
1599                     if (sinkfp)
1600                         pclose(sinkfp);
1601                     signal(SIGCHLD, sigchld);
1602                 }
1603                 return(PS_IOERR);
1604             }
1605             else if (outlevel == O_VERBOSE)
1606                 fputc('*', stderr);
1607         }
1608     }
1609
1610     return(PS_SUCCESS);
1611 }
1612
1613 #ifdef KERBEROS_V4
1614 int
1615 kerberos_auth (socket, canonical) 
1616 /* authenticate to the server host using Kerberos V4 */
1617 int socket;             /* socket to server host */
1618 #ifdef __FreeBSD__
1619 char *canonical;        /* server name */
1620 #else
1621 const char *canonical;  /* server name */
1622 #endif
1623 {
1624     char * host_primary;
1625     KTEXT ticket;
1626     MSG_DAT msg_data;
1627     CREDENTIALS cred;
1628     Key_schedule schedule;
1629     int rem;
1630   
1631     ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1632     rem = (krb_sendauth (0L, socket, ticket, "pop",
1633                          canonical,
1634                          ((char *) (krb_realmofhost (canonical))),
1635                          ((unsigned long) 0),
1636                          (&msg_data),
1637                          (&cred),
1638                          (schedule),
1639                          ((struct sockaddr_in *) 0),
1640                          ((struct sockaddr_in *) 0),
1641                          "KPOPV0.1"));
1642     free (ticket);
1643     if (rem != KSUCCESS)
1644     {
1645         error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1646         return (PS_AUTHFAIL);
1647     }
1648     return (0);
1649 }
1650 #endif /* KERBEROS_V4 */
1651
1652 #ifdef KERBEROS_V5
1653 int
1654 kerberos5_auth(socket, canonical)
1655 /* authernticate to the server host using Kerberos V5 */
1656 int socket;             /* socket to server host */
1657 const char *canonical;  /* server name */
1658 {
1659     krb5_error_code retval;
1660     krb5_context context;
1661     krb5_ccache ccdef;
1662     krb5_principal client = NULL, server = NULL;
1663     krb5_error *err_ret = NULL;
1664
1665     krb5_auth_context auth_context = NULL;
1666
1667     krb5_init_context(&context);
1668     krb5_init_ets(context);
1669     krb5_auth_con_init(context, &auth_context);
1670
1671     if (retval = krb5_cc_default(context, &ccdef)) {
1672         error(0, 0, "krb5_cc_default: %s", error_message(retval));
1673         return(PS_ERROR);
1674     }
1675
1676     if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1677         error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1678         return(PS_ERROR);
1679     }
1680
1681     if (retval = krb5_sname_to_principal(context, canonical, "pop",
1682            KRB5_NT_UNKNOWN,
1683            &server)) {
1684         error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1685         return(PS_ERROR);
1686     }
1687
1688     retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1689          "KPOPV1.0", client, server,
1690          AP_OPTS_MUTUAL_REQUIRED,
1691          NULL,  /* no data to checksum */
1692          0,   /* no creds, use ccache instead */
1693          ccdef,
1694          &err_ret, 0,
1695
1696          NULL); /* don't need reply */
1697
1698     krb5_free_principal(context, server);
1699     krb5_free_principal(context, client);
1700     krb5_auth_con_free(context, auth_context);
1701
1702     if (retval) {
1703       if (err_ret && err_ret->text.length) {
1704           error(0, 0, "krb5_sendauth: %s [server says '%*s'] ",
1705             error_message(retval),
1706             err_ret->text.length,
1707             err_ret->text.data);
1708           krb5_free_error(context, err_ret);
1709       } else
1710           error(0, 0, "krb5_sendauth: %s", error_message(retval));
1711       return(PS_ERROR);
1712     }
1713
1714     return 0;
1715 }
1716 #endif /* KERBEROS_V5 */
1717
1718 int do_protocol(ctl, proto)
1719 /* retrieve messages from server using given protocol method table */
1720 struct query *ctl;              /* parsed options with merged-in defaults */
1721 const struct method *proto;     /* protocol method table */
1722 {
1723     int ok, js, sock = -1;
1724     char *msg;
1725     void (*sigsave)();
1726
1727 #ifndef KERBEROS_V4
1728     if (ctl->server.preauthenticate == A_KERBEROS_V4)
1729     {
1730         error(0, -1, "Kerberos V4 support not linked.");
1731         return(PS_ERROR);
1732     }
1733 #endif /* KERBEROS_V4 */
1734
1735 #ifndef KERBEROS_V5
1736     if (ctl->server.preauthenticate == A_KERBEROS_V5)
1737     {
1738         error(0, -1, "Kerberos V5 support not linked.");
1739         return(PS_ERROR);
1740     }
1741 #endif /* KERBEROS_V5 */
1742
1743     /* lacking methods, there are some options that may fail */
1744     if (!proto->is_old)
1745     {
1746         /* check for unsupported options */
1747         if (ctl->flush) {
1748             error(0, 0,
1749                     "Option --flush is not supported with %s",
1750                     proto->name);
1751             return(PS_SYNTAX);
1752         }
1753         else if (ctl->fetchall) {
1754             error(0, 0,
1755                     "Option --all is not supported with %s",
1756                     proto->name);
1757             return(PS_SYNTAX);
1758         }
1759     }
1760     if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1761     {
1762         error(0, 0,
1763                 "Option --limit is not supported with %s",
1764                 proto->name);
1765         return(PS_SYNTAX);
1766     }
1767
1768     protocol = proto;
1769     pass = 0;
1770     tagnum = 0;
1771     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1772     ok = 0;
1773
1774     /* set up the server-nonresponse timeout */
1775     sigsave = signal(SIGALRM, timeout_handler);
1776     mytimeout = ctl->server.timeout;
1777
1778     if ((js = setjmp(restart)) == 1)
1779     {
1780         if (phase == SERVER_WAIT)
1781             error(0, 0,
1782                   "timeout after %d seconds waiting for server %s.",
1783                   ctl->server.timeout, ctl->server.pollname);
1784         else if (phase == FORWARDING_WAIT)
1785             error(0, 0,
1786                   "timeout after %d seconds waiting for %s.",
1787                   ctl->server.timeout,
1788                   ctl->mda ? "MDA" : "SMTP");
1789         else if (phase == LISTENER_WAIT)
1790             error(0, 0,
1791                   "timeout after %d seconds waiting for listener to respond.");
1792         else
1793             error(0, 0, "timeout after %d seconds.", ctl->server.timeout);
1794
1795         if (ctl->smtp_socket != -1)
1796             close(ctl->smtp_socket);
1797         if (sock != -1)
1798             SockClose(sock);
1799         if (sinkfp)
1800             pclose(sinkfp);
1801         ok = PS_ERROR;
1802     }
1803     else
1804     {
1805         char buf [POPBUFSIZE+1], *realhost;
1806         int *msgsizes, len, num, count, new, bytes, deletions = 0;
1807 #if INET6
1808         int fetches, dispatches;
1809 #else /* INET6 */
1810         int port, fetches, dispatches;
1811 #endif /* INET6 */
1812         struct idlist *idp;
1813
1814         /* execute pre-initialization command, if any */
1815         if (ctl->preconnect && (ok = system(ctl->preconnect)))
1816         {
1817             sprintf(buf, "pre-connection command failed with status %d", ok);
1818             error(0, 0, buf);
1819             ok = PS_SYNTAX;
1820             goto closeUp;
1821         }
1822
1823         /* open a socket to the mail server */
1824 #if !INET6
1825         port = ctl->server.port ? ctl->server.port : protocol->port;
1826 #endif /* !INET6 */
1827         realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1828 #if INET6
1829         if ((sock = SockOpen(realhost, 
1830                              ctl->server.service ? ctl->server.service : protocol->service,
1831                              ctl->server.netsec)) == -1)
1832 #else /* INET6 */
1833         if ((sock = SockOpen(realhost, port, NULL)) == -1)
1834 #endif /* INET6 */
1835         {
1836 #if !INET6
1837 #ifndef EHOSTUNREACH
1838 #define EHOSTUNREACH (-1)
1839 #endif
1840             if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1841             {
1842                 error_build("fetchmail: %s connection to %s failed: ", 
1843                              protocol->name, ctl->server.pollname);
1844 #ifdef HAVE_RES_SEARCH
1845                 if (h_errno == HOST_NOT_FOUND)
1846                     error_complete(0, 0, "host is unknown");
1847                 else if (h_errno == NO_ADDRESS)
1848                     error_complete(0, 0, "name is valid but has no IP address");
1849                 else if (h_errno == NO_RECOVERY)
1850                     error_complete(0, 0, "unrecoverable name server error");
1851                 else if (h_errno == TRY_AGAIN)
1852                     error_complete(0, 0, "temporary name server error");
1853                 else if (h_errno)
1854                     error_complete(0, 0, "unknown DNS error %d", h_errno);
1855                 else
1856 #endif /* HAVE_RES_SEARCH */
1857                     error_complete(0, errno, "local error");
1858             }
1859 #endif /* INET6 */
1860             ok = PS_SOCKET;
1861             goto closeUp;
1862         }
1863
1864 #ifdef KERBEROS_V4
1865         if (ctl->server.preauthenticate == A_KERBEROS_V4)
1866         {
1867             set_timeout(ctl->server.timeout);
1868             ok = kerberos_auth(sock, ctl->server.truename);
1869             set_timeout(0);
1870             if (ok != 0)
1871                 goto cleanUp;
1872         }
1873 #endif /* KERBEROS_V4 */
1874
1875 #ifdef KERBEROS_V5
1876         if (ctl->server.preauthenticate == A_KERBEROS_V5)
1877         {
1878             set_timeout(ctl->server.timeout);
1879             ok = kerberos5_auth(sock, ctl->server.truename);
1880             set_timeout(0);
1881             if (ok != 0)
1882                 goto cleanUp;
1883         }
1884 #endif /* KERBEROS_V5 */
1885
1886         /* accept greeting message from mail server */
1887         ok = (protocol->parse_response)(sock, buf);
1888         if (ok != 0)
1889             goto cleanUp;
1890
1891         /* try to get authorized to fetch mail */
1892         if (protocol->getauth)
1893         {
1894             if (protocol->password_canonify)
1895                 (protocol->password_canonify)(shroud, ctl->password);
1896             else
1897                 strcpy(shroud, ctl->password);
1898
1899             ok = (protocol->getauth)(sock, ctl, buf);
1900             if (ok != 0)
1901             {
1902                 if (ok == PS_LOCKBUSY)
1903                     error(0, -1, "Lock-busy error on %s@%s",
1904                           ctl->remotename,
1905                           ctl->server.truename);
1906                 else
1907                 {
1908                     if (ok == PS_ERROR)
1909                         ok = PS_AUTHFAIL;
1910                     error(0, -1, "Authorization failure on %s@%s", 
1911                           ctl->remotename,
1912                           ctl->server.truename);
1913                 }
1914                 goto cleanUp;
1915             }
1916         }
1917
1918         ctl->errcount = fetches = 0;
1919
1920         /* now iterate over each folder selected */
1921         for (idp = ctl->mailboxes; idp; idp = idp->next)
1922         {
1923             pass = 0;
1924             do {
1925                 dispatches = 0;
1926                 ++pass;
1927
1928                 if (outlevel >= O_VERBOSE)
1929                     if (idp->id)
1930                         error(0, 0, "selecting or re-polling folder %s", idp->id);
1931                     else
1932                         error(0, 0, "selecting or re-polling default folder");
1933
1934                 /* compute # of messages and number of new messages waiting */
1935                 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1936                 if (ok != 0)
1937                     goto cleanUp;
1938
1939                 /* 
1940                  * We need the size of each message before it's
1941                  * loaded in order to pass via the ESMTP SIZE
1942                  * option.  If the protocol has a getsizes method,
1943                  * we presume this means it doesn't get reliable
1944                  * sizes from message fetch responses.
1945                  */
1946                 if (count > 0 && proto->getsizes)
1947                 {
1948                     int i;
1949
1950                     msgsizes = (int *)alloca(sizeof(int) * count);
1951                     for (i = 0; i < count; i++)
1952                         msgsizes[i] = -1;
1953
1954                     ok = (proto->getsizes)(sock, count, msgsizes);
1955                     if (ok != 0)
1956                         goto cleanUp;
1957
1958                     if (bytes == -1)
1959                     {
1960                         bytes = 0;
1961                         for (i = 0; i < count; i++)
1962                             bytes += msgsizes[i];
1963                     }
1964                 }
1965
1966                 /* show user how many messages we downloaded */
1967                 if (idp->id)
1968                     (void) sprintf(buf, "%s at %s (folder %s)",
1969                                    ctl->remotename, ctl->server.truename, idp->id);
1970                 else
1971                     (void) sprintf(buf, "%s at %s",
1972                                    ctl->remotename, ctl->server.truename);
1973                 if (outlevel > O_SILENT)
1974                     if (count == -1)            /* only used for ETRN */
1975                         error(0, 0, "Polling %s", ctl->server.truename);
1976                     else if (count != 0)
1977                     {
1978                         if (new != -1 && (count - new) > 0)
1979                             error_build("%d message%s (%d seen) for %s",
1980                                   count, count > 1 ? "s" : "", count-new, buf);
1981                         else
1982                             error_build("%d message%s for %s", 
1983                                   count, count > 1 ? "s" : "", buf);
1984                         if (bytes == -1)
1985                             error_complete(0, 0, ".");
1986                         else
1987                             error_complete(0, 0, " (%d bytes).", bytes);
1988                     }
1989                     else
1990                     {
1991                         /* these are pointless in normal daemon mode */
1992                         if (pass == 1 && (run.poll_interval == 0 || outlevel == O_VERBOSE))
1993                             error(0, 0, "No mail for %s", buf); 
1994                     }
1995
1996                 /* very important, this is where we leave the do loop */ 
1997                 if (count == 0)
1998                     break;
1999
2000                 if (check_only)
2001                 {
2002                     if (new == -1 || ctl->fetchall)
2003                         new = count;
2004                     ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
2005                     goto cleanUp;
2006                 }
2007                 else if (count > 0)
2008                 {    
2009                     flag        force_retrieval;
2010
2011                     /*
2012                      * What forces this code is that in POP2 and
2013                      * IMAP2bis you can't fetch a message without
2014                      * having it marked `seen'.  In POP3 and IMAP4, on the
2015                      * other hand, you can (peek_capable is set by 
2016                      * each driver module to convey this; it's not a
2017                      * method constant because of the difference between
2018                      * IMAP2bis and IMAP4).
2019                      *
2020                      * The result of being unable to peek is that if there's
2021                      * any kind of transient error (DNS lookup failure, or
2022                      * sendmail refusing delivery due to process-table limits)
2023                      * the message will be marked "seen" on the server without
2024                      * having been delivered.  This is not a big problem if
2025                      * fetchmail is running in foreground, because the user
2026                      * will see a "skipped" message when it next runs and get
2027                      * clued in.
2028                      *
2029                      * But in daemon mode this leads to the message
2030                      * being silently ignored forever.  This is not
2031                      * acceptable.
2032                      *
2033                      * We compensate for this by checking the error
2034                      * count from the previous pass and forcing all
2035                      * messages to be considered new if it's nonzero.
2036                      */
2037                     force_retrieval = !peek_capable && (ctl->errcount > 0);
2038
2039                     /* read, forward, and delete messages */
2040                     for (num = 1; num <= count; num++)
2041                     {
2042                         flag toolarge = NUM_NONZERO(ctl->limit)
2043                             && msgsizes && (msgsizes[num-1] > ctl->limit);
2044                         flag fetch_it = !toolarge 
2045                             && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
2046                         flag suppress_delete = FALSE;
2047                         flag suppress_forward = FALSE;
2048                         flag suppress_readbody = FALSE;
2049                         flag retained = FALSE;
2050
2051                         /*
2052                          * This check copes with Post Office/NT's
2053                          * annoying habit of randomly prepending bogus
2054                          * LIST items of length -1.  Patrick Audley
2055                          * <paudley@pobox.com> tells us: LIST shows a
2056                          * size of -1, RETR and TOP return "-ERR
2057                          * System error - couldn't open message", and
2058                          * DELE succeeds but doesn't actually delete
2059                          * the message.
2060                          */
2061                         if (msgsizes && msgsizes[num-1] == -1)
2062                         {
2063                             if (outlevel >= O_VERBOSE)
2064                                 error(0, 0, 
2065                                       "Skipping message %d, length -1",
2066                                       num - 1);
2067                             continue;
2068                         }
2069
2070                         /* we may want to reject this message if it's old */
2071                         if (!fetch_it)
2072                         {
2073                             if (outlevel > O_SILENT)
2074                             {
2075                                 error_build("skipping message %d", num);
2076                                 if (toolarge)
2077                                     error_build(" (oversized, %d bytes)",
2078                                                 msgsizes[num-1]);
2079                             }
2080                         }
2081                         else
2082                         {
2083                             flag wholesize = !protocol->fetch_body;
2084
2085                             /* request a message */
2086                             ok = (protocol->fetch_headers)(sock,ctl,num, &len);
2087                             if (ok != 0)
2088                                 goto cleanUp;
2089
2090                             /* -1 means we didn't see a size in the response */
2091                             if (len == -1 && msgsizes)
2092                             {
2093                                 len = msgsizes[num - 1];
2094                                 wholesize = TRUE;
2095                             }
2096
2097                             if (outlevel > O_SILENT)
2098                             {
2099                                 error_build("reading message %d of %d",
2100                                             num,count);
2101
2102                                 if (len > 0)
2103                                     error_build(" (%d %sbytes)",
2104                                         len, wholesize ? "" : "header ");
2105                                 if (outlevel == O_VERBOSE)
2106                                     error_complete(0, 0, "");
2107                                 else
2108                                     error_build(" ");
2109                             }
2110
2111                             /* later we'll test for this before closing */
2112                             sinkfp = (FILE *)NULL;
2113
2114                             /* 
2115                              * Read the message headers and ship them to the
2116                              * output sink.  
2117                              */
2118                             ok = readheaders(sock, len, msgsizes[num-1],
2119                                              ctl, num);
2120                             if (ok == PS_RETAINED)
2121                                 suppress_forward = retained = TRUE;
2122                             else if (ok == PS_TRANSIENT)
2123                                 suppress_delete = suppress_forward = TRUE;
2124                             else if (ok == PS_REFUSED)
2125                                 suppress_forward = TRUE;
2126                             else if (ok == PS_TRUNCATED)
2127                                 suppress_readbody = TRUE;
2128                             else if (ok)
2129                                 goto cleanUp;
2130
2131                             /* 
2132                              * If we're using IMAP4 or something else that
2133                              * can fetch headers separately from bodies,
2134                              * it's time to request the body now.  This
2135                              * fetch may be skipped if we got an anti-spam
2136                              * or other PS_REFUSED error response during
2137                              * read_headers.
2138                              */
2139                             if (protocol->fetch_body && !suppress_readbody) 
2140                             {
2141                                 if (outlevel == O_VERBOSE)
2142                                     fputc('\n', stderr);
2143
2144                                 if ((ok = (protocol->trail)(sock, ctl, num)))
2145                                     goto cleanUp;
2146                                 len = 0;
2147                                 if (!suppress_forward)
2148                                 {
2149                                     if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
2150                                         goto cleanUp;
2151                                     if (outlevel > O_SILENT && !wholesize)
2152                                         error_build(" (%d body bytes) ", len);
2153                                 }
2154                             }
2155
2156                             /* process the body now */
2157                             if (len > 0)
2158                             {
2159                                 if (suppress_readbody)
2160                                 {
2161                                   /* When readheaders returns PS_TRUNCATED,
2162                                      the body (which has no content
2163                                      has already been read by readheaders,
2164                                      so we say readbody returned PS_SUCCESS */
2165                                   ok = PS_SUCCESS;
2166                                 }
2167                                 else
2168                                 {
2169                                   ok = readbody(sock,
2170                                                 ctl,
2171                                                 !suppress_forward,
2172                                                 len);
2173                                 }
2174                                 if (ok == PS_TRANSIENT)
2175                                     suppress_delete = suppress_forward = TRUE;
2176                                 else if (ok)
2177                                     goto cleanUp;
2178
2179                                 /* tell server we got it OK and resynchronize */
2180                                 if (protocol->trail)
2181                                 {
2182                                     if (outlevel == O_VERBOSE)
2183                                         fputc('\n', stderr);
2184
2185                                     ok = (protocol->trail)(sock, ctl, num);
2186                                     if (ok != 0)
2187                                         goto cleanUp;
2188                                 }
2189                             }
2190
2191                             /* count # messages forwarded on this pass */
2192                             if (!suppress_forward)
2193                                 dispatches++;
2194
2195                             /*
2196                              * Check to see if the numbers matched?
2197                              *
2198                              * Yes, some servers foo this up horribly.
2199                              * All IMAP servers seem to get it right, and
2200                              * so does Eudora QPOP at least in 2.xx
2201                              * versions.
2202                              *
2203                              * Microsoft Exchange gets it completely
2204                              * wrong, reporting compressed rather than
2205                              * actual sizes (so the actual length of
2206                              * message is longer than the reported size).
2207                              * Another fine example of Microsoft brain death!
2208                              *
2209                              * Some older POP servers, like the old UCB
2210                              * POP server and the pre-QPOP QUALCOMM
2211                              * versions, report a longer size in the LIST
2212                              * response than actually gets shipped up.
2213                              * It's unclear what is going on here, as the
2214                              * QUALCOMM server (at least) seems to be
2215                              * reporting the on-disk size correctly.
2216                              */
2217                             if (msgsizes && msglen != msgsizes[num-1])
2218                             {
2219                                 if (outlevel >= O_VERBOSE)
2220                                     error(0, 0,
2221                                           "message %d was not the expected length (%d != %d)",
2222                                           num, msglen, msgsizes[num-1]);
2223                             }
2224
2225                             /* end-of-message processing starts here */
2226
2227                             if (ctl->mda)
2228                             {
2229                                 int rc;
2230
2231                                 /* close the delivery pipe, we'll reopen before next message */
2232                                 if (sinkfp)
2233                                     rc = pclose(sinkfp);
2234                                 else
2235                                     rc = 0;
2236                                 signal(SIGCHLD, sigchld);
2237                                 if (rc)
2238                                 {
2239                                     error(0, -1, "MDA exited abnormally or returned nonzero status");
2240                                     goto cleanUp;
2241                                 }
2242                             }
2243                             else if (!suppress_forward)
2244                             {
2245                                 /* write message terminator */
2246                                 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
2247                                 {
2248                                     error(0, -1, "SMTP listener refused delivery");
2249                                     ctl->errcount++;
2250                                     suppress_delete = TRUE;
2251                                 }
2252                             }
2253
2254                             fetches++;
2255                         }
2256
2257                         /*
2258                          * At this point in flow of control, either
2259                          * we've bombed on a protocol error or had
2260                          * delivery refused by the SMTP server
2261                          * (unlikely -- I've never seen it) or we've
2262                          * seen `accepted for delivery' and the
2263                          * message is shipped.  It's safe to mark the
2264                          * message seen and delete it on the server
2265                          * now.
2266                          */
2267
2268                         /* tell the UID code we've seen this */
2269                         if (ctl->newsaved)
2270                         {
2271                             struct idlist       *sdp;
2272
2273                             for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2274                                 if (sdp->val.status.num == num)
2275                                     sdp->val.status.mark = UID_SEEN;
2276                         }
2277
2278                         /* maybe we delete this message now? */
2279                         if (retained)
2280                         {
2281                             if (outlevel > O_SILENT) 
2282                                 error_complete(0, 0, " retained");
2283                         }
2284                         else if (protocol->delete
2285                                  && !suppress_delete
2286                                  && (fetch_it ? !ctl->keep : ctl->flush))
2287                         {
2288                             deletions++;
2289                             if (outlevel > O_SILENT) 
2290                                 error_complete(0, 0, " flushed");
2291                             ok = (protocol->delete)(sock, ctl, num);
2292                             if (ok != 0)
2293                                 goto cleanUp;
2294 #ifdef POP3_ENABLE
2295                             delete_str(&ctl->newsaved, num);
2296 #endif /* POP3_ENABLE */
2297                         }
2298                         else if (outlevel > O_SILENT) 
2299                             error_complete(0, 0, " not flushed");
2300
2301                         /* perhaps this as many as we're ready to handle */
2302                         if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
2303                             goto no_error;
2304                     }
2305                 }
2306             } while
2307                   /*
2308                    * Only re-poll if we had some actual forwards, allowed
2309                    * deletions and had no errors.
2310                    * Otherwise it is far too easy to get into infinite loops.
2311                    */
2312                   (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2313         }
2314
2315    no_error:
2316         ok = (protocol->logout_cmd)(sock, ctl);
2317         /*
2318          * Hmmmm...arguably this would be incorrect if we had fetches but
2319          * no dispatches (due to oversized messages, etc.)
2320          */
2321         if (ok == 0)
2322             ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2323         SockClose(sock);
2324         goto closeUp;
2325
2326     cleanUp:
2327         if (ok != 0 && ok != PS_SOCKET)
2328             (protocol->logout_cmd)(sock, ctl);
2329         SockClose(sock);
2330     }
2331
2332     msg = (char *)NULL;         /* sacrifice to -Wall */
2333     switch (ok)
2334     {
2335     case PS_SOCKET:
2336         msg = "socket";
2337         break;
2338     case PS_AUTHFAIL:
2339         msg = "authorization";
2340         break;
2341     case PS_SYNTAX:
2342         msg = "missing or bad RFC822 header";
2343         break;
2344     case PS_IOERR:
2345         msg = "MDA";
2346         break;
2347     case PS_ERROR:
2348         msg = "client/server synchronization";
2349         break;
2350     case PS_PROTOCOL:
2351         msg = "client/server protocol";
2352         break;
2353     case PS_LOCKBUSY:
2354         msg = "lock busy on server";
2355         break;
2356     case PS_SMTP:
2357         msg = "SMTP transaction";
2358         break;
2359     case PS_DNS:
2360         msg = "DNS lookup";
2361         break;
2362     case PS_UNDEFINED:
2363         error(0, 0, "undefined");
2364         break;
2365     }
2366     if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX 
2367                 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL 
2368                 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2369         error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2370
2371 closeUp:
2372     /* execute post-initialization command, if any */
2373     if (ctl->postconnect && (ok = system(ctl->postconnect)))
2374     {
2375         char buf[80];
2376
2377         sprintf(buf, "post-connection command failed with status %d", ok);
2378         error(0, 0, buf);
2379         if (ok == PS_SUCCESS)
2380             ok = PS_SYNTAX;
2381     }
2382
2383     signal(SIGALRM, sigsave);
2384     return(ok);
2385 }
2386
2387 #if defined(HAVE_STDARG_H)
2388 void gen_send(int sock, const char *fmt, ... )
2389 /* assemble command in printf(3) style and send to the server */
2390 #else
2391 void gen_send(sock, fmt, va_alist)
2392 /* assemble command in printf(3) style and send to the server */
2393 int sock;               /* socket to which server is connected */
2394 const char *fmt;        /* printf-style format */
2395 va_dcl
2396 #endif
2397 {
2398     char buf [MSGBUFSIZE+1];
2399     va_list ap;
2400
2401     if (protocol->tagged)
2402         (void) sprintf(buf, "%s ", GENSYM);
2403     else
2404         buf[0] = '\0';
2405
2406 #if defined(HAVE_STDARG_H)
2407     va_start(ap, fmt) ;
2408 #else
2409     va_start(ap);
2410 #endif
2411 #ifdef HAVE_VSNPRINTF
2412     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2413 #else
2414     vsprintf(buf + strlen(buf), fmt, ap);
2415 #endif
2416     va_end(ap);
2417
2418     strcat(buf, "\r\n");
2419     SockWrite(sock, buf, strlen(buf));
2420
2421     if (outlevel == O_VERBOSE)
2422     {
2423         char *cp;
2424
2425         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2426         {
2427             char        *sp;
2428
2429             sp = cp + strlen(shroud);
2430             *cp++ = '*';
2431             while (*sp)
2432                 *cp++ = *sp++;
2433             *cp = '\0';
2434         }
2435         buf[strlen(buf)-2] = '\0';
2436         error(0, 0, "%s> %s", protocol->name, buf);
2437     }
2438 }
2439
2440 int gen_recv(sock, buf, size)
2441 /* get one line of input from the server */
2442 int sock;       /* socket to which server is connected */
2443 char *buf;      /* buffer to receive input */
2444 int size;       /* length of buffer */
2445 {
2446     int oldphase = phase;       /* we don't have to be re-entrant */
2447
2448     phase = SERVER_WAIT;
2449     set_timeout(mytimeout);
2450     if (SockRead(sock, buf, size) == -1)
2451     {
2452         set_timeout(0);
2453         phase = oldphase;
2454         return(PS_SOCKET);
2455     }
2456     else
2457     {
2458         set_timeout(0);
2459         if (buf[strlen(buf)-1] == '\n')
2460             buf[strlen(buf)-1] = '\0';
2461         if (buf[strlen(buf)-1] == '\r')
2462             buf[strlen(buf)-1] = '\0';
2463         if (outlevel == O_VERBOSE)
2464             error(0, 0, "%s< %s", protocol->name, buf);
2465         phase = oldphase;
2466         return(PS_SUCCESS);
2467     }
2468 }
2469
2470 #if defined(HAVE_STDARG_H)
2471 int gen_transact(int sock, char *fmt, ... )
2472 /* assemble command in printf(3) style, send to server, accept a response */
2473 #else
2474 int gen_transact(int sock, fmt, va_alist)
2475 /* assemble command in printf(3) style, send to server, accept a response */
2476 int sock;               /* socket to which server is connected */
2477 const char *fmt;        /* printf-style format */
2478 va_dcl
2479 #endif
2480 {
2481     int ok;
2482     char buf [MSGBUFSIZE+1];
2483     va_list ap;
2484     int oldphase = phase;       /* we don't have to be re-entrant */
2485
2486     phase = SERVER_WAIT;
2487
2488     if (protocol->tagged)
2489         (void) sprintf(buf, "%s ", GENSYM);
2490     else
2491         buf[0] = '\0';
2492
2493 #if defined(HAVE_STDARG_H)
2494     va_start(ap, fmt) ;
2495 #else
2496     va_start(ap);
2497 #endif
2498 #ifdef HAVE_VSNPRINTF
2499     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2500 #else
2501     vsprintf(buf + strlen(buf), fmt, ap);
2502 #endif
2503     va_end(ap);
2504
2505     strcat(buf, "\r\n");
2506     SockWrite(sock, buf, strlen(buf));
2507
2508     if (outlevel == O_VERBOSE)
2509     {
2510         char *cp;
2511
2512         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2513         {
2514             char        *sp;
2515
2516             sp = cp + strlen(shroud);
2517             *cp++ = '*';
2518             while (*sp)
2519                 *cp++ = *sp++;
2520             *cp = '\0';
2521         }
2522         buf[strlen(buf)-1] = '\0';
2523         error(0, 0, "%s> %s", protocol->name, buf);
2524     }
2525
2526     /* we presume this does its own response echoing */
2527     ok = (protocol->parse_response)(sock, buf);
2528
2529     phase = oldphase;
2530     return(ok);
2531 }
2532
2533 /* driver.c ends here */