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