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