]> Pileus Git - ~andy/fetchmail/blob - driver.c
Prevent core dumps on messages with no destination lines.
[~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 #if defined(STDC_HEADERS)
15 #include  <stdlib.h>
16 #endif
17 #if defined(HAVE_UNISTD_H)
18 #include <unistd.h>
19 #endif
20 #if defined(HAVE_STDARG_H)
21 #include  <stdarg.h>
22 #else
23 #include  <varargs.h>
24 #endif
25 #if defined(HAVE_ALLOCA_H)
26 #include <alloca.h>
27 #endif
28 #if defined(HAVE_SYS_ITIMER_H)
29 #include <sys/itimer.h>
30 #endif
31 #include  <sys/time.h>
32 #include  <signal.h>
33
34 #ifdef HAVE_GETHOSTBYNAME
35 #include <netdb.h>
36 #include "mx.h"
37 #endif /* HAVE_GETHOSTBYNAME */
38
39 #ifdef SUNOS
40 #include <memory.h>
41 #endif
42
43 #ifdef KERBEROS_V4
44 #if defined (__bsdi__)
45 #include <des.h> /* order of includes matters */
46 #include <krb.h>
47 #define krb_get_err_text(e) (krb_err_txt[e])
48 #else
49 #if defined(__FreeBSD__)
50 #define krb_get_err_text(e) (krb_err_txt[e])
51 #include <krb.h>
52 #include <des.h>
53 #else
54 #include <krb.h>
55 #include <des.h>
56 #endif /* ! defined (__FreeBSD__) */
57 #endif /* ! defined (__bsdi__) */
58 #include <netinet/in.h>
59 #include <netdb.h>
60 #endif /* KERBEROS_V4 */
61 #include  "fetchmail.h"
62 #include  "socket.h"
63 #include  "smtp.h"
64
65 /* BSD portability hack...I know, this is an ugly place to put it */
66 #if !defined(SIGCHLD) && defined(SIGCLD)
67 #define SIGCHLD SIGCLD
68 #endif
69
70 #define SMTP_PORT       25      /* standard SMTP service port */
71
72 extern char *strstr();  /* needed on sysV68 R3V7.1. */
73
74 int fetchlimit;         /* how often to tear down the server connection */
75 int batchcount;         /* count of messages sent in current batch */
76 flag peek_capable;      /* can we peek for better error recovery? */
77
78 static const struct method *protocol;
79 static jmp_buf  restart;
80
81 char tag[TAGLEN];
82 static int tagnum;
83 #define GENSYM  (sprintf(tag, "a%04d", ++tagnum), tag)
84
85 static char *shroud;    /* string to shroud in debug output, if  non-NULL */
86 static int mytimeout;   /* value of nonreponse timeout */
87
88 static void set_timeout(int timeleft)
89 /* reset the nonresponse-timeout */
90 {
91     struct itimerval ntimeout;
92
93     ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
94     ntimeout.it_value.tv_sec  = timeleft;
95     ntimeout.it_value.tv_usec = 0;
96     setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
97 }
98
99 static void timeout_handler (int signal)
100 /* handle server-timeout SIGALRM signal */
101 {
102     longjmp(restart, 1);
103 }
104
105 #define XMIT_ACCEPT             1
106 #define XMIT_REJECT             2
107 #define XMIT_ANTISPAM           3       
108 static int accept_count, reject_count;
109
110 #ifdef HAVE_RES_SEARCH
111 #define MX_RETRIES      3
112
113 static int is_host_alias(const char *name, struct query *ctl)
114 /* determine whether name is a DNS alias of the hostname */
115 {
116     struct hostent      *he;
117     struct mxentry      *mxp, *mxrecords;
118
119     struct hostdata *lead_server = 
120         ctl->server.lead_server ? ctl->server.lead_server : &ctl->server;
121
122     /*
123      * The first two checks are optimizations that will catch a good
124      * many cases.
125      *
126      * (1) check against the `true name' deduced from the poll label
127      * and the via option (if present) at the beginning of the poll cycle.  
128      * Odds are good this will either be the mailserver's FQDN or a suffix of
129      * it with the mailserver's domain's default host name omitted.
130      *
131      * (2) Then check the rest of the `also known as'
132      * cache accumulated by previous DNS checks.  This cache is primed
133      * by the aka list option.
134      *
135      * Any of these on a mail address is definitive.  Only if the
136      * name doesn't match any is it time to call the bind library.
137      * If this happens odds are good we're looking at an MX name.
138      */
139     if (strcmp(lead_server->truename, name) == 0)
140         return(TRUE);
141     else if (str_in_list(&lead_server->akalist, name))
142         return(TRUE);
143     else if (!ctl->server.dns)
144         return(FALSE);
145
146     /*
147      * We know DNS service was up at the beginning of this poll cycle.
148      * If it's down, our nameserver has crashed.  We don't want to try
149      * delivering the current message or anything else from this
150      * mailbox until it's back up.
151      */
152     else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
153     {
154         if (strcmp(ctl->server.truename, he->h_name) == 0)
155             goto match;
156         else
157             return(FALSE);
158     }
159     else
160         switch (h_errno)
161         {
162         case HOST_NOT_FOUND:    /* specified host is unknown */
163         case NO_ADDRESS:        /* valid, but does not have an IP address */
164             break;
165
166         case NO_RECOVERY:       /* non-recoverable name server error */
167         case TRY_AGAIN:         /* temporary error on authoritative server */
168         default:
169             if (outlevel != O_SILENT)
170                 putchar('\n');  /* terminate the progress message */
171             error(0, 0,
172                 "nameserver failure while looking for `%s' during poll of %s.",
173                 name, ctl->server.pollname);
174             ctl->errcount++;
175             break;
176         }
177
178     /*
179      * We're only here if DNS was OK but the gethostbyname() failed
180      * with a HOST_NOT_FOUND or NO_ADDRESS error.
181      * Search for a name match on MX records pointing to the server.
182      */
183     h_errno = 0;
184     if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
185     {
186         switch (h_errno)
187         {
188         case HOST_NOT_FOUND:    /* specified host is unknown */
189         case NO_ADDRESS:        /* valid, but does not have an IP address */
190             return(FALSE);
191             break;
192
193         case NO_RECOVERY:       /* non-recoverable name server error */
194         case TRY_AGAIN:         /* temporary error on authoritative server */
195         default:
196             error(0, 0,
197                 "nameserver failure while looking for `%s' during poll of %s.",
198                 name, ctl->server.pollname);
199             ctl->errcount++;
200             break;
201         }
202     }
203     else
204     {
205         for (mxp = mxrecords; mxp->name; mxp++)
206             if (strcmp(ctl->server.truename, mxp->name) == 0)
207                 goto match;
208         return(FALSE);
209     match:;
210     }
211
212     /* add this name to relevant server's `also known as' list */
213     save_str(&lead_server->akalist, -1, name);
214     return(TRUE);
215 }
216
217 static void map_name(name, ctl, xmit_names)
218 /* add given name to xmit_names if it matches declared localnames */
219 const char *name;               /* name to map */
220 struct query *ctl;              /* list of permissible aliases */
221 struct idlist **xmit_names;     /* list of recipient names parsed out */
222 {
223     const char  *lname;
224
225     lname = idpair_find(&ctl->localnames, name);
226     if (!lname && ctl->wildcard)
227         lname = name;
228
229     if (lname != (char *)NULL)
230     {
231         if (outlevel == O_VERBOSE)
232             error(0, 0, "mapped %s to local %s", name, lname);
233         save_str(xmit_names, XMIT_ACCEPT, lname);
234         accept_count++;
235     }
236 }
237
238 void find_server_names(hdr, ctl, xmit_names)
239 /* parse names out of a RFC822 header into an ID list */
240 const char *hdr;                /* RFC822 header in question */
241 struct query *ctl;              /* list of permissible aliases */
242 struct idlist **xmit_names;     /* list of recipient names parsed out */
243 {
244     if (hdr == (char *)NULL)
245         return;
246     else
247     {
248         char    *cp;
249
250         if ((cp = nxtaddr(hdr)) != (char *)NULL)
251             do {
252                 char    *atsign;
253
254                 if ((atsign = strchr(cp, '@')))
255                 {
256                     struct idlist       *idp;
257
258                     /*
259                      * Does a trailing segment of the hostname match something
260                      * on the localdomains list?  If so, save the whole name
261                      * and keep going.
262                      */
263                     for (idp = ctl->server.localdomains; idp; idp = idp->next)
264                     {
265                         char    *rhs;
266
267                         rhs = atsign + (strlen(atsign) - strlen(idp->id));
268                         if ((rhs[-1] == '.' || rhs[-1] == '@')
269                                         && strcasecmp(rhs, idp->id) == 0)
270                         {
271                             if (outlevel == O_VERBOSE)
272                                 error(0, 0, "passed through %s matching %s", 
273                                       cp, idp->id);
274                             save_str(xmit_names, XMIT_ACCEPT, cp);
275                             accept_count++;
276                             continue;
277                         }
278                     }
279
280                     /*
281                      * Check to see if the right-hand part is an alias
282                      * or MX equivalent of the mailserver.  If it's
283                      * not, skip this name.  If it is, we'll keep
284                      * going and try to find a mapping to a client name.
285                      */
286                     if (!is_host_alias(atsign+1, ctl))
287                     {
288                         save_str(xmit_names, XMIT_REJECT, cp);
289                         reject_count++;
290                         continue;
291                     }
292                     atsign[0] = '\0';
293                 }
294
295                 map_name(cp, ctl, xmit_names);
296             } while
297                 ((cp = nxtaddr((char *)NULL)) != (char *)NULL);
298     }
299 }
300
301 static char *parse_received(struct query *ctl, char *bufp)
302 /* try to extract real addressee from the Received line */
303 {
304     char *ok;
305     static char rbuf[HOSTLEN + USERNAMELEN + 4]; 
306
307     /*
308      * Try to extract the real envelope addressee.  We look here
309      * specifically for the mailserver's Received line.
310      * Note: this will only work for sendmail, or an MTA that
311      * shares sendmail's convention for embedding the envelope
312      * address in the Received line.  Sendmail itself only
313      * does this when the mail has a single recipient.
314      */
315     if ((ok = strstr(bufp, "by ")) == (char *)NULL)
316         ok = (char *)NULL;
317     else
318     {
319         char    *sp, *tp;
320
321         /* extract space-delimited token after "by " */
322         for (sp = ok + 3; isspace(*sp); sp++)
323             continue;
324         tp = rbuf;
325         for (; !isspace(*sp); sp++)
326             *tp++ = *sp;
327         *tp = '\0';
328
329         /*
330          * If it's a DNS name of the mail server, look for the
331          * recipient name after a following "for".  Otherwise
332          * punt.
333          */
334         if (is_host_alias(rbuf, ctl))
335             ok = strstr(sp, "for ");
336         else
337             ok = (char *)NULL;
338     }
339
340     if (ok != 0)
341     {
342         char    *sp, *tp;
343
344         tp = rbuf;
345         sp = ok + 4;
346         if (*sp == '<')
347             sp++;
348         while (*sp && *sp != '>' && *sp != '@' && *sp != ';')
349             if (!isspace(*sp))
350                 *tp++ = *sp++;
351             else
352             {
353                 /* uh oh -- whitespace here can't be right! */
354                 ok = (char *)NULL;
355                 break;
356             }
357         *tp = '\0';
358     }
359
360     if (!ok)
361         return(NULL);
362     else
363     {
364         if (outlevel == O_VERBOSE)
365             error(0, 0, "found Received address `%s'", rbuf);
366         return(rbuf);
367     }
368 }
369 #endif /* HAVE_RES_SEARCH */
370
371 static int smtp_open(struct query *ctl)
372 /* try to open a socket to the appropriate SMTP server for this query */ 
373 {
374     /* maybe it's time to close the socket in order to force delivery */
375     if (ctl->batchlimit > 0 && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
376     {
377         close(ctl->smtp_socket);
378         ctl->smtp_socket = -1;
379         batchcount = 0;
380     }
381
382     /* if no socket to any SMTP host is already set up, try to open one */
383     if (ctl->smtp_socket == -1) 
384     {
385         /* 
386          * RFC 1123 requires that the domain name in HELO address is a
387          * "valid principal domain name" for the client host.  We
388          * violate this with malice aforethought in order to make the
389          * Received headers and logging look right.
390          *
391          * In fact this code relies on the RFC1123 requirement that the
392          * SMTP listener must accept messages even if verification of the
393          * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
394          *
395          * How we compute the true mailhost name to pass to the
396          * listener doesn't affect behavior on RFC1123- violating
397          * listener that check for name match; we're going to lose
398          * on those anyway because we can never give them a name
399          * that matches the local machine fetchmail is running on.
400          * What it will affect is the listener's logging.
401          */
402         struct idlist   *idp;
403
404         /* run down the SMTP hunt list looking for a server that's up */
405         for (idp = ctl->smtphunt; idp; idp = idp->next)
406         {
407             ctl->smtphost = idp->id;  /* remember last host tried. */
408
409             if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
410                 continue;
411
412             if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
413                     SMTP_ehlo(ctl->smtp_socket, 
414                           ctl->server.truename,
415                           &ctl->server.esmtp_options) == SM_OK)
416                break;  /* success */
417
418             /*
419              * RFC 1869 warns that some listeners hang up on a failed EHLO,
420              * so it's safest not to assume the socket will still be good.
421              */
422             close(ctl->smtp_socket);
423             ctl->smtp_socket = -1;
424
425             /* if opening for ESMTP failed, try SMTP */
426             if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
427                 continue;
428
429             if (SMTP_ok(ctl->smtp_socket) == SM_OK && 
430                     SMTP_helo(ctl->smtp_socket, ctl->server.truename) == SM_OK)
431                 break;  /* success */
432
433             close(ctl->smtp_socket);
434             ctl->smtp_socket = -1;
435         }
436     }
437
438     return(ctl->smtp_socket);
439 }
440
441 /* these are shared by stuffline, readheaders and readbody */
442 static FILE *sinkfp;
443 static RETSIGTYPE (*sigchld)();
444 static int sizeticker;
445
446 static int stuffline(struct query *ctl, char *buf, flag delimited)
447 /* ship a line to the given control block's SMTP server */
448 {
449     int n;
450
451     /* fix message lines that have only \n termination (for qmail) */
452     if (ctl->forcecr)
453     {
454         char    *cp = buf + strlen(buf) - 1;
455
456         if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
457         {
458             *cp++ = '\r';
459             *cp++ = '\n';
460             *cp++ = '\0';
461         }
462     }
463
464     /*
465      * SMTP byte-stuffing.  We only do this if the protocol does *not*
466      * use .<CR><LF> as EOM.  If it does, the server will already have
467      * decorated any . lines it sends back up.
468      */
469     if (!delimited && *buf == '.')
470         if (sinkfp && ctl->mda)
471             fputs(".", sinkfp);
472         else if (ctl->smtp_socket != -1)
473             SockWrite(ctl->smtp_socket, buf, 1);
474
475     /* we may need to strip carriage returns */
476     if (ctl->stripcr)
477     {
478         char    *sp, *tp;
479
480         for (sp = tp = buf; *sp; sp++)
481             if (*sp != '\r')
482                 *tp++ =  *sp;
483         *tp = '\0';
484     }
485
486     n = 0;
487     if (ctl->mda)
488         n = fwrite(buf, 1, strlen(buf), sinkfp);
489     else if (ctl->smtp_socket != -1)
490         n = SockWrite(ctl->smtp_socket, buf, strlen(buf));
491
492     return(n);
493 }
494
495 static int readheaders(sock, len, ctl, realname, num)
496 /* read message headers and ship to SMTP or MDA */
497 int sock;               /* to which the server is connected */
498 long len;               /* length of message */
499 struct query *ctl;      /* query control record */
500 char *realname;         /* real name of host */
501 int num;                /* index of message */
502 {
503     struct addrblk
504     {
505         int             offset;
506         struct addrblk  *next;
507     } *addrchain = NULL, **chainptr = &addrchain;
508     char buf[MSGBUFSIZE+1], return_path[MSGBUFSIZE+1]; 
509     int from_offs, ctt_offs, env_offs, next_address;
510     char *headers, *received_for;
511     int n, linelen, oldlen, ch, remaining;
512     char                *cp;
513     struct idlist       *idp, *xmit_names;
514     flag                        good_addresses, bad_addresses, has_nuls;
515 #ifdef HAVE_RES_SEARCH
516     flag                no_local_matches = FALSE;
517 #endif /* HAVE_RES_SEARCH */
518     int                 olderrs;
519
520     next_address = sizeticker = 0;
521     has_nuls = FALSE;
522     return_path[0] = '\0';
523     olderrs = ctl->errcount;
524
525     /* read message headers */
526     headers = received_for = NULL;
527     from_offs = ctt_offs = env_offs = -1;
528     oldlen = 0;
529     for (remaining = len; remaining > 0; remaining -= linelen)
530     {
531         char *line;
532
533         line = xmalloc(sizeof(buf));
534         linelen = 0;
535         line[0] = '\0';
536         do {
537             if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1)
538                 return(PS_SOCKET);
539             linelen += n;
540
541             /* lines may not be properly CRLF terminated; fix this for qmail */
542             if (ctl->forcecr)
543             {
544                 cp = buf + strlen(buf) - 1;
545                 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
546                 {
547                     *cp++ = '\r';
548                     *cp++ = '\n';
549                     *cp++ = '\0';
550                 }
551             }
552
553             set_timeout(ctl->server.timeout);
554             /* leave extra room for reply_hack to play with */
555             line = (char *) realloc(line, strlen(line) + strlen(buf) + HOSTLEN + 1);
556             strcat(line, buf);
557             if (line[0] == '\r' && line[1] == '\n')
558                 break;
559         } while
560             /* we may need to grab RFC822 continuations */
561             ((ch = SockPeek(sock)) == ' ' || ch == '\t');
562
563         /* write the message size dots */
564         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
565         {
566             sizeticker += linelen;
567             while (sizeticker >= SIZETICKER)
568             {
569                 error_build(".");
570                 sizeticker -= SIZETICKER;
571             }
572         }
573
574         if (linelen != strlen(line))
575             has_nuls = TRUE;
576
577         /* check for end of headers; don't save terminating line */
578         if (line[0] == '\r' && line[1] == '\n')
579         {
580             free(line);
581             break;
582         }
583      
584         /* maybe this is a special message that holds mailbox annotations? */ 
585         if (protocol->retain_hdr && protocol->retain_hdr(num, line))
586             return(PS_RETAINED);
587
588         /*
589          * This code prevents fetchmail from becoming an accessory after
590          * the fact to upstream sendmails with the `E' option on.  This
591          * can result in an escaped Unix From_ line at the beginning of
592          * the headers.  If fetchmail just passes it through, the client
593          * listener may think the message has *no* headers (since the first)
594          * line it sees doesn't look RFC822-conformant) and fake up a set.
595          *
596          * What the user would see in this case is bogus (synthesized)
597          * headers, followed by a blank line, followed by the >From, 
598          * followed by the real headers, followed by a blank line,
599          * followed by text.
600          *
601          * We forestall this lossage by tossing anything that looks
602          * like an escaped From_ line in headers.  These aren't RFC822
603          * so our conscience is clear...
604          */
605         if (!strncasecmp(line, ">From ", 6))
606         {
607             free(line);
608             continue;
609         }
610
611         /*
612          * If we see a Status line, it may have been inserted by an MUA
613          * on the mail host, or it may have been inserted by the server
614          * program after the headers in the transaction stream.  This
615          * can actually hose some new-mail notifiers such as xbuffy,
616          * which assumes any Status line came from a *local* MDA and
617          * therefore indicates that the message has been seen.
618          *
619          * Some buggy POP servers (including at least the 3.3(20)
620          * version of the one distributed with IMAP) insert empty
621          * Status lines in the transaction stream; we'll chuck those
622          * unconditionally.  Nonempty ones get chucked if the user
623          * turns on the dropstatus flag.
624          */
625         if (!strncasecmp(line, "Status:", 7))
626         {
627             char        *cp;
628
629             for (cp = line + 7; *cp && isspace(*cp); cp++)
630                 continue;
631
632             if (!*cp || ctl->dropstatus)
633             {
634                 free(line);
635                 continue;
636             }
637         }
638
639         /*
640          * OK, this is messy.  If we're forwarding by SMTP, it's the
641          * SMTP-receiver's job (according to RFC821, page 22, section
642          * 4.1.1) to generate a Return-Path line on final delivery.
643          * The trouble is, we've already got one because the
644          * mailserver's SMTP thought *it* was responsible for final
645          * delivery.
646          *
647          * Stash away the contents of Return-Path for use in generating
648          * MAIL FROM later on, then prevent the header from being saved
649          * with the others.  In effect, we strip it off here.
650          *
651          * If the SMTP server conforms to the standards, and fetchmail gets the
652          * envelope sender from the Return-Path, the new Return-Path should be
653          * exactly the same as the original one.
654          */
655         if (!ctl->mda && !strncasecmp("Return-Path:", line, 12))
656         {
657             strcpy(return_path, nxtaddr(line));
658             free(line);
659             continue;
660         }
661
662         if (ctl->rewrite)
663             reply_hack(line, realname);
664
665         if (!headers)
666         {
667             oldlen = strlen(line);
668             headers = xmalloc(oldlen + 1);
669             (void) strcpy(headers, line);
670             free(line);
671             line = headers;
672         }
673         else
674         {
675             int newlen;
676
677             newlen = oldlen + strlen(line);
678             headers = (char *) realloc(headers, newlen + 1);
679             if (headers == NULL)
680                 return(PS_IOERR);
681             strcpy(headers + oldlen, line);
682             free(line);
683             line = headers + oldlen;
684             oldlen = newlen;
685         }
686
687         if (from_offs == -1 && !strncasecmp("From:", line, 5))
688             from_offs = (line - headers);
689         else if (from_offs == -1 && !strncasecmp("Resent-From:", line, 12))
690             from_offs = (line - headers);
691         else if (from_offs == -1 && !strncasecmp("Apparently-From:", line, 16))
692             from_offs = (line - headers);
693         else if (!strncasecmp("Content-Transfer-Encoding:", line, 26))
694             ctt_offs = (line - headers);
695         else if (!strncasecmp("Message-Id:", buf, 11 ))
696         {
697             if( ctl->server.uidl )
698             {
699                 char id[IDLEN+1];
700                 sscanf( buf+12, "%s", id);
701                 if( !str_in_list( &ctl->newsaved, id ) )
702                     save_str(&ctl->newsaved, num, id );
703             }
704         }
705
706         else if (!MULTIDROP(ctl))
707             continue;
708
709         else if (!strncasecmp("To:", line, 3)
710                         || !strncasecmp("Cc:", line, 3)
711                         || !strncasecmp("Bcc:", line, 4))
712         {
713             *chainptr = xmalloc(sizeof(struct addrblk));
714             (*chainptr)->offset = (line - headers);
715             chainptr = &(*chainptr)->next; 
716             *chainptr = NULL;
717         }
718
719         else if (ctl->server.envelope != STRING_DISABLED)
720         {
721             if (ctl->server.envelope 
722                         && strcasecmp(ctl->server.envelope, "received"))
723             {
724                 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
725                                                 line,
726                                                 strlen(ctl->server.envelope)))
727                     env_offs = (line - headers);
728             }
729 #ifdef HAVE_RES_SEARCH
730             else if (!received_for && !strncasecmp("Received:", line, 9))
731                 received_for = parse_received(ctl, line);
732 #endif /* HAVE_RES_SEARCH */
733         }
734     }
735
736     /*
737      * Hack time.  If the first line of the message was blank, with no headers
738      * (this happens occasionally due to bad gatewaying software) cons up
739      * a set of fake headers.  
740      *
741      * If you modify the fake header template below, be sure you don't
742      * make either From or To address @-less, otherwise the reply_hack
743      * logic will do bad things.
744      */
745     if (headers == (char *)NULL)
746     {
747         sprintf(buf, 
748         "From: <FETCHMAIL-DAEMON@%s>\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
749                 fetchmailhost, user, ctl->remotename, realname);
750         headers = xstrdup(buf);
751     }
752
753     /*
754      * We can now process message headers before reading the text.
755      * In fact we have to, as this will tell us where to forward to.
756      */
757
758     /* cons up a list of local recipients */
759     xmit_names = (struct idlist *)NULL;
760     bad_addresses = good_addresses = accept_count = reject_count = 0;
761 #ifdef HAVE_RES_SEARCH
762     /* is this a multidrop box? */
763     if (MULTIDROP(ctl))
764     {
765         if (env_offs > -1)          /* We have the actual envelope addressee */
766             find_server_names(headers + env_offs, ctl, &xmit_names);
767         else if (received_for)
768             /*
769              * We have the Received for addressee.  
770              * It has to be a mailserver address, or we
771              * wouldn't have got here.
772              */
773             map_name(received_for, ctl, &xmit_names);
774         else
775         {
776             int i;
777
778             /*
779              * We haven't extracted the envelope address.
780              * So check all the header addresses.
781              */
782             while (addrchain)
783             {
784                 register struct addrblk *nextptr;
785
786                 find_server_names(headers+addrchain->offset, ctl, &xmit_names);
787                 nextptr = addrchain->next;
788                 free(addrchain);
789                 addrchain = nextptr;
790             }
791         }
792         if (!accept_count)
793         {
794             no_local_matches = TRUE;
795             save_str(&xmit_names, XMIT_ACCEPT, user);
796             if (outlevel == O_VERBOSE)
797                 error(0, 0, 
798                       "no local matches, forwarding to %s",
799                       user);
800         }
801     }
802     else        /* it's a single-drop box, use first localname */
803 #endif /* HAVE_RES_SEARCH */
804         save_str(&xmit_names, XMIT_ACCEPT, ctl->localnames->id);
805
806
807     /*
808      * Time to either address the message or decide we can't deliver it yet.
809      */
810     if (ctl->errcount > olderrs)        /* there were DNS errors above */
811     {
812         if (outlevel == O_VERBOSE)
813             error(0,0, "forwarding and deletion suppressed due to DNS errors");
814         free(headers);
815         return(PS_TRANSIENT);
816     }
817     else if (ctl->mda)          /* we have a declared MDA */
818     {
819         int     length = 0;
820         char    *names, *cmd;
821
822         /*
823          * We go through this in order to be able to handle very
824          * long lists of users and (re)implement %s.
825          */
826         for (idp = xmit_names; idp; idp = idp->next)
827             if (idp->val.num == XMIT_ACCEPT)
828                 length += (strlen(idp->id) + 1);
829         names = (char *)alloca(length);
830         names[0] = '\0';
831         for (idp = xmit_names; idp; idp = idp->next)
832             if (idp->val.num == XMIT_ACCEPT)
833             {
834                 strcat(names, idp->id);
835                 strcat(names, " ");
836             }
837         cmd = (char *)alloca(strlen(ctl->mda) + length);
838         sprintf(cmd, ctl->mda, names);
839         if (outlevel == O_VERBOSE)
840             error(0, 0, "about to deliver with: %s", cmd);
841
842 #ifdef HAVE_SETEUID
843         /*
844          * Arrange to run with user's permissions if we're root.
845          * This will initialize the ownership of any files the
846          * MDA creates properly.  (The seteuid call is available
847          * under all BSDs and Linux)
848          */
849         seteuid(ctl->uid);
850 #endif /* HAVE_SETEUID */
851
852         sinkfp = popen(cmd, "w");
853
854 #ifdef HAVE_SETEUID
855         /* this will fail quietly if we didn't start as root */
856         seteuid(0);
857 #endif /* HAVE_SETEUID */
858
859         if (!sinkfp)
860         {
861             error(0, -1, "MDA open failed");
862             return(PS_IOERR);
863         }
864
865         sigchld = signal(SIGCHLD, SIG_DFL);
866     }
867     else
868     {
869         char    *ap, *ctt, options[MSGBUFSIZE], addr[128];
870
871         /* build a connection to the SMTP listener */
872         if ((smtp_open(ctl) == -1))
873         {
874             free_str_list(&xmit_names);
875             error(0, -1, "SMTP connect to %s failed",
876                   ctl->smtphost ? ctl->smtphost : "localhost");
877             return(PS_SMTP);
878         }
879
880         /*
881          * Compute ESMTP options.  It's a kluge to use nxtaddr()
882          * here because the contents of the Content-Transfer-Encoding
883          * headers isn't semantically an address.  But it has the
884          * desired tokenizing effect.
885          */
886         options[0] = '\0';
887         if (ctl->server.esmtp_options & ESMTP_8BITMIME)
888             if (ctl->pass8bits)
889                 sprintf(options, " BODY=8BITMIME");
890             else if ((ctt_offs >= 0) && (ctt = nxtaddr(headers + ctt_offs)))
891             {
892                 if (!strcasecmp(ctt,"7BIT"))
893                     sprintf(options, " BODY=7BIT");
894                 else if (!strcasecmp(ctt,"8BIT"))
895                     sprintf(options, " BODY=8BITMIME");
896             }
897         if ((ctl->server.esmtp_options & ESMTP_SIZE))
898             sprintf(options + strlen(options), " SIZE=%ld", len);
899
900         /*
901          * If there is a Return-Path address on the message, this was
902          * almost certainly the MAIL FROM address given the originating
903          * sendmail.  This is the best thing to use for logging the
904          * message origin (it sets up the right behavior for bounces and
905          * mailing lists).  Otherwise, take the From address.
906          *
907          * Try to get the SMTP listener to take the Return-Path or
908          * From address as MAIL FROM .  If it won't, fall back on the
909          * calling-user ID.  This won't affect replies, which use the
910          * header From address anyway.
911          *
912          * RFC 1123 requires that the domain name part of the
913          * MAIL FROM address be "canonicalized", that is a
914          * FQDN or MX but not a CNAME.  We'll assume the From
915          * header is already in this form here (it certainly
916          * is if rewrite is on).  RFC 1123 is silent on whether
917          * a nonexistent hostname part is considered canonical.
918          *
919          * This is a potential problem if the MTAs further upstream
920          * didn't pass canonicalized From/Return-Path lines, *and* the
921          * local SMTP listener insists on them.
922          */
923         ap = (char *)NULL;
924         if (return_path[0])
925             ap = return_path;
926         else if (from_offs == -1 || !(ap = nxtaddr(headers + from_offs)))
927             ap = user;
928         if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
929         {
930             int smtperr = atoi(smtp_response);
931
932             /*
933              * Suppress error message only if the response specifically 
934              * means `excluded for policy reasons'.  We *should* see
935              * an error when the return code is less specific.
936              */
937             if (smtperr >= 400 && smtperr != 571)
938                 error(0, -1, "SMTP error: %s", smtp_response);
939
940             switch (smtperr)
941             {
942             case 571:   /* sendmail's "unsolicited email refused" */
943             case 501:   /* exim's old antispam response */
944             case 550:   /* exim's new antispam response (temporary) */
945                 /*
946                  * SMTP listener explicitly refuses to deliver
947                  * mail coming from this address, probably due
948                  * to an anti-spam domain exclusion.  Respect
949                  * this.  Don't try to ship the message, and
950                  * don't prevent it from being deleted.
951                  */
952                 free(headers);
953                 return(PS_REFUSED);
954
955             case 452: /* insufficient system storage */
956                 /*
957                  * Temporary out-of-queue-space condition on the
958                  * ESMTP server.  Don't try to ship the message, 
959                  * and suppress deletion so it can be retried on
960                  * a future retrieval cycle.
961                  */
962                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
963                 free(headers);
964                 return(PS_TRANSIENT);
965
966             case 552: /* message exceeds fixed maximum message size */
967                 /*
968                  * Permanent no-go condition on the
969                  * ESMTP server.  Don't try to ship the message, 
970                  * and allow it to be deleted.
971                  */
972                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
973                 free(headers);
974                 return(PS_REFUSED);
975
976             default:    /* retry with invoking user's address */
977                 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
978                 {
979                     error(0, -1, "SMTP error: %s", smtp_response);
980                     free(headers);
981                     return(PS_SMTP);    /* should never happen */
982                 }
983             }
984         }
985
986         /*
987          * Now list the recipient addressees
988          *
989          * RFC 1123 requires that the domain name part of the
990          * RCPT TO address be "canonicalized", that is a FQDN
991          * or MX but not a CNAME.  Some listeners (like exim)
992          * enforce this.
993          */
994         for (idp = xmit_names; idp; idp = idp->next)
995             if (idp->val.num == XMIT_ACCEPT)
996             {
997 #ifdef HAVE_SNPRINTF
998                 snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id,ctl->smtphost);
999 #else
1000                 sprintf(addr, "%s@%s", idp->id, ctl->smtphost);
1001 #endif /* HAVE_SNPRINTF */
1002
1003                 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1004                     good_addresses++;
1005                 else
1006                 {
1007                     bad_addresses++;
1008                     idp->val.num = XMIT_ANTISPAM;
1009                     error(0, 0, 
1010                           "SMTP listener doesn't like recipient address `%s'", idp->id);
1011                 }
1012             }
1013         if (!good_addresses)
1014         {
1015 #ifdef HAVE_SNPRINTF
1016             snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, ctl->smtphost);
1017 #else
1018             sprintf(addr, "%s@%s", idp->id, ctl->smtphost);
1019 #endif /* HAVE_SNPRINTF */
1020
1021             if (SMTP_rcpt(ctl->smtp_socket, user) != SM_OK)
1022             {
1023                 error(0, 0, "can't even send to calling user!");
1024                 free(headers);
1025                 return(PS_SMTP);
1026             }
1027         }
1028
1029         /* tell it we're ready to send data */
1030         SMTP_data(ctl->smtp_socket);
1031     }
1032
1033     /* we may need to strip carriage returns */
1034     if (ctl->stripcr)
1035     {
1036         char    *sp, *tp;
1037
1038         for (sp = tp = headers; *sp; sp++)
1039             if (*sp != '\r')
1040                 *tp++ =  *sp;
1041         *tp = '\0';
1042
1043     }
1044
1045     /* write all the headers */
1046     n = 0;
1047     if (ctl->mda && sinkfp)
1048         n = fwrite(headers, 1, strlen(headers), sinkfp);
1049     else if (ctl->smtp_socket != -1)
1050         n = SockWrite(ctl->smtp_socket, headers, strlen(headers));
1051     free(headers);
1052
1053     if (n < 0)
1054     {
1055         error(0, errno, "writing RFC822 headers");
1056         if (ctl->mda)
1057         {
1058             pclose(sinkfp);
1059             signal(SIGCHLD, sigchld);
1060         }
1061         return(PS_IOERR);
1062     }
1063     else if (outlevel == O_VERBOSE)
1064         fputs("#", stderr);
1065
1066     /* write error notifications */
1067 #ifdef HAVE_RES_SEARCH
1068     if (no_local_matches || has_nuls || bad_addresses)
1069 #else
1070     if (has_nuls || bad_addresses)
1071 #endif /* HAVE_RES_SEARCH */
1072     {
1073         int     errlen = 0;
1074         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1075
1076         errmsg = errhd;
1077         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1078 #ifdef HAVE_RES_SEARCH
1079         if (no_local_matches)
1080         {
1081             if (reject_count != 1)
1082                 strcat(errhd, "no recipient addresses matched declared local names");
1083             else
1084             {
1085                 for (idp = xmit_names; idp; idp = idp->next)
1086                     if (idp->val.num == XMIT_REJECT)
1087                         break;
1088                 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1089             }
1090         }
1091 #endif /* HAVE_RES_SEARCH */
1092
1093         if (has_nuls)
1094         {
1095             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1096                 strcat(errhd, "; ");
1097             strcat(errhd, "message has embedded NULs");
1098         }
1099
1100         if (bad_addresses)
1101         {
1102             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1103                 strcat(errhd, "; ");
1104             strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1105             errlen = strlen(errhd);
1106             for (idp = xmit_names; idp; idp = idp->next)
1107                 if (idp->val.num == XMIT_ANTISPAM)
1108                     errlen += strlen(idp->id) + 2;
1109
1110             errmsg = alloca(errlen+3);
1111             (void) strcpy(errmsg, errhd);
1112             for (idp = xmit_names; idp; idp = idp->next)
1113                 if (idp->val.num == XMIT_ANTISPAM)
1114                 {
1115                     strcat(errmsg, idp->id);
1116                     if (idp->next)
1117                         strcat(errmsg, ", ");
1118                 }
1119
1120         }
1121
1122         /* ship out the error line */
1123         if (sinkfp)
1124             stuffline(ctl, errmsg, protocol->delimited);
1125     }
1126
1127     free_str_list(&xmit_names);
1128
1129     /* issue the delimiter line */
1130     cp = buf;
1131     *cp++ = '\r';
1132     *cp++ = '\n';
1133     *cp++ = '\0';
1134     stuffline(ctl, buf, protocol->delimited);
1135
1136     return(PS_SUCCESS);
1137 }
1138
1139 static int readbody(sock, ctl, forward, len, delimited)
1140 /* read and dispose of a message body presented on sock */
1141 struct query *ctl;      /* query control record */
1142 int sock;               /* to which the server is connected */
1143 int len;                /* length of message */
1144 flag forward;           /* TRUE to forward */
1145 flag delimited;         /* does the protocol use a message delimiter? */
1146 {
1147     int linelen;
1148     char buf[MSGBUFSIZE+1], *cp;
1149
1150     /* pass through the text lines */
1151     while (delimited || len > 0)
1152     {
1153         if ((linelen = SockRead(sock, buf, sizeof(buf)-1)) == -1)
1154         {
1155             if (ctl->mda)
1156             {
1157                 pclose(sinkfp);
1158                 signal(SIGCHLD, sigchld);
1159             }
1160             return(PS_SOCKET);
1161         }
1162         set_timeout(ctl->server.timeout);
1163
1164         /* write the message size dots */
1165         if (linelen > 0)
1166         {
1167             sizeticker += linelen;
1168             while (sizeticker >= SIZETICKER)
1169             {
1170                 if (outlevel > O_SILENT)
1171                     error_build(".");
1172                 sizeticker -= SIZETICKER;
1173             }
1174         }
1175         len -= linelen;
1176
1177         /* check for end of message */
1178         if (delimited && *buf == '.')
1179             if (buf[1] == '\r' && buf[2] == '\n' && buf[3] == '\0')
1180                 break;
1181             else if (buf[1] == '\n' && buf[2] == '\0')
1182                 break;
1183
1184         /* ship out the text line */
1185         if (forward)
1186         {
1187             int n = stuffline(ctl, buf, delimited);
1188
1189             if (n < 0)
1190             {
1191                 error(0, errno, "writing message text");
1192                 if (ctl->mda)
1193                 {
1194                     pclose(sinkfp);
1195                     signal(SIGCHLD, sigchld);
1196                 }
1197                 return(PS_IOERR);
1198             }
1199             else if (outlevel == O_VERBOSE)
1200                 fputc('*', stderr);
1201         }
1202     }
1203
1204     return(PS_SUCCESS);
1205 }
1206
1207 #ifdef KERBEROS_V4
1208 int
1209 kerberos_auth (socket, canonical) 
1210 /* authenticate to the server host using Kerberos V4 */
1211 int socket;             /* socket to server host */
1212 #ifdef __FreeBSD__
1213 char *canonical;        /* server name */
1214 #else
1215 const char *canonical;  /* server name */
1216 #endif
1217 {
1218     char * host_primary;
1219     KTEXT ticket;
1220     MSG_DAT msg_data;
1221     CREDENTIALS cred;
1222     Key_schedule schedule;
1223     int rem;
1224   
1225     ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1226     rem = (krb_sendauth (0L, socket, ticket, "pop",
1227                          canonical,
1228                          ((char *) (krb_realmofhost (canonical))),
1229                          ((unsigned long) 0),
1230                          (&msg_data),
1231                          (&cred),
1232                          (schedule),
1233                          ((struct sockaddr_in *) 0),
1234                          ((struct sockaddr_in *) 0),
1235                          "KPOPV0.1"));
1236     free (ticket);
1237     if (rem != KSUCCESS)
1238     {
1239         error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1240         return (PS_ERROR);
1241     }
1242     return (0);
1243 }
1244 #endif /* KERBEROS_V4 */
1245
1246 int do_protocol(ctl, proto)
1247 /* retrieve messages from server using given protocol method table */
1248 struct query *ctl;              /* parsed options with merged-in defaults */
1249 const struct method *proto;     /* protocol method table */
1250 {
1251     int ok, js, pst, sock = -1;
1252     char *msg, *cp, realname[HOSTLEN];
1253     void (*sigsave)();
1254
1255 #ifndef KERBEROS_V4
1256     if (ctl->server.preauthenticate == A_KERBEROS_V4)
1257     {
1258         error(0, -1, "Kerberos V4 support not linked.");
1259         return(PS_ERROR);
1260     }
1261 #endif /* KERBEROS_V4 */
1262
1263     /* lacking methods, there are some options that may fail */
1264     if (!proto->is_old)
1265     {
1266         /* check for unsupported options */
1267         if (ctl->flush) {
1268             error(0, 0,
1269                     "Option --flush is not supported with %s",
1270                     proto->name);
1271             return(PS_SYNTAX);
1272         }
1273         else if (ctl->fetchall) {
1274             error(0, 0,
1275                     "Option --all is not supported with %s",
1276                     proto->name);
1277             return(PS_SYNTAX);
1278         }
1279     }
1280     if (!proto->getsizes && ctl->limit)
1281     {
1282         error(0, 0,
1283                 "Option --limit is not supported with %s",
1284                 proto->name);
1285         return(PS_SYNTAX);
1286     }
1287
1288     protocol = proto;
1289     tagnum = 0;
1290     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1291     ok = 0;
1292     error_init(poll_interval == 0 && !logfile);
1293
1294     /* set up the server-nonresponse timeout */
1295     sigsave = signal(SIGALRM, timeout_handler);
1296     set_timeout(mytimeout = ctl->server.timeout);
1297
1298     if ((js = setjmp(restart)) == 1)
1299     {
1300         error(0, 0,
1301                 "timeout after %d seconds waiting for %s.",
1302                 ctl->server.timeout, ctl->server.pollname);
1303         if (ctl->smtp_socket != -1)
1304             close(ctl->smtp_socket);
1305         if (sock != -1)
1306             close(sock);
1307         ok = PS_ERROR;
1308     }
1309     else
1310     {
1311         char buf [POPBUFSIZE+1], *sp, *realhost;
1312         int *msgsizes, len, num, count, new, deletions = 0;
1313         int port, fetches;
1314         struct idlist *idp;
1315
1316         /* execute pre-initialization command, if any */
1317         if (ctl->preconnect && (ok = system(ctl->preconnect)))
1318         {
1319             sprintf(buf, "pre-connection command failed with status %d", ok);
1320             error(0, 0, buf);
1321             ok = PS_SYNTAX;
1322             goto closeUp;
1323         }
1324
1325         /* open a socket to the mail server */
1326         port = ctl->server.port ? ctl->server.port : protocol->port;
1327         realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1328         if ((sock = SockOpen(realhost, port)) == -1)
1329         {
1330 #ifndef EHOSTUNREACH
1331 #define EHOSTUNREACH (-1)
1332 #endif
1333             if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1334             {
1335                 error_build("fetchmail: %s connection to %s failed: ", 
1336                              protocol->name, ctl->server.pollname);
1337                 if (h_errno == HOST_NOT_FOUND)
1338                     error_complete(0, 0, "host is unknown");
1339                 else if (h_errno == NO_ADDRESS)
1340                     error_complete(0, 0, "name is valid but has no IP address");
1341                 else if (h_errno == NO_RECOVERY)
1342                     error_complete(0, 0, "unrecoverable name server error");
1343                 else if (h_errno == TRY_AGAIN)
1344                     error_complete(0, 0, "temporary name server error");
1345                 else if (h_errno)
1346                     error_complete(0, 0, "unknown DNS error %d", h_errno);
1347                 else
1348                     error_complete(0, errno, "local error");
1349             }
1350             ok = PS_SOCKET;
1351             goto closeUp;
1352         }
1353
1354 #ifdef KERBEROS_V4
1355         if (ctl->server.preauthenticate == A_KERBEROS_V4)
1356         {
1357             ok = kerberos_auth(sock, ctl->server.truename);
1358             if (ok != 0)
1359                 goto cleanUp;
1360             set_timeout(ctl->server.timeout);
1361         }
1362 #endif /* KERBEROS_V4 */
1363
1364         /* accept greeting message from mail server */
1365         ok = (protocol->parse_response)(sock, buf);
1366         if (ok != 0)
1367             goto cleanUp;
1368         set_timeout(ctl->server.timeout);
1369
1370         /*
1371          * Try to parse the host's actual name out of the greeting
1372          * message.  We do this so that the progress messages will
1373          * make sense even if the connection is indirected through
1374          * ssh. *Do* use this for hacking reply headers, but *don't*
1375          * use it for error logging, as the names in the log should
1376          * correlate directly back to rc file entries.
1377          *
1378          * This assumes that the first space-delimited token found
1379          * that contains at least two dots (with the characters on
1380          * each side of the dot alphanumeric to exclude version
1381          * numbers) is the hostname.  The hostname candidate may not
1382          * contain @ -- if it does it's probably a mailserver
1383          * maintainer's name.  If no such token is found, fall back on
1384          * the .fetchmailrc id.
1385          */
1386         pst = 0;
1387         sp = (char *)NULL;      /* sacrifice to -Wall */
1388         for (cp = buf; *cp; cp++)
1389         {
1390             switch (pst)
1391             {
1392             case 0:             /* skip to end of current token */
1393                 if (*cp == ' ')
1394                     pst = 1;
1395                 break;
1396
1397             case 1:             /* look for blank-delimited token */
1398                 if (*cp != ' ')
1399                 {
1400                     sp = cp;
1401                     pst = 2;
1402                 }
1403                 break;
1404
1405             case 2:             /* look for first dot */
1406                 if (*cp == '@')
1407                     pst = 0;
1408                 else if (*cp == ' ')
1409                     pst = 1;
1410                 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1411                     pst = 3;
1412                 break;
1413
1414             case 3:             /* look for second dot */
1415                 if (*cp == '@')
1416                     pst = 0;
1417                 else if (*cp == ' ')
1418                     pst = 1;
1419                 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1420                     pst = 4;
1421                 break;
1422
1423             case 4:             /* look for trailing space */
1424                 if (*cp == '@')
1425                     pst = 0;
1426                 else if (*cp == ' ')
1427                 {
1428                     pst = 5;
1429                     goto done;
1430                 }
1431                 break;
1432             }
1433         }
1434     done:
1435         if (pst == 5)
1436         {
1437             char        *tp = realname;
1438
1439             while (sp < cp)
1440                 *tp++ = *sp++;
1441             *tp = '\0';
1442         }
1443         else
1444             strcpy(realname, ctl->server.pollname);
1445
1446         /* try to get authorized to fetch mail */
1447         if (protocol->getauth)
1448         {
1449             shroud = ctl->password;
1450             ok = (protocol->getauth)(sock, ctl, buf);
1451             shroud = (char *)NULL;
1452             if (ok != 0)
1453             {
1454                 if (ok == PS_LOCKBUSY)
1455                     error(0, -1, "Lock-busy error on %s@%s",
1456                           ctl->remotename,
1457                           realname);
1458                 else
1459                 {
1460                     if (ok == PS_ERROR)
1461                         ok = PS_AUTHFAIL;
1462                     error(0, -1, "Authorization failure on %s@%s", 
1463                           ctl->remotename,
1464                           realname);
1465                 }
1466                 goto cleanUp;
1467             }
1468             set_timeout(ctl->server.timeout);
1469         }
1470
1471         ctl->errcount = fetches = 0;
1472
1473         /* now iterate over each folder selected */
1474         for (idp = ctl->mailboxes; idp; idp = idp->next)
1475         {
1476             if (outlevel >= O_VERBOSE)
1477                 if (idp->next)
1478                     error(0, 0, "selecting folder %s");
1479                 else
1480                     error(0, 0, "selecting default folder");
1481
1482             /* compute number of messages and number of new messages waiting */
1483             ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new);
1484             if (ok != 0)
1485                 goto cleanUp;
1486             set_timeout(ctl->server.timeout);
1487
1488             /* show user how many messages we downloaded */
1489             if (idp->id)
1490                 (void) sprintf(buf, "%s@%s:%s",
1491                                ctl->remotename, realname, idp->id);
1492             else
1493                 (void) sprintf(buf, "%s@%s", ctl->remotename, realname);
1494             if (outlevel > O_SILENT)
1495                 if (count == -1)                /* only used for ETRN */
1496                     error(0, 0, "Polling %s", buf);
1497                 else if (count == 0)
1498                 {
1499                     /* these are pointless in normal daemon mode */
1500                     if (poll_interval == 0 || outlevel == O_VERBOSE )
1501                         error(0, 0, "No mail at %s", buf); 
1502                 }
1503                 else
1504                 {
1505                     if (new != -1 && (count - new) > 0)
1506                         error(0, 0, "%d message%s (%d seen) at %s.",
1507                               count, count > 1 ? "s" : "", count-new, buf);
1508                     else
1509                         error(0, 0, "%d message%s at %s.", 
1510                               count, count > 1 ? "s" : "", buf);
1511                 }
1512
1513             if (check_only)
1514             {
1515                 if (new == -1 || ctl->fetchall)
1516                     new = count;
1517                 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1518                 goto cleanUp;
1519             }
1520             else if (count > 0)
1521             {    
1522                 flag    force_retrieval;
1523
1524                 /*
1525                  * What forces this code is that in POP3 and IMAP2BIS you can't
1526                  * fetch a message without having it marked `seen'.  In IMAP4,
1527                  * on the other hand, you can (peek_capable is set to convey
1528                  * this).
1529                  *
1530                  * The result of being unable to peek is that if there's
1531                  * any kind of transient error (DNS lookup failure, or
1532                  * sendmail refusing delivery due to process-table limits)
1533                  * the message will be marked "seen" on the server without
1534                  * having been delivered.  This is not a big problem if
1535                  * fetchmail is running in foreground, because the user
1536                  * will see a "skipped" message when it next runs and get
1537                  * clued in.
1538                  *
1539                  * But in daemon mode this leads to the message being silently
1540                  * ignored forever.  This is not acceptable.
1541                  *
1542                  * We compensate for this by checking the error count from the 
1543                  * previous pass and forcing all messages to be considered new
1544                  * if it's nonzero.
1545                  */
1546                 force_retrieval = !peek_capable && (ctl->errcount > 0);
1547
1548                 /*
1549                  * We may need to get sizes in order to check message
1550                  * limits.  Or it may be forced because the fetch methods
1551                  * don't return reliable sizes.
1552                  */
1553                 msgsizes = (int *)NULL;
1554                 if (proto->getsizes && (proto->force_getsizes || ctl->limit > 0))
1555                 {
1556                     msgsizes = (int *)alloca(sizeof(int) * count);
1557
1558                     ok = (proto->getsizes)(sock, count, msgsizes);
1559                     if (ok != 0)
1560                         goto cleanUp;
1561                     set_timeout(ctl->server.timeout);
1562                 }
1563
1564                 /* read, forward, and delete messages */
1565                 for (num = 1; num <= count; num++)
1566                 {
1567                     flag toolarge = (ctl->limit > 0)
1568                         && msgsizes && (msgsizes[num-1] > ctl->limit);
1569                     flag fetch_it = !toolarge 
1570                         && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
1571                     flag suppress_delete = FALSE;
1572                     flag suppress_forward = FALSE;
1573                     flag retained = FALSE;
1574
1575                     /* we may want to reject this message if it's old */
1576                     if (!fetch_it)
1577                     {
1578                         if (outlevel > O_SILENT)
1579                         {
1580                             error_build("skipping message %d", num);
1581                             if (toolarge)
1582                                 error_build(" (oversized, %d bytes)", msgsizes[num-1]);
1583                         }
1584                     }
1585                     else
1586                     {
1587                         flag wholesize = !protocol->fetch_body;
1588
1589                         /* request a message */
1590                         ok = (protocol->fetch_headers)(sock, ctl, num, &len);
1591                         if (ok != 0)
1592                             goto cleanUp;
1593                         set_timeout(ctl->server.timeout);
1594
1595                         /* -1 means we didn't see a size in the response */
1596                         if (len == -1 && msgsizes)
1597                         {
1598                             len = msgsizes[num - 1];
1599                             wholesize = TRUE;
1600                         }
1601
1602                         if (outlevel > O_SILENT)
1603                         {
1604                             error_build("reading message %d of %d",num,count);
1605
1606                             if (len > 0)
1607                                 error_build(" (%d %sbytes)",
1608                                             len, wholesize ? "" : "header ");
1609                             if (outlevel == O_VERBOSE)
1610                                 error_complete(0, 0, "");
1611                             else
1612                                 error_build(" ");
1613                         }
1614
1615                         /* 
1616                          * Read the message headers and ship them to the
1617                          * output sink.  
1618                          */
1619                         ok = readheaders(sock, len, ctl, realname, num);
1620                         if (ok == PS_RETAINED)
1621                             suppress_forward = retained = TRUE;
1622                         else if (ok == PS_TRANSIENT)
1623                             suppress_delete = suppress_forward = TRUE;
1624                         else if (ok == PS_REFUSED)
1625                             suppress_forward = TRUE;
1626                         else if (ok)
1627                             goto cleanUp;
1628                         set_timeout(ctl->server.timeout);
1629
1630                         /* 
1631                          * If we're using IMAP4 or something else that
1632                          * can fetch headers separately from bodies,
1633                          * it's time to request the body now.  This
1634                          * fetch may be skipped if we got an anti-spam
1635                          * or other PS_REFUSED error response during
1636                          * read_headers.
1637                          */
1638                         if (protocol->fetch_body) 
1639                         {
1640                             if ((ok = (protocol->trail)(sock, ctl, num)))
1641                                 goto cleanUp;
1642                             set_timeout(ctl->server.timeout);
1643                             len = 0;
1644                             if (!suppress_forward)
1645                             {
1646                                 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1647                                     goto cleanUp;
1648                                 if (outlevel > O_SILENT && !msgsizes)
1649                                     error_build(" (%d body bytes) ", len);
1650                                 set_timeout(ctl->server.timeout);
1651                             }
1652                         }
1653
1654                         /* process the body now */
1655                         if (len > 0)
1656                         {
1657                             ok = readbody(sock,
1658                                           ctl,
1659                                           !suppress_forward,
1660                                           len,
1661                                           protocol->delimited);
1662                             if (ok == PS_TRANSIENT)
1663                                 suppress_delete = suppress_forward = TRUE;
1664                             else if (ok)
1665                                 goto cleanUp;
1666                             set_timeout(ctl->server.timeout);
1667
1668                             /* tell server we got it OK and resynchronize */
1669                             if (protocol->trail)
1670                             {
1671                                 ok = (protocol->trail)(sock, ctl, num);
1672                                 if (ok != 0)
1673                                     goto cleanUp;
1674                                 set_timeout(ctl->server.timeout);
1675                             }
1676                         }
1677
1678                         /* end-of-message processing starts here */
1679                         if (outlevel == O_VERBOSE)
1680                             fputc('\n', stderr);
1681
1682                         if (ctl->mda)
1683                         {
1684                             int rc;
1685
1686                             /* close the delivery pipe, we'll reopen before next message */
1687                             rc = pclose(sinkfp);
1688                             signal(SIGCHLD, sigchld);
1689                             if (rc)
1690                             {
1691                                 error(0, -1, "MDA exited abnormally or returned nonzero status");
1692                                 goto cleanUp;
1693                             }
1694                         }
1695                         else if (!suppress_forward)
1696                         {
1697                             /* write message terminator */
1698                             if (SMTP_eom(ctl->smtp_socket) != SM_OK)
1699                             {
1700                                 error(0, -1, "SMTP listener refused delivery");
1701                                 ctl->errcount++;
1702                                 suppress_delete = TRUE;
1703                             }
1704                         }
1705
1706                         fetches++;
1707                     }
1708
1709                     /*
1710                      * At this point in flow of control, either we've bombed
1711                      * on a protocol error or had delivery refused by the SMTP
1712                      * server (unlikely -- I've never seen it) or we've seen
1713                      * `accepted for delivery' and the message is shipped.
1714                      * It's safe to mark the message seen and delete it on the
1715                      * server now.
1716                      */
1717
1718                     /* maybe we delete this message now? */
1719                     if (retained)
1720                     {
1721                         if (outlevel > O_SILENT) 
1722                             error_complete(0, 0, " retained");
1723                     }
1724                     else if (protocol->delete
1725                         && !suppress_delete
1726                         && (fetch_it ? !ctl->keep : ctl->flush))
1727                     {
1728                         deletions++;
1729                         if (outlevel > O_SILENT) 
1730                             error_complete(0, 0, " flushed");
1731                         ok = (protocol->delete)(sock, ctl, num);
1732                         if (ok != 0)
1733                             goto cleanUp;
1734                         set_timeout(ctl->server.timeout);
1735                         delete_str(&ctl->newsaved, num);
1736                     }
1737                     else if (outlevel > O_SILENT) 
1738                         error_complete(0, 0, " not flushed");
1739
1740                     /* perhaps this as many as we're ready to handle */
1741                     if (ctl->fetchlimit > 0 && ctl->fetchlimit <= fetches)
1742                         goto no_error;
1743                 }
1744             }
1745         }
1746
1747    no_error:
1748         set_timeout(ctl->server.timeout);
1749         ok = gen_transact(sock, protocol->exit_cmd);
1750         if (ok == 0)
1751             ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1752         set_timeout(0);
1753         close(sock);
1754         goto closeUp;
1755
1756     cleanUp:
1757         set_timeout(ctl->server.timeout);
1758         if (ok != 0 && ok != PS_SOCKET)
1759             gen_transact(sock, protocol->exit_cmd);
1760         set_timeout(0);
1761         close(sock);
1762     }
1763
1764     msg = (char *)NULL;         /* sacrifice to -Wall */
1765     switch (ok)
1766     {
1767     case PS_SOCKET:
1768         msg = "socket";
1769         break;
1770     case PS_AUTHFAIL:
1771         msg = "authorization";
1772         break;
1773     case PS_SYNTAX:
1774         msg = "missing or bad RFC822 header";
1775         break;
1776     case PS_IOERR:
1777         msg = "MDA";
1778         break;
1779     case PS_ERROR:
1780         msg = "client/server synchronization";
1781         break;
1782     case PS_PROTOCOL:
1783         msg = "client/server protocol";
1784         break;
1785     case PS_LOCKBUSY:
1786         msg = "lock busy on server";
1787         break;
1788     case PS_SMTP:
1789         msg = "SMTP transaction";
1790         break;
1791     case PS_UNDEFINED:
1792         error(0, 0, "undefined");
1793         break;
1794     }
1795     if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX 
1796                 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL 
1797                 || ok==PS_LOCKBUSY || ok==PS_SMTP)
1798         error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
1799
1800 closeUp:
1801     /* execute post-initialization command, if any */
1802     if (ctl->postconnect && (ok = system(ctl->postconnect)))
1803     {
1804         char buf[80];
1805
1806         sprintf(buf, "post-connection command failed with status %d", ok);
1807         error(0, 0, buf);
1808         if (ok == PS_SUCCESS)
1809             ok = PS_SYNTAX;
1810     }
1811
1812     signal(SIGALRM, sigsave);
1813     return(ok);
1814 }
1815
1816 #if defined(HAVE_STDARG_H)
1817 void gen_send(int sock, char *fmt, ... )
1818 /* assemble command in printf(3) style and send to the server */
1819 #else
1820 void gen_send(sock, fmt, va_alist)
1821 /* assemble command in printf(3) style and send to the server */
1822 int sock;               /* socket to which server is connected */
1823 const char *fmt;        /* printf-style format */
1824 va_dcl
1825 #endif
1826 {
1827     char buf [POPBUFSIZE+1];
1828     va_list ap;
1829
1830     if (protocol->tagged)
1831         (void) sprintf(buf, "%s ", GENSYM);
1832     else
1833         buf[0] = '\0';
1834
1835 #if defined(HAVE_STDARG_H)
1836     va_start(ap, fmt) ;
1837 #else
1838     va_start(ap);
1839 #endif
1840 #ifdef HAVE_VSNPRINTF
1841     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
1842 #else
1843     vsprintf(buf + strlen(buf), fmt, ap);
1844 #endif
1845     va_end(ap);
1846
1847     strcat(buf, "\r\n");
1848     SockWrite(sock, buf, strlen(buf));
1849
1850     if (outlevel == O_VERBOSE)
1851     {
1852         char *cp;
1853
1854         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
1855         {
1856             char        *sp;
1857
1858             sp = cp + strlen(shroud);
1859             *cp++ = '*';
1860             while (*sp)
1861                 *cp++ = *sp++;
1862             *cp = '\0';
1863         }
1864         buf[strlen(buf)-2] = '\0';
1865         error(0, 0, "%s> %s", protocol->name, buf);
1866     }
1867 }
1868
1869 int gen_recv(sock, buf, size)
1870 /* get one line of input from the server */
1871 int sock;       /* socket to which server is connected */
1872 char *buf;      /* buffer to receive input */
1873 int size;       /* length of buffer */
1874 {
1875     if (SockRead(sock, buf, size) == -1)
1876         return(PS_SOCKET);
1877     else
1878     {
1879         if (buf[strlen(buf)-1] == '\n')
1880             buf[strlen(buf)-1] = '\0';
1881         if (buf[strlen(buf)-1] == '\r')
1882             buf[strlen(buf)-1] = '\r';
1883         if (outlevel == O_VERBOSE)
1884             error(0, 0, "%s< %s", protocol->name, buf);
1885         return(PS_SUCCESS);
1886     }
1887 }
1888
1889 #if defined(HAVE_STDARG_H)
1890 int gen_transact(int sock, char *fmt, ... )
1891 /* assemble command in printf(3) style, send to server, accept a response */
1892 #else
1893 int gen_transact(int sock, fmt, va_alist)
1894 /* assemble command in printf(3) style, send to server, accept a response */
1895 int sock;               /* socket to which server is connected */
1896 const char *fmt;        /* printf-style format */
1897 va_dcl
1898 #endif
1899 {
1900     int ok;
1901     char buf [POPBUFSIZE+1];
1902     va_list ap;
1903
1904     if (protocol->tagged)
1905         (void) sprintf(buf, "%s ", GENSYM);
1906     else
1907         buf[0] = '\0';
1908
1909 #if defined(HAVE_STDARG_H)
1910     va_start(ap, fmt) ;
1911 #else
1912     va_start(ap);
1913 #endif
1914 #ifdef HAVE_VSNPRINTF
1915     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
1916 #else
1917     vsprintf(buf + strlen(buf), fmt, ap);
1918 #endif
1919     va_end(ap);
1920
1921     strcat(buf, "\r\n");
1922     SockWrite(sock, buf, strlen(buf));
1923
1924     if (outlevel == O_VERBOSE)
1925     {
1926         char *cp;
1927
1928         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
1929         {
1930             char        *sp;
1931
1932             sp = cp + strlen(shroud);
1933             *cp++ = '*';
1934             while (*sp)
1935                 *cp++ = *sp++;
1936             *cp = '\0';
1937         }
1938         buf[strlen(buf)-1] = '\0';
1939         error(0, 0, "%s> %s", protocol->name, buf);
1940     }
1941
1942     /* we presume this does its own response echoing */
1943     ok = (protocol->parse_response)(sock, buf);
1944     set_timeout(mytimeout);
1945
1946     return(ok);
1947 }
1948
1949 /* driver.c ends here */