]> Pileus Git - ~andy/fetchmail/blob - driver.c
Comment fix.
[~andy/fetchmail] / driver.c
1 /*
2  * driver.c -- generic driver for mail fetch method protocols
3  *
4  * Copyright 1996 by Eric S. Raymond
5  * All rights reserved.
6  * For license terms, see the file COPYING in this directory.
7  */
8
9 #include  <config.h>
10 #include  <stdio.h>
11 #include  <setjmp.h>
12 #include  <errno.h>
13 #include  <ctype.h>
14 #include  <string.h>
15 #if defined(STDC_HEADERS)
16 #include  <stdlib.h>
17 #endif
18 #if defined(HAVE_UNISTD_H)
19 #include <unistd.h>
20 #endif
21 #if defined(HAVE_STDARG_H)
22 #include  <stdarg.h>
23 #else
24 #include  <varargs.h>
25 #endif
26 #if defined(HAVE_ALLOCA_H)
27 #include <alloca.h>
28 #endif
29 #include  <sys/time.h>
30 #include  <signal.h>
31
32 #ifdef HAVE_GETHOSTBYNAME
33 #include <netdb.h>
34 #include "mx.h"
35 #endif /* HAVE_GETHOSTBYNAME */
36
37 #ifdef KERBEROS_V4
38 #include <krb.h>
39 #include <des.h>
40 #include <netinet/in.h>
41 #include <netdb.h>
42 #endif /* KERBEROS_V4 */
43 #include  "socket.h"
44 #include  "fetchmail.h"
45 #include  "socket.h"
46 #include  "smtp.h"
47
48 /* BSD portability hack...I know, this is an ugly place to put it */
49 #if !defined(SIGCHLD) && defined(SIGCLD)
50 #define SIGCHLD SIGCLD
51 #endif
52
53 #define SMTP_PORT       25      /* standard SMTP service port */
54
55 extern char *strstr();  /* needed on sysV68 R3V7.1. */
56
57 int batchlimit;         /* how often to tear down the delivery connection */
58 int fetchlimit;         /* how often to tear down the server connection */
59 int batchcount;         /* count of messages sent in current batch */
60 int peek_capable;       /* can we peek for better error recovery? */
61
62 static const struct method *protocol;
63 static jmp_buf  restart;
64
65 char tag[TAGLEN];
66 static int tagnum;
67 #define GENSYM  (sprintf(tag, "a%04d", ++tagnum), tag)
68
69 static char *shroud;    /* string to shroud in debug output, if  non-NULL */
70 static int mytimeout;   /* value of nonreponse timeout */
71
72 static void vtalarm(int timeleft)
73 /* reset the nonresponse-timeout */
74 {
75     struct itimerval ntimeout;
76
77     ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
78     ntimeout.it_value.tv_sec  = timeleft;
79     ntimeout.it_value.tv_usec = 0;
80     setitimer(ITIMER_VIRTUAL, &ntimeout, (struct itimerval *)NULL);
81 }
82
83 static void vtalarm_handler (int signal)
84 /* handle server-timeout SIGVTALARM signal */
85 {
86     longjmp(restart, 1);
87 }
88
89 #ifdef HAVE_RES_SEARCH
90 #define MX_RETRIES      3
91
92 static int is_host_alias(const char *name, struct query *ctl)
93 /* determine whether name is a DNS alias of the hostname */
94 {
95     struct hostent      *he;
96     struct mxentry      *mxp, *mxrecords;
97
98     /*
99      * The first two checks are optimizations that will catch a good
100      * many cases.  (1) check against the hostname the user
101      * specified.  Odds are good this will either be the mailserver's
102      * FQDN or a suffix of it with the mailserver's domain's default
103      * host name omitted.  Then check the rest of the `also known as'
104      * cache accumulated by previous DNS checks.  This cache is primed
105      * by the aka list option.
106      *
107      * (2) check against the mailserver's FQDN, in case
108      * it's not the same as the declared hostname.
109      *
110      * Either of these on a mail address is definitive.  Only if the
111      * name doesn't match either is it time to call the bind library.
112      * If this happens odds are good we're looking at an MX name.
113      */
114     if (str_in_list(&ctl->server.lead_server->names, name))
115         return(TRUE);
116     else if (strcmp(name, ctl->server.canonical_name) == 0)
117         return(TRUE);
118     else if (ctl->server.no_dns)
119         return(FALSE);
120
121     /*
122      * We know DNS service was up at the beginning of this poll cycle.
123      * If it's down, our nameserver has crashed.  We don't want to try
124      * delivering the current message or anything else from this
125      * mailbox until it's back up.
126      */
127     else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
128     {
129         if (strcmp(ctl->server.canonical_name, he->h_name) == 0)
130             goto match;
131         else
132             return(FALSE);
133     }
134     else
135         switch (h_errno)
136         {
137         case HOST_NOT_FOUND:    /* specified host is unknown */
138         case NO_ADDRESS:        /* valid, but does not have an IP address */
139             break;
140
141         case NO_RECOVERY:       /* non-recoverable name server error */
142         case TRY_AGAIN:         /* temporary error on authoritative server */
143         default:
144             if (outlevel != O_SILENT)
145                 putchar('\n');  /* terminate the progress message */
146             error(0, 0,
147                 "nameserver failure while looking for `%s' during poll of %s.",
148                 name, ctl->server.names->id);
149             ctl->errcount++;
150             longjmp(restart, 2);        /* try again next poll cycle */
151             break;
152         }
153
154     /*
155      * We're only here if DNS was OK but the gethostbyname() failed
156      * with a HOST_NOT_FOUND or NO_ADDRESS error.
157      * Search for a name match on MX records pointing to the server.
158      */
159     h_errno = 0;
160     if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
161     {
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             return(FALSE);
167             break;
168
169         case NO_RECOVERY:       /* non-recoverable name server error */
170         case TRY_AGAIN:         /* temporary error on authoritative server */
171         default:
172             error(0, 0,
173                 "nameserver failure while looking for `%s' during poll of %s.",
174                 name, ctl->server.names->id);
175             ctl->errcount++;
176             longjmp(restart, 2);        /* try again next poll cycle */
177             break;
178         }
179     }
180     else
181     {
182         for (mxp = mxrecords; mxp->name; mxp++)
183             if (strcmp(ctl->server.canonical_name, mxp->name) == 0)
184                 goto match;
185         return(FALSE);
186     match:;
187     }
188
189     /* add this name to relevant server's `also known as' list */
190     save_str(&ctl->server.lead_server->names, -1, name);
191     return(TRUE);
192 }
193
194 static void map_name(name, ctl, xmit_names)
195 /* add given name to xmit_names if it matches declared localnames */
196 const char *name;               /* name to map */
197 struct query *ctl;              /* list of permissible aliases */
198 struct idlist **xmit_names;     /* list of recipient names parsed out */
199 {
200     const char  *lname;
201
202     lname = idpair_find(&ctl->localnames, name);
203     if (!lname && ctl->wildcard)
204         lname = name;
205
206     if (lname != (char *)NULL)
207     {
208         if (outlevel == O_VERBOSE)
209             error(0, 0, "mapped %s to local %s", name, lname);
210         save_str(xmit_names, -1, lname);
211     }
212 }
213
214 void find_server_names(hdr, ctl, xmit_names)
215 /* parse names out of a RFC822 header into an ID list */
216 const char *hdr;                /* RFC822 header in question */
217 struct query *ctl;              /* list of permissible aliases */
218 struct idlist **xmit_names;     /* list of recipient names parsed out */
219 {
220     if (hdr == (char *)NULL)
221         return;
222     else
223     {
224         char    *cp, *lname;
225
226         if ((cp = nxtaddr(hdr)) != (char *)NULL)
227             do {
228                 char    *atsign;
229
230                 if ((atsign = strchr(cp, '@')))
231                 {
232                     struct idlist       *idp;
233
234                     /*
235                      * Does a trailing segment of the hostname match something
236                      * on the localdomains list?  If so, save the whole name
237                      * and keep going.
238                      */
239                     for (idp = ctl->server.localdomains; idp; idp = idp->next)
240                     {
241                         char    *rhs;
242
243                         rhs = atsign + 1 + (strlen(atsign) - strlen(idp->id));
244                         if ((rhs[-1] == '.' || rhs[-1] == '@')
245                                         && strcmp(rhs, idp->id) == 0)
246                         {
247                             if (outlevel == O_VERBOSE)
248                                 error(0, 0, "passed through %s matching %s", 
249                                       cp, idp->id);
250                             save_str(xmit_names, -1, cp);
251                             continue;
252                         }
253                     }
254
255                     /*
256                      * Check to see if the right-hand part is an alias
257                      * or MX equivalent of the mailserver.  If it's
258                      * not, skip this name.  If it is, we'll keep
259                      * going and try to find a mapping to a client name.
260                      */
261                     if (!is_host_alias(atsign+1, ctl))
262                         continue;
263                     atsign[0] = '\0';
264                 }
265
266                 map_name(cp, ctl, xmit_names);
267             } while
268                 ((cp = nxtaddr((char *)NULL)) != (char *)NULL);
269     }
270 }
271
272 char *parse_received(struct query *ctl, char *bufp)
273 /* try to extract */
274 {
275     char *ok;
276     static char rbuf[HOSTLEN + USERNAMELEN + 4]; 
277
278     /*
279      * Try to extract the real envelope addressee.  We look here
280      * specifically for the mailserver's Received line.
281      * Note: this will only work for sendmail, or an MTA that
282      * shares sendmail's convention for embedding the envelope
283      * address in the Received line.  Sendmail itself only
284      * does this when the mail has a single recipient.
285      */
286     if ((ok = strstr(bufp, "by ")) == (char *)NULL)
287         ok = (char *)NULL;
288     else
289     {
290         char    *sp, *tp;
291
292         /* extract space-delimited token after "by " */
293         tp = rbuf;
294         for (sp = ok + 3; !isspace(*sp); sp++)
295             *tp++ = *sp;
296         *tp = '\0';
297
298         /*
299          * If it's a DNS name of the mail server, look for the
300          * recipient name after a following "for".  Otherwise
301          * punt.
302          */
303         if (is_host_alias(rbuf, ctl))
304             ok = strstr(sp, "for ");
305         else
306             ok = (char *)NULL;
307     }
308
309     if (ok != 0)
310     {
311         char    *sp, *tp;
312
313         tp = rbuf;
314         sp = ok + 4;
315         if (*sp == '<')
316             sp++;
317         while (*sp && *sp != '>' && *sp != '@' && *sp != ';')
318             if (!isspace(*sp))
319                 *tp++ = *sp++;
320             else
321             {
322                 /* uh oh -- whitespace here can't be right! */
323                 ok = (char *)NULL;
324                 break;
325             }
326         *tp = '\0';
327     }
328
329     if (!ok)
330         return(NULL);
331     else
332     {
333         if (outlevel == O_VERBOSE)
334             error(0, 0, "found Received address `%s'", rbuf);
335         return(rbuf);
336     }
337 }
338 #endif /* HAVE_RES_SEARCH */
339
340 static FILE *smtp_open(struct query *ctl)
341 /* try to open a socket to the appropriate SMTP server for this query */ 
342 {
343     struct query *lead;
344
345     lead = ctl->lead_smtp; /* go to the SMTP leader for this query */
346
347     /* maybe it's time to close the socket in order to force delivery */
348     if (batchlimit && lead->smtp_sockfp && batchcount++ == batchlimit)
349     {
350         fclose(lead->smtp_sockfp);
351         lead->smtp_sockfp = (FILE *)NULL;
352         batchcount = 0;
353     }
354
355     /* 
356      * RFC 1123 requires that the domain name in HELO address is a
357      * "valid principal domain name" for the client host.  We
358      * violate this with malice aforethought in order to make the
359      * Received headers and logging look right.
360      *
361      * In fact this code relies on the RFC1123 requirement that the
362      * SMTP listener must accept messages even if verification of the
363      * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
364      */
365
366     /* if no socket to this host is already set up, try to open ESMTP */
367     if (lead->smtp_sockfp == (FILE *)NULL)
368     {
369         if ((lead->smtp_sockfp = SockOpen(lead->smtphost, SMTP_PORT)) == (FILE *)NULL)
370             return((FILE *)NULL);
371         else if (SMTP_ok(lead->smtp_sockfp) != SM_OK
372                  || SMTP_ehlo(lead->smtp_sockfp, 
373                               ctl->server.names->id,
374                               &lead->server.esmtp_options) != SM_OK)
375         {
376             /*
377              * RFC 1869 warns that some listeners hang up on a failed EHLO,
378              * so it's safest not to assume the socket will still be good.
379              */
380             fclose(lead->smtp_sockfp);
381             lead->smtp_sockfp = (FILE *)NULL;
382         }
383     }
384
385     /* if opening for ESMTP failed, try SMTP */
386     if (lead->smtp_sockfp == (FILE *)NULL)
387     {
388         if ((lead->smtp_sockfp = SockOpen(lead->smtphost, SMTP_PORT)) == (FILE *)NULL)
389             return((FILE *)NULL);
390         else if (SMTP_ok(lead->smtp_sockfp) != SM_OK
391                  || SMTP_helo(lead->smtp_sockfp, ctl->server.names->id) != SM_OK)
392         {
393             fclose(lead->smtp_sockfp);
394             lead->smtp_sockfp = (FILE *)NULL;
395         }
396     }
397
398     return(lead->smtp_sockfp);
399 }
400
401 static int gen_readmsg(sockfp, len, delimited, ctl, realname)
402 /* read message content and ship to SMTP or MDA */
403 FILE *sockfp;           /* to which the server is connected */
404 long len;               /* length of message */
405 int delimited;          /* does the protocol use a message delimiter? */
406 struct query *ctl;      /* query control record */
407 char *realname;         /* real name of host */
408 {
409     char buf [MSGBUFSIZE+1]; 
410     char *bufp, *headers, *fromhdr,*tohdr,*cchdr,*bcchdr,*received_for,*envto;
411     char *fromptr, *toptr, *ctthdr;
412     int n, oldlen, ch;
413     int inheaders, sizeticker, delete_ok;
414     FILE *sinkfp;
415     RETSIGTYPE (*sigchld)();
416 #ifdef HAVE_GETHOSTBYNAME
417     char rbuf[HOSTLEN + USERNAMELEN + 4]; 
418 #endif /* HAVE_GETHOSTBYNAME */
419
420     /* read the message content from the server */
421     inheaders = delete_ok = TRUE;
422     headers = fromhdr = tohdr = cchdr = bcchdr = received_for = envto = ctthdr = NULL;
423     sizeticker = 0;
424     oldlen = 0;
425     while (delimited || len > 0)
426     {
427         buf[0] = '\0';
428         do {
429             if (!SockGets(buf+strlen(buf), sizeof(buf)-strlen(buf)-1, sockfp))
430                 return(PS_SOCKET);
431             vtalarm(ctl->server.timeout);
432         } while
433             /* we may need to grab RFC822 continuations */
434             (inheaders && (ch = SockPeek(sockfp)) == ' ' || ch == '\t');
435
436         /* write the message size dots */
437         if ((n = strlen(buf)) > 0)
438         {
439             sizeticker += n;
440             while (sizeticker >= SIZETICKER)
441             {
442                 if (outlevel > O_SILENT)
443                     error_build(".");
444                 sizeticker -= SIZETICKER;
445             }
446         }
447         len -= n;
448         bufp = buf;
449         if (buf[0] == '\r' && buf[1] == '\n')
450             inheaders = FALSE;
451         if (delimited && *bufp == '.') {
452             if (bufp[1] == '\r' && bufp[2] == '\n')
453                 break;  /* end of message */
454         }
455      
456         if (inheaders)
457         {
458             if (!ctl->no_rewrite)
459                 reply_hack(bufp, realname);
460
461             if (!headers)
462             {
463                 oldlen = strlen(bufp);
464                 headers = xmalloc(oldlen + 1);
465                 (void) strcpy(headers, bufp);
466                 bufp = headers;
467             }
468             else
469             {
470                 int     newlen;
471
472                 newlen = oldlen + strlen(bufp);
473                 headers = realloc(headers, newlen + 1);
474                 if (headers == NULL)
475                     return(PS_IOERR);
476                 strcpy(headers + oldlen, bufp);
477                 bufp = headers + oldlen;
478                 oldlen = newlen;
479             }
480
481             if (!fromhdr && !strncasecmp("From:", bufp, 5))
482                 fromhdr = bufp;
483             else if (!fromhdr && !strncasecmp("Resent-From:", bufp, 12))
484                 fromhdr = bufp;
485             else if (!fromhdr && !strncasecmp("Apparently-From:", bufp, 16))
486                 fromhdr = bufp;
487
488             else if (!strncasecmp("To:", bufp, 3))
489                 tohdr = bufp;
490
491             else if (!envto && !strncasecmp("Apparently-To:", bufp, 14))
492                 envto = bufp;
493             else if (!envto && !strncasecmp(ctl->server.envelope, bufp, 14))
494                 envto = bufp;
495
496             else if (!strncasecmp("Cc:", bufp, 3))
497                 cchdr = bufp;
498
499             else if (!strncasecmp("Bcc:", bufp, 4))
500                 bcchdr = bufp;
501
502             else if (!strncasecmp("Content-Transfer-Encoding:", bufp, 26))
503                 ctthdr = bufp;
504
505 #ifdef HAVE_RES_SEARCH
506             else if (MULTIDROP(ctl) && !strncasecmp("Received:", bufp, 9))
507                 received_for = parse_received(ctl, bufp);
508 #endif /* HAVE_RES_SEARCH */
509
510             if (len > 0)
511                 continue;
512         } /* if (inheaders) */
513
514         if (headers && (!inheaders || len == 0))    /* at end of headers now */
515         {
516             char                *cp;
517             struct idlist       *idp, *xmit_names;
518             int                 good_addresses, bad_addresses;
519 #ifdef HAVE_RES_SEARCH
520             int                 no_local_matches = FALSE;
521 #endif /* HAVE_RES_SEARCH */
522
523             /* cons up a list of local recipients */
524             xmit_names = (struct idlist *)NULL;
525             bad_addresses = good_addresses = 0;
526 #ifdef HAVE_RES_SEARCH
527             /* is this a multidrop box? */
528             if (MULTIDROP(ctl))
529             {
530                 if (envto)          /* We have the actual envelope addressee */
531                     find_server_names(envto, ctl, &xmit_names);
532                 else if (received_for)
533                     /*
534                      * We have the Received for addressee.  
535                      * It has to be a mailserver address, or we
536                      * wouldn't have got here.
537                      */
538                     map_name(received_for, ctl, &xmit_names);
539                 else
540                 {
541                     /*
542                      * We haven't extracted the envelope address.
543                      * So check all the header addresses.
544                      */
545                     find_server_names(tohdr,  ctl, &xmit_names);
546                     find_server_names(cchdr,  ctl, &xmit_names);
547                     find_server_names(bcchdr, ctl, &xmit_names);
548                 }
549                 if (!xmit_names)
550                 {
551                     no_local_matches = TRUE;
552                     save_str(&xmit_names, -1, user);
553                     if (outlevel == O_VERBOSE)
554                         error(0, 0, 
555                                 "no local matches, forwarding to %s",
556                                 user);
557                 }
558             }
559             else        /* it's a single-drop box, use first localname */
560 #endif /* HAVE_RES_SEARCH */
561                 save_str(&xmit_names, -1, ctl->localnames->id);
562
563             /* time to address the message */
564             if (ctl->mda)       /* we have a declared MDA */
565             {
566                 int     length = 0;
567                 char    *names, *cmd;
568
569                 /*
570                  * We go through this in order to be able to handle very
571                  * long lists of users and (re)implement %s.
572                  */
573                 for (idp = xmit_names; idp; idp = idp->next)
574                     length += (strlen(idp->id) + 1);
575                 names = (char *)alloca(length);
576                 names[0] = '\0';
577                 for (idp = xmit_names; idp; idp = idp->next)
578                 {
579                     strcat(names, idp->id);
580                     strcat(names, " ");
581                 }
582                 cmd = (char *)alloca(strlen(ctl->mda) + length);
583                 sprintf(cmd, ctl->mda, names);
584                 if (outlevel == O_VERBOSE)
585                     error(0, 0, "about to deliver with: %s", cmd);
586
587 #ifdef HAVE_SETEUID
588                 /*
589                  * Arrange to run with user's permissions if we're root.
590                  * This will initialize the ownership of any files the
591                  * MDA creates properly.  (The seteuid call is available
592                  * under all BSDs and Linux)
593                  */
594                 seteuid(ctl->uid);
595 #endif /* HAVE_SETEUID */
596
597                 sinkfp = popen(cmd, "w");
598
599 #ifdef HAVE_SETEUID
600                 /* this will fail quietly if we didn't start as root */
601                 seteuid(0);
602 #endif /* HAVE_SETEUID */
603
604                 if (!sinkfp)
605                 {
606                     error(0, 0, "MDA open failed");
607                     return(PS_IOERR);
608                 }
609
610                 sigchld = signal(SIGCHLD, SIG_DFL);
611             }
612             else
613             {
614                 char    *ap, *ctt, options[MSGBUFSIZE];
615                 int     smtperr;
616
617                 /* build a connection to the SMTP listener */
618                 if (!ctl->mda && ((sinkfp = smtp_open(ctl)) == NULL))
619                 {
620                     free_str_list(&xmit_names);
621                     error(0, 0, "SMTP connect failed");
622                     return(PS_SMTP);
623                 }
624
625                 /*
626                  * Compute ESMTP options.  It's a kluge to use nxtaddr()
627                  * here because the contents of the Content-Transfer-Encoding
628                  * headers isn't semantically an address.  But it has the
629                  * desired tokenizing effect.
630                  */
631                 options[0] = '\0';
632                 if ((ctl->server.esmtp_options & ESMTP_8BITMIME)
633                         && ctthdr
634                         && (ctt = nxtaddr(ctthdr))
635                         && (!strcasecmp(ctt,"7BIT")||!strcasecmp(ctt,"8BIT")))
636                     sprintf(options, " BODY=%s", ctt);
637                 if ((ctl->server.esmtp_options & ESMTP_SIZE) && !delimited)
638                     sprintf(options + strlen(options), " SIZE=%d", len);
639
640                 /*
641                  * Try to get the SMTP listener to take the header
642                  * From address as MAIL FROM (this makes the logging
643                  * nicer).  If it won't, fall back on the calling-user
644                  * ID.  This won't affect replies, which use the header
645                  * From address anyway.
646                  *
647                  * RFC 1123 requires that the domain name part of the
648                  * MAIL FROM address be "canonicalized", that is a
649                  * FQDN or MX but not a CNAME.  We'll assume the From
650                  * header is already in this form here (it certainly
651                  * is if rewrite is on).  RFC 1123 is silent on whether
652                  * a nonexistent hostname part is considered canonical.
653                  *
654                  * This is a potential problem if the MTAs further
655                  * upstream didn't pass canonicalized From lines, *and*
656                  * the local SMTP listener insists on them.
657                  */
658                 if (!fromhdr || !(ap = nxtaddr(fromhdr)))
659                     ap = user;
660                 if (SMTP_from(sinkfp, ap, options) != SM_OK)
661                 {
662                     int smtperr = atoi(smtp_response);
663
664                     if (smtperr >= 400)
665                         error(0, 0, "SMTP error: %s", smtp_response);
666
667                     /*
668                      * There'a one problem with this flow of control;
669                      * there's no way to avoid reading the whole message
670                      * off the server, even if the MAIL FROM response 
671                      * tells us that it's just to be discarded.  We could
672                      * fix this under IMAP by reading headers first, then
673                      * trying to issue the MAIL FROM, and *then* reading
674                      * the body...but POP3 can't do this.
675                      */
676
677                     switch (smtperr)
678                     {
679                     case 571: /* unsolicited email refused */
680                         /*
681                          * SMTP listener explicitly refuses to deliver
682                          * mail coming from this address, probably due
683                          * to an anti-spam domain exclusion.  Respect
684                          * this.  Don't try to ship the message, and
685                          * don't prevent it from being deleted.
686                          */
687                         sinkfp = (FILE *)NULL;
688                         goto skiptext;
689
690                     case 452: /* insufficient system storage */
691                         /*
692                          * Temporary out-of-queue-space condition on the
693                          * ESMTP server.  Don't try to ship the message, 
694                          * and suppress deletion so it can be retried on
695                          * a future retrieval cycle.
696                          */
697                         delete_ok = FALSE;
698                         sinkfp = (FILE *)NULL;
699                         SMTP_rset(sockfp);      /* required by RFC1870 */
700                         goto skiptext;
701
702                     case 552: /* message exceeds fixed maximum message size */
703                         /*
704                          * Permanent no-go condition on the
705                          * ESMTP server.  Don't try to ship the message, 
706                          * and allow it to be deleted.
707                          */
708                         sinkfp = (FILE *)NULL;
709                         SMTP_rset(sockfp);      /* required by RFC1870 */
710                         goto skiptext;
711
712                     default:    /* retry with invoking user's address */
713                         if (SMTP_from(sinkfp, user, options) != SM_OK)
714                         {
715                             error(0,0,"SMTP error: %s", smtp_response);
716                             return(PS_SMTP);    /* should never happen */
717                         }
718                     }
719                 }
720
721                 /*
722                  * Now list the recipient addressees
723                  *
724                  * RFC 1123 requires that the domain name part of the
725                  * RCPT TO address be "canonicalized", that is a FQDN
726                  * or MX but not a CNAME.  RFC1123 doesn't say whether
727                  * the FQDN part can be null (as it frequently will be
728                  * here), but it's hard to see how this could cause a
729                  * problem.
730                  */
731                 for (idp = xmit_names; idp; idp = idp->next)
732                     if (SMTP_rcpt(sinkfp, idp->id) == SM_OK)
733                         good_addresses++;
734                     else
735                     {
736                         bad_addresses++;
737                         idp->val.num = 0;
738                         error(0, 0, 
739                                 "SMTP listener doesn't like recipient address `%s'", idp->id);
740                     }
741                 if (!good_addresses && SMTP_rcpt(sinkfp, user) != SM_OK)
742                 {
743                     error(0, 0, 
744                             "can't even send to calling user!");
745                     return(PS_SMTP);
746                 }
747
748                 /* tell it we're ready to send data */
749                 SMTP_data(sinkfp);
750
751             skiptext:;
752             }
753
754             /* write all the headers */
755             if (ctl->mda)
756                 n = fwrite(headers, 1, oldlen, sinkfp);
757             else if (sinkfp)
758                 n = SockWrite(headers, 1, oldlen, sinkfp);
759
760             if (n < 0)
761             {
762                 free(headers);
763                 headers = NULL;
764                 error(0, errno, "writing RFC822 headers");
765                 if (ctl->mda)
766                 {
767                     pclose(sinkfp);
768                     signal(SIGCHLD, sigchld);
769                 }
770                 return(PS_IOERR);
771             }
772             else if (outlevel == O_VERBOSE)
773                 fputs("#", stderr);
774             free(headers);
775             headers = NULL;
776
777             /* write error notifications */
778 #ifdef HAVE_RES_SEARCH
779             if (no_local_matches || bad_addresses)
780 #else
781             if (bad_addresses)
782 #endif /* HAVE_RES_SEARCH */
783             {
784                 int     errlen = 0;
785                 char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
786
787                 errmsg = errhd;
788                 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
789 #ifdef HAVE_RES_SEARCH
790                 if (no_local_matches)
791                 {
792                     strcat(errhd, "no recipient addresses matched declared local names");
793                     if (bad_addresses)
794                         strcat(errhd, "; ");
795                 }
796 #endif /* HAVE_RES_SEARCH */
797
798                 if (bad_addresses)
799                 {
800                     strcat(errhd, "SMTP listener rejected local recipient addresses: ");
801                     errlen = strlen(errhd);
802                     for (idp = xmit_names; idp; idp = idp->next)
803                         if (!idp->val.num)
804                             errlen += strlen(idp->id) + 2;
805
806                     errmsg = alloca(errlen+3);
807                     (void) strcpy(errmsg, errhd);
808                     for (idp = xmit_names; idp; idp = idp->next)
809                         if (!idp->val.num)
810                         {
811                             strcat(errmsg, idp->id);
812                             if (idp->next)
813                                 strcat(errmsg, ", ");
814                         }
815                 }
816
817                 strcat(errmsg, "\n");
818
819                 /* ship out the error line */
820                 if (ctl->mda)
821                     fwrite(errmsg, 1, strlen(errmsg), sinkfp);
822                 else if (sinkfp)
823                     SockWrite(errmsg, 1, strlen(errmsg), sinkfp);
824             }
825
826             free_str_list(&xmit_names);
827         } /* else if (headers) */
828
829         /* output a crlf if zero length message body */
830         if (!len && inheaders)
831         {
832             if (ctl->mda[0])
833                 fputs("\r\n", sinkfp);
834             else if (sinkfp)
835                 SockWrite("\r\n", 1, 2, sinkfp);
836             continue;
837         }
838
839         /* following code is executed on non-header lines only */
840
841         /* SMTP byte-stuffing */
842         if (*bufp == '.')
843             if (ctl->mda)
844                 fputs(".", sinkfp);
845             else if (sinkfp)
846                 SockWrite(bufp, 1, 1, sinkfp);
847
848         /* ship out the text line */
849         if (ctl->mda)
850             n = fwrite(bufp, 1, strlen(bufp), sinkfp);
851         else if (sinkfp)
852             n = SockWrite(bufp, 1, strlen(bufp), sinkfp);
853
854         if (n < 0)
855         {
856             error(0, errno, "writing message text");
857             if (ctl->mda)
858             {
859                 pclose(sinkfp);
860                 signal(SIGCHLD, sigchld);
861             }
862             return(PS_IOERR);
863         }
864         else if (outlevel == O_VERBOSE)
865             fputc('*', stderr);
866     }
867
868     if (outlevel == O_VERBOSE)
869         fputc('\n', stderr);
870
871     if (ctl->mda)
872     {
873         int rc;
874
875         /* close the delivery pipe, we'll reopen before next message */
876         rc = pclose(sinkfp);
877         signal(SIGCHLD, sigchld);
878         if (rc)
879         {
880             error(0, 0, "MDA exited abnormally or returned nonzero status");
881             return(PS_IOERR);
882         }
883     }
884     else if (sinkfp)
885     {
886         /* write message terminator */
887         if (SMTP_eom(sinkfp) != SM_OK)
888         {
889             error(0, 0, "SMTP listener refused delivery");
890             return(PS_TRANSIENT);
891         }
892     }
893
894     return(delete_ok ? PS_SUCCESS : PS_TRANSIENT);
895 }
896
897 #ifdef KERBEROS_V4
898 int
899 kerberos_auth (socket, canonical) 
900 /* authenticate to the server host using Kerberos V4 */
901 int socket;             /* socket to server host */
902 const char *canonical;  /* server name */
903 {
904     char * host_primary;
905     KTEXT ticket;
906     MSG_DAT msg_data;
907     CREDENTIALS cred;
908     Key_schedule schedule;
909     int rem;
910   
911     ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
912     rem = (krb_sendauth (0L, socket, ticket, "pop",
913                          canonical,
914                          ((char *) (krb_realmofhost (canonical))),
915                          ((unsigned long) 0),
916                          (&msg_data),
917                          (&cred),
918                          (schedule),
919                          ((struct sockaddr_in *) 0),
920                          ((struct sockaddr_in *) 0),
921                          "KPOPV0.1"));
922     free (ticket);
923     if (rem != KSUCCESS)
924     {
925         error(0, 0, "kerberos error %s", (krb_get_err_text (rem)));
926         return (PS_ERROR);
927     }
928     return (0);
929 }
930 #endif /* KERBEROS_V4 */
931
932 int do_protocol(ctl, proto)
933 /* retrieve messages from server using given protocol method table */
934 struct query *ctl;              /* parsed options with merged-in defaults */
935 const struct method *proto;     /* protocol method table */
936 {
937     int ok, js, pst;
938     char *msg, *sp, *cp, realname[HOSTLEN];
939     void (*sigsave)();
940
941 #ifndef KERBEROS_V4
942     if (ctl->server.authenticate == A_KERBEROS)
943     {
944         error(0, 0, "Kerberos support not linked.");
945         return(PS_ERROR);
946     }
947 #endif /* KERBEROS_V4 */
948
949     /* lacking methods, there are some options that may fail */
950     if (!proto->is_old)
951     {
952         /* check for unsupported options */
953         if (ctl->flush) {
954             error(0, 0,
955                     "Option --flush is not supported with %s",
956                     proto->name);
957             return(PS_SYNTAX);
958         }
959         else if (ctl->fetchall) {
960             error(0, 0,
961                     "Option --all is not supported with %s",
962                     proto->name);
963             return(PS_SYNTAX);
964         }
965     }
966     if (!proto->getsizes && ctl->limit)
967     {
968         error(0, 0,
969                 "Option --limit is not supported with %s",
970                 proto->name);
971         return(PS_SYNTAX);
972     }
973
974     protocol = proto;
975     tagnum = 0;
976     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
977     ok = 0;
978     error_init(poll_interval == 0 && !logfile);
979
980     /* set up the server-nonresponse timeout */
981     sigsave = signal(SIGVTALRM, vtalarm_handler);
982     vtalarm(mytimeout = ctl->server.timeout);
983
984     if ((js = setjmp(restart)) == 1)
985     {
986         error(0, 0,
987                 "timeout after %d seconds waiting for %s.",
988                 ctl->server.timeout, ctl->server.names->id);
989         ok = PS_ERROR;
990     }
991     else if (js == 2)
992     {
993         /* error message printed at point of longjmp */
994         ok = PS_ERROR;
995     }
996     else
997     {
998         char buf [POPBUFSIZE+1];
999         int *msgsizes, len, num, count, new, deletions = 0;
1000         FILE *sockfp; 
1001         /* execute pre-initialization command, if any */
1002         if (ctl->preconnect && (ok = system(ctl->preconnect)))
1003         {
1004             sprintf(buf, "pre-connection command failed with status %d", ok);
1005             error(0, 0, buf);
1006             ok = PS_SYNTAX;
1007             goto closeUp;
1008         }
1009
1010         /* open a socket to the mail server */
1011         if (!(sockfp = SockOpen(ctl->server.names->id,
1012                      ctl->server.port ? ctl->server.port : protocol->port)))
1013         {
1014 #ifndef EHOSTUNREACH
1015 #define EHOSTUNREACH (-1)
1016 #endif
1017             if (errno != EHOSTUNREACH)
1018                 error(0, errno, "connecting to host");
1019             ok = PS_SOCKET;
1020             goto closeUp;
1021         }
1022
1023 #ifdef KERBEROS_V4
1024         if (ctl->authenticate == A_KERBEROS)
1025         {
1026             ok = kerberos_auth(fileno(sockfp), ctl->server.canonical_name);
1027             if (ok != 0)
1028                 goto cleanUp;
1029             vtalarm(ctl->server.timeout);
1030         }
1031 #endif /* KERBEROS_V4 */
1032
1033         /* accept greeting message from mail server */
1034         ok = (protocol->parse_response)(sockfp, buf);
1035         if (ok != 0)
1036             goto cleanUp;
1037         vtalarm(ctl->server.timeout);
1038
1039         /*
1040          * Try to parse the host's actual name out of the greeting
1041          * message.  We do this so that the progress messages will
1042          * make sense even if the connection is indirected through
1043          * ssh. *Do* use this for hacking reply headers, but *don't*
1044          * use it for error logging, as the names in the log should
1045          * correlate directly back to rc file entries.
1046          *
1047          * This assumes that the first space-delimited token found
1048          * that contains at least two dots (with the characters on
1049          * each side of the dot alphanumeric to exclude version
1050          * numbers) is the hostname.  The hostname candidate may not
1051          * contain @ -- if it does it's probably a mailserver
1052          * maintainer's name.  If no such token is found, fall back on
1053          * the .fetchmailrc id.
1054          */
1055         pst = 0;
1056         for (cp = buf; *cp; cp++)
1057         {
1058             switch (pst)
1059             {
1060             case 0:             /* skip to end of current token */
1061                 if (*cp == ' ')
1062                     pst = 1;
1063                 break;
1064
1065             case 1:             /* look for blank-delimited token */
1066                 if (*cp != ' ')
1067                 {
1068                     sp = cp;
1069                     pst = 2;
1070                 }
1071                 break;
1072
1073             case 2:             /* look for first dot */
1074                 if (*cp == '@')
1075                     pst = 0;
1076                 else if (*cp == ' ')
1077                     pst = 1;
1078                 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1079                     pst = 3;
1080                 break;
1081
1082             case 3:             /* look for second dot */
1083                 if (*cp == '@')
1084                     pst = 0;
1085                 else if (*cp == ' ')
1086                     pst = 1;
1087                 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1088                     pst = 4;
1089                 break;
1090
1091             case 4:             /* look for trailing space */
1092                 if (*cp == '@')
1093                     pst = 0;
1094                 else if (*cp == ' ')
1095                 {
1096                     pst = 5;
1097                     goto done;
1098                 }
1099                 break;
1100             }
1101         }
1102     done:
1103         if (pst == 5)
1104         {
1105             char        *tp = realname;
1106
1107             while (sp < cp)
1108                 *tp++ = *sp++;
1109             *tp = '\0';
1110         }
1111         else
1112             strcpy(realname, ctl->server.names->id);
1113
1114         /* try to get authorized to fetch mail */
1115         shroud = ctl->password;
1116         ok = (protocol->getauth)(sockfp, ctl, buf);
1117         shroud = (char *)NULL;
1118         if (ok == PS_ERROR)
1119             ok = PS_AUTHFAIL;
1120         if (ok != 0)
1121             goto cleanUp;
1122         vtalarm(ctl->server.timeout);
1123
1124         /* compute number of messages and number of new messages waiting */
1125         ok = (protocol->getrange)(sockfp, ctl, &count, &new);
1126         if (ok != 0)
1127             goto cleanUp;
1128         vtalarm(ctl->server.timeout);
1129
1130         /* show user how many messages we downloaded */
1131         if (outlevel > O_SILENT)
1132             if (count == 0)
1133                 error(0, 0, "No mail from %s@%s", 
1134                         ctl->remotename,
1135                         realname);
1136             else
1137             {
1138                 if (new != -1 && (count - new) > 0)
1139                     error(0, 0, "%d message%s (%d seen) from %s@%s.",
1140                                 count, count > 1 ? "s" : "", count-new,
1141                                 ctl->remotename,
1142                                 realname);
1143                 else
1144                     error(0, 0, "%d message%s from %s@%s.", count, count > 1 ? "s" : "",
1145                                 ctl->remotename,
1146                                 realname);
1147             }
1148
1149         /* we may need to get sizes in order to check message limits */
1150         msgsizes = (int *)NULL;
1151         if (!ctl->fetchall && proto->getsizes && ctl->limit)
1152         {
1153             msgsizes = (int *)alloca(sizeof(int) * count);
1154
1155             ok = (proto->getsizes)(sockfp, count, msgsizes);
1156             if (ok != 0)
1157                 goto cleanUp;
1158             vtalarm(ctl->server.timeout);
1159         }
1160
1161         if (check_only)
1162         {
1163             if (new == -1 || ctl->fetchall)
1164                 new = count;
1165             ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1166             goto cleanUp;
1167         }
1168         else if (count > 0)
1169         {    
1170             /*
1171              * What forces this code is that in POP3 and IMAP2BIS you can't
1172              * fetch a message without having it marked `seen'.  In IMAP4,
1173              * on the other hand, you can (peek_capable is set to convey
1174              * this).
1175              *
1176              * The result of being unable to peek is that if there's
1177              * any kind of transient error (DNS lookup failure, or
1178              * sendmail refusing delivery due to process-table limits)
1179              * the message will be marked "seen" on the server without
1180              * having been delivered.  This is not a big problem if
1181              * fetchmail is running in foreground, because the user
1182              * will see a "skipped" message when it next runs and get
1183              * clued in.
1184              *
1185              * But in daemon mode this leads to the message being silently
1186              * ignored forever.  This is not acceptable.
1187              *
1188              * We compensate for this by checking the error count from the 
1189              * previous pass and forcing all messages to be considered new
1190              * if it's nonzero.
1191              */
1192             int force_retrieval = !peek_capable && (ctl->errcount > 0);
1193
1194             ctl->errcount = 0;
1195
1196             /* read, forward, and delete messages */
1197             for (num = 1; num <= count; num++)
1198             {
1199                 int     toolarge = msgsizes && (msgsizes[num-1] > ctl->limit);
1200                 int     fetch_it = ctl->fetchall ||
1201                     (!toolarge && (force_retrieval || !(protocol->is_old && (protocol->is_old)(sockfp,ctl,num))));
1202                 int     suppress_delete = FALSE;
1203
1204                 /* we may want to reject this message if it's old */
1205                 if (!fetch_it)
1206                 {
1207                     if (outlevel > O_SILENT)
1208                     {
1209                         error_build("skipping message %d", num);
1210                         if (toolarge)
1211                             error_build(" (oversized, %d bytes)", msgsizes[num-1]);
1212                     }
1213                 }
1214                 else
1215                 {
1216                     /* request a message */
1217                     ok = (protocol->fetch)(sockfp, ctl, num, &len);
1218                     if (ok != 0)
1219                         goto cleanUp;
1220                     vtalarm(ctl->server.timeout);
1221
1222                     if (outlevel > O_SILENT)
1223                     {
1224                         error_build("reading message %d", num);
1225                         if (len > 0)
1226                             error_build(" (%d bytes)", len);
1227                         if (outlevel == O_VERBOSE)
1228                             error_complete(0, 0, "");
1229                         else
1230                             error_build(" ");
1231                     }
1232
1233                     /* read the message and ship it to the output sink */
1234                     ok = gen_readmsg(sockfp,
1235                                      len, 
1236                                      protocol->delimited,
1237                                      ctl,
1238                                      realname);
1239                     if (ok == PS_TRANSIENT)
1240                         suppress_delete = TRUE;
1241                     else if (ok)
1242                         goto cleanUp;
1243                     vtalarm(ctl->server.timeout);
1244
1245                     /* tell the server we got it OK and resynchronize */
1246                     if (protocol->trail)
1247                     {
1248                         ok = (protocol->trail)(sockfp, ctl, num);
1249                         if (ok != 0)
1250                             goto cleanUp;
1251                         vtalarm(ctl->server.timeout);
1252                     }
1253                 }
1254
1255                 /*
1256                  * At this point in flow of control, either we've bombed
1257                  * on a protocol error or had delivery refused by the SMTP
1258                  * server (unlikely -- I've never seen it) or we've seen
1259                  * `accepted for delivery' and the message is shipped.
1260                  * It's safe to mark the message seen and delete it on the
1261                  * server now.
1262                  */
1263
1264                 /* maybe we delete this message now? */
1265                 if (protocol->delete
1266                     && !suppress_delete
1267                     && (fetch_it ? !ctl->keep : ctl->flush))
1268                 {
1269                     deletions++;
1270                     if (outlevel > O_SILENT) 
1271                         error_complete(0, 0, " flushed");
1272                     ok = (protocol->delete)(sockfp, ctl, num);
1273                     if (ok != 0)
1274                         goto cleanUp;
1275                     vtalarm(ctl->server.timeout);
1276                     delete_str(&ctl->newsaved, num);
1277                 }
1278                 else if (outlevel > O_SILENT) 
1279                     error_complete(0, 0, " not flushed");
1280
1281                 /* perhaps this as many as we're ready to handle */
1282                 if (ctl->fetchlimit && ctl->fetchlimit <= num)
1283                     break;
1284             }
1285
1286             ok = gen_transact(sockfp, protocol->exit_cmd);
1287             if (ok == 0)
1288                 ok = PS_SUCCESS;
1289             vtalarm(0);
1290             fclose(sockfp);
1291             goto closeUp;
1292         }
1293         else {
1294             ok = gen_transact(sockfp, protocol->exit_cmd);
1295             if (ok == 0)
1296                 ok = PS_NOMAIL;
1297             vtalarm(0);
1298             fclose(sockfp);
1299             goto closeUp;
1300         }
1301
1302     cleanUp:
1303         vtalarm(ctl->server.timeout);
1304         if (ok != 0 && ok != PS_SOCKET)
1305             gen_transact(sockfp, protocol->exit_cmd);
1306         vtalarm(0);
1307         fclose(sockfp);
1308     }
1309
1310     switch (ok)
1311     {
1312     case PS_SOCKET:
1313         msg = "socket";
1314         break;
1315     case PS_AUTHFAIL:
1316         msg = "authorization";
1317         break;
1318     case PS_SYNTAX:
1319         msg = "missing or bad RFC822 header";
1320         break;
1321     case PS_IOERR:
1322         msg = "MDA";
1323         break;
1324     case PS_ERROR:
1325         msg = "client/server synchronization";
1326         break;
1327     case PS_PROTOCOL:
1328         msg = "client/server protocol";
1329         break;
1330     case PS_SMTP:
1331         msg = "SMTP transaction";
1332         break;
1333     case PS_UNDEFINED:
1334         error(0, 0, "undefined");
1335         break;
1336     }
1337     if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX || ok==PS_IOERR
1338                 || ok==PS_ERROR || ok==PS_PROTOCOL || ok==PS_SMTP)
1339         error(0, 0, "%s error while fetching from %s", msg, ctl->server.names->id);
1340
1341 closeUp:
1342     signal(SIGVTALRM, sigsave);
1343     return(ok);
1344 }
1345
1346 #if defined(HAVE_STDARG_H)
1347 void gen_send(FILE *sockfp, char *fmt, ... )
1348 /* assemble command in printf(3) style and send to the server */
1349 #else
1350 void gen_send(sockfp, fmt, va_alist)
1351 /* assemble command in printf(3) style and send to the server */
1352 FILE *sockfp;           /* socket to which server is connected */
1353 const char *fmt;        /* printf-style format */
1354 va_dcl
1355 #endif
1356 {
1357     char buf [POPBUFSIZE+1];
1358     va_list ap;
1359
1360     if (protocol->tagged)
1361         (void) sprintf(buf, "%s ", GENSYM);
1362     else
1363         buf[0] = '\0';
1364
1365 #if defined(HAVE_STDARG_H)
1366     va_start(ap, fmt) ;
1367 #else
1368     va_start(ap);
1369 #endif
1370     vsprintf(buf + strlen(buf), fmt, ap);
1371     va_end(ap);
1372
1373     strcat(buf, "\r\n");
1374     SockWrite(buf, 1, strlen(buf), sockfp);
1375
1376     if (outlevel == O_VERBOSE)
1377     {
1378         char *cp;
1379
1380         if (shroud && (cp = strstr(buf, shroud)))
1381             memset(cp, '*', strlen(shroud));
1382         buf[strlen(buf)-1] = '\0';
1383         error(0, 0, "%s> %s", protocol->name, buf);
1384     }
1385 }
1386
1387 #if defined(HAVE_STDARG_H)
1388 int gen_transact(FILE *sockfp, char *fmt, ... )
1389 /* assemble command in printf(3) style, send to server, accept a response */
1390 #else
1391 int gen_transact(sockfp, fmt, va_alist)
1392 /* assemble command in printf(3) style, send to server, accept a response */
1393 FILE *sockfp;           /* socket to which server is connected */
1394 const char *fmt;        /* printf-style format */
1395 va_dcl
1396 #endif
1397 {
1398     int ok;
1399     char buf [POPBUFSIZE+1];
1400     va_list ap;
1401
1402     if (protocol->tagged)
1403         (void) sprintf(buf, "%s ", GENSYM);
1404     else
1405         buf[0] = '\0';
1406
1407 #if defined(HAVE_STDARG_H)
1408     va_start(ap, fmt) ;
1409 #else
1410     va_start(ap);
1411 #endif
1412     vsprintf(buf + strlen(buf), fmt, ap);
1413     va_end(ap);
1414
1415     strcat(buf, "\r\n");
1416     SockWrite(buf, 1, strlen(buf), sockfp);
1417
1418     if (outlevel == O_VERBOSE)
1419     {
1420         char *cp;
1421
1422         if (shroud && (cp = strstr(buf, shroud)))
1423             memset(cp, '*', strlen(shroud));
1424         buf[strlen(buf)-1] = '\0';
1425         error(0, 0, "%s> %s", protocol->name, buf);
1426     }
1427
1428     /* we presume this does its own response echoing */
1429     ok = (protocol->parse_response)(sockfp, buf);
1430     vtalarm(mytimeout);
1431
1432     return(ok);
1433 }
1434
1435 /* driver.c ends here */