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