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