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