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