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