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