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