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