]> Pileus Git - ~andy/fetchmail/blob - driver.c
Clean up the generated trace headers.
[~andy/fetchmail] / driver.c
1 /*
2  * driver.c -- generic driver for mail fetch method protocols
3  *
4  * Copyright 1997 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  *
7  * i18n by Arnaldo Carvalho de Melo <acme@conectiva.com.br> 7-Nov-1998
8  */
9
10 #include  "config.h"
11 #include  <stdio.h>
12 #include  <setjmp.h>
13 #include  <errno.h>
14 #include  <ctype.h>
15 #include  <string.h>
16 #ifdef HAVE_MEMORY_H
17 #include  <memory.h>
18 #endif /* HAVE_MEMORY_H */
19 #if defined(STDC_HEADERS)
20 #include  <stdlib.h>
21 #endif
22 #if defined(HAVE_UNISTD_H)
23 #include <unistd.h>
24 #endif
25 #if defined(HAVE_STDARG_H)
26 #include  <stdarg.h>
27 #else
28 #include  <varargs.h>
29 #endif
30 #if defined(HAVE_SYS_ITIMER_H)
31 #include <sys/itimer.h>
32 #endif
33 #include  <sys/time.h>
34 #include  <signal.h>
35
36 #ifdef HAVE_RES_SEARCH
37 #include <netdb.h>
38 #include "mx.h"
39 #endif /* HAVE_RES_SEARCH */
40
41 #ifdef KERBEROS_V4
42 #ifdef KERBEROS_V5
43 #include <kerberosIV/des.h>
44 #include <kerberosIV/krb.h>
45 #else
46 #if defined (__bsdi__)
47 #include <des.h> /* order of includes matters */
48 #include <krb.h>
49 #define krb_get_err_text(e) (krb_err_txt[e])
50 #else
51 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
52 #define krb_get_err_text(e) (krb_err_txt[e])
53 #include <krb.h>
54 #include <des.h>
55 #else
56 #include <krb.h>
57 #include <des.h>
58 #endif /* ! defined (__FreeBSD__) */
59 #endif /* ! defined (__bsdi__) */
60 #endif /* KERBEROS_V5 */
61 #include <netinet/in.h>
62 #include <netdb.h>
63 #endif /* KERBEROS_V4 */
64 #ifdef KERBEROS_V5
65 #include <krb5.h>
66 #include <com_err.h>
67 #endif /* KERBEROS_V5 */
68 #include "i18n.h"
69
70 #include "socket.h"
71 #include "fetchmail.h"
72 #include "tunable.h"
73
74 #ifndef strstr          /* glibc-2.1 declares this as a macro */
75 extern char *strstr();  /* needed on sysV68 R3V7.1. */
76 #endif /* strstr */
77
78 int fetchlimit;         /* how often to tear down the server connection */
79 int batchcount;         /* count of messages sent in current batch */
80 flag peek_capable;      /* can we peek for better error recovery? */
81 int pass;               /* how many times have we re-polled? */
82 int phase;              /* where are we, for error-logging purposes? */
83
84 static const struct method *protocol;
85 static jmp_buf  restart;
86
87 char tag[TAGLEN];
88 static int tagnum;
89 #define GENSYM  (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
90
91 static char shroud[PASSWORDLEN];        /* string to shroud in debug output */
92 static int mytimeout;                   /* value of nonreponse timeout */
93 static int timeoutcount;                /* count consecutive timeouts */
94 static int msglen;                      /* actual message length */
95
96 void set_timeout(int timeleft)
97 /* reset the nonresponse-timeout */
98 {
99 #ifndef __EMX__
100     struct itimerval ntimeout;
101
102     if (timeleft == 0)
103         timeoutcount = 0;
104
105     ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
106     ntimeout.it_value.tv_sec  = timeleft;
107     ntimeout.it_value.tv_usec = 0;
108     setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
109 #endif
110 }
111
112 static void timeout_handler (int signal)
113 /* handle server-timeout SIGALRM signal */
114 {
115     timeoutcount++;
116     longjmp(restart, 1);
117 }
118
119 static int accept_count, reject_count;
120
121 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
122 /* add given name to xmit_names if it matches declared localnames */
123 /*   name:       name to map */
124 /*   ctl:        list of permissible aliases */
125 /*   xmit_names: list of recipient names parsed out */
126 {
127     const char  *lname;
128     int off = 0;
129     
130     lname = idpair_find(&ctl->localnames, name+off);
131     if (!lname && ctl->wildcard)
132         lname = name+off;
133
134     if (lname != (char *)NULL)
135     {
136         if (outlevel >= O_DEBUG)
137             error(0, 0, _("mapped %s to local %s"), name, lname);
138         save_str(xmit_names, lname, XMIT_ACCEPT);
139         accept_count++;
140     }
141 }
142
143 void find_server_names(const char *hdr, struct query *ctl, struct idlist **xmit_names)
144 /* parse names out of a RFC822 header into an ID list */
145 /*   hdr:               RFC822 header in question */
146 /*   ctl:               list of permissible aliases */
147 /*   xmit_names:        list of recipient names parsed out */
148 {
149     if (hdr == (char *)NULL)
150         return;
151     else
152     {
153         char    *cp;
154
155         for (cp = nxtaddr(hdr);
156              cp != NULL;
157              cp = nxtaddr(NULL))
158         {
159             char        *atsign;
160
161             /*
162              * If the name of the user begins with a qmail virtual
163              * domain prefix, ignore the prefix.  Doing this here
164              * means qvirtual will work either with ordinary name
165              * mapping or with a localdomains option.
166              */
167             if (ctl->server.qvirtual)
168             {
169                 int sl = strlen(ctl->server.qvirtual);
170  
171                 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
172                     cp += sl;
173             }
174
175             if ((atsign = strchr(cp, '@'))) {
176                 struct idlist   *idp;
177
178                 /*
179                  * Does a trailing segment of the hostname match something
180                  * on the localdomains list?  If so, save the whole name
181                  * and keep going.
182                  */
183                 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
184                     char        *rhs;
185
186                     rhs = atsign + (strlen(atsign) - strlen(idp->id));
187                     if (rhs > atsign &&
188                         (rhs[-1] == '.' || rhs[-1] == '@') &&
189                         strcasecmp(rhs, idp->id) == 0)
190                     {
191                         if (outlevel >= O_DEBUG)
192                             error(0, 0, _("passed through %s matching %s"), 
193                                   cp, idp->id);
194                         save_str(xmit_names, cp, XMIT_ACCEPT);
195                         accept_count++;
196                         goto nomap;
197                     }
198                 }
199
200                 /* if we matched a local domain, idp != NULL */
201                 if (!idp)
202                 {
203                     /*
204                      * Check to see if the right-hand part is an alias
205                      * or MX equivalent of the mailserver.  If it's
206                      * not, skip this name.  If it is, we'll keep
207                      * going and try to find a mapping to a client name.
208                      */
209                     if (!is_host_alias(atsign+1, ctl))
210                     {
211                         save_str(xmit_names, cp, XMIT_REJECT);
212                         reject_count++;
213                         continue;
214                     }
215                 }
216                 atsign[0] = '\0';
217                 map_name(cp, ctl, xmit_names);
218             nomap:;
219             }
220         }
221     }
222 }
223
224 static char *parse_received(struct query *ctl, char *bufp)
225 /* try to extract real address from the Received line */
226 /* If a valid Received: line is found, we return the full address in
227  * a buffer which can be parsed from nxtaddr().  This is to ansure that
228  * the local domain part of the address can be passed along in 
229  * find_server_names() if it contains one.
230  * Note: We should return a dummy header containing the address 
231  * which makes nxtaddr() behave correctly. 
232  */
233 {
234     char *base, *ok = (char *)NULL;
235     static char rbuf[HOSTLEN + USERNAMELEN + 4]; 
236
237     /*
238      * Try to extract the real envelope addressee.  We look here
239      * specifically for the mailserver's Received line.
240      * Note: this will only work for sendmail, or an MTA that
241      * shares sendmail's convention for embedding the envelope
242      * address in the Received line.  Sendmail itself only
243      * does this when the mail has a single recipient.
244      */
245     if (outlevel >= O_DEBUG)
246         error(0, 0, _("analyzing Received line:\n%s"), bufp);
247
248     /* search for whitepace-surrounded "by" followed by xxxx.yyyy */
249     for (base = bufp;  ; base = ok + 2)
250     {
251         if (!(ok = strstr(base, "by")))
252             break;
253         else if (!isspace(ok[-1]) || !isspace(ok[2]))
254         {
255             ok = (char *)NULL;
256             continue;
257         }
258         else
259         {
260             char        *sp, *tp;
261
262             /* extract space-delimited token after "by" */
263             for (sp = ok + 2; isspace(*sp); sp++)
264                 continue;
265             tp = rbuf;
266             for (; !isspace(*sp); sp++)
267                 *tp++ = *sp;
268             *tp = '\0';
269
270             /* look for embedded periods */
271             if (strchr(rbuf, '.'))
272                 break;
273             else
274                 ok = sp - 1;    /* arrange to skip this token */
275         }
276     }
277     if (ok)
278     {
279         /*
280          * If it's a DNS name of the mail server, look for the
281          * recipient name after a following "for".  Otherwise
282          * punt.
283          */
284         if (is_host_alias(rbuf, ctl))
285         {
286             if (outlevel >= O_DEBUG)
287                 error(0, 0, 
288                       _("line accepted, %s is an alias of the mailserver"), rbuf);
289         }
290         else
291         {
292             if (outlevel >= O_DEBUG)
293                 error(0, 0, 
294                       _("line rejected, %s is not an alias of the mailserver"), 
295                       rbuf);
296             return(NULL);
297         }
298
299         /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
300         for (base = ok + 4 + strlen(rbuf);  ; base = ok + 2)
301         {
302             if (!(ok = strstr(base, "for")))
303                 break;
304             else if (!isspace(ok[-1]) || !isspace(ok[3]))
305             {
306                 ok = (char *)NULL;
307                 continue;
308             }
309             else
310             {
311                 char    *sp, *tp;
312
313                 /* extract space-delimited token after "for" */
314                 for (sp = ok + 3; isspace(*sp); sp++)
315                     continue;
316                 tp = rbuf;
317                 for (; !isspace(*sp); sp++)
318                     *tp++ = *sp;
319                 *tp = '\0';
320
321                 if (strchr(rbuf, '@'))
322                     break;
323                 else
324                     ok = sp - 1;        /* arrange to skip this token */
325             }
326         }
327         if (ok)
328         {
329             flag        want_gt = FALSE;
330             char        *sp, *tp;
331
332             /* char after "for" could be space or a continuation newline */
333             for (sp = ok + 4; isspace(*sp); sp++)
334                 continue;
335             tp = rbuf;
336             *tp++ = ':';        /* Here is the hack.  This is to be friends */
337             *tp++ = ' ';        /* with nxtaddr()... */
338             if (*sp == '<')
339             {
340                 want_gt = TRUE;
341                 sp++;
342             }
343             while (*sp == '@')          /* skip routes */
344                 while (*sp && *sp++ != ':')
345                     continue;
346             while (*sp
347                    && (want_gt ? (*sp != '>') : !isspace(*sp))
348                    && *sp != ';')
349                 if (!isspace(*sp))
350                     *tp++ = *sp++;
351                 else
352                 {
353                     /* uh oh -- whitespace here can't be right! */
354                     ok = (char *)NULL;
355                     break;
356                 }
357             *tp++ = '\n';
358             *tp = '\0';
359             if (strlen(rbuf) <= 3)      /* apparently nothing has been found */
360                 ok = NULL;
361         } else
362             ok = (char *)NULL;
363     }
364
365     if (!ok)
366     {
367         if (outlevel >= O_DEBUG)
368             error(0, 0, _("no Received address found"));
369         return(NULL);
370     }
371     else
372     {
373         if (outlevel >= O_DEBUG) {
374             char *lf = rbuf + strlen(rbuf)-1;
375             *lf = '\0';
376             if (outlevel >= O_DEBUG)
377                 error(0, 0, _("found Received address `%s'"), rbuf+2);
378             *lf = '\n';
379         }
380         return(rbuf);
381     }
382 }
383
384 /* shared by readheaders and readbody */
385 static int sizeticker;
386 static struct msgblk msgblk;
387
388 #define EMPTYLINE(s)    ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
389
390 static int readheaders(int sock, long fetchlen, long reallen, struct query *ctl, int num)
391 /* read message headers and ship to SMTP or MDA */
392 /*   sock:              to which the server is connected */
393 /*   fetchlen:          length of message according to fetch response */
394 /*   reallen:           length of message according to getsizes */
395 /*   ctl:               query control record */
396 /*   num:               index of message */
397 {
398     struct addrblk
399     {
400         int             offset;
401         struct addrblk  *next;
402     };
403     struct addrblk      *to_addrchain = NULL;
404     struct addrblk      **to_chainptr = &to_addrchain;
405     struct addrblk      *resent_to_addrchain = NULL;
406     struct addrblk      **resent_to_chainptr = &resent_to_addrchain;
407
408     char                buf[MSGBUFSIZE+1];
409     int                 from_offs, reply_to_offs, resent_from_offs;
410     int                 app_from_offs, sender_offs, resent_sender_offs;
411     int                 env_offs;
412     char                *received_for, *rcv, *cp;
413     int                 n, linelen, oldlen, ch, remaining, skipcount;
414     struct idlist       *idp;
415     flag                no_local_matches = FALSE;
416     flag                headers_ok, has_nuls;
417     int                 olderrs, good_addresses, bad_addresses;
418
419     sizeticker = 0;
420     has_nuls = headers_ok = FALSE;
421     msgblk.return_path[0] = '\0';
422     olderrs = ctl->errcount;
423
424     /* read message headers */
425     msgblk.reallen = reallen;
426     msgblk.headers = received_for = NULL;
427     from_offs = reply_to_offs = resent_from_offs = app_from_offs = 
428         sender_offs = resent_sender_offs = env_offs = -1;
429     oldlen = 0;
430     msglen = 0;
431     skipcount = 0;
432     ctl->mimemsg = 0;
433
434     for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
435     {
436         char *line;
437
438         line = xmalloc(sizeof(buf));
439         linelen = 0;
440         line[0] = '\0';
441         do {
442             set_timeout(mytimeout);
443             if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
444                 set_timeout(0);
445                 free(line);
446                 free(msgblk.headers);
447                 return(PS_SOCKET);
448             }
449             set_timeout(0);
450             linelen += n;
451             msglen += n;
452
453             /* lines may not be properly CRLF terminated; fix this for qmail */
454             if (ctl->forcecr)
455             {
456                 cp = buf + strlen(buf) - 1;
457                 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
458                 {
459                     *cp++ = '\r';
460                     *cp++ = '\n';
461                     *cp++ = '\0';
462                 }
463             }
464
465
466             line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
467
468             strcat(line, buf);
469
470             /* check for end of headers */
471             if (EMPTYLINE(line))
472             {
473                 headers_ok = TRUE;
474                 has_nuls = (linelen != strlen(line));
475                 free(line);
476                 goto process_headers;
477             }
478
479             /*
480              * Check for end of message immediately.  If one of your folders
481              * has been mangled, the delimiter may occur directly after the
482              * header.
483              */
484             if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
485             {
486                 free(line);
487                 has_nuls = (linelen != strlen(line));
488                 goto process_headers;
489             }
490
491             /* check for RFC822 continuations */
492             set_timeout(mytimeout);
493             ch = SockPeek(sock);
494             set_timeout(0);
495         } while
496             (ch == ' ' || ch == '\t');  /* continuation to next line? */
497
498         /* write the message size dots */
499         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
500         {
501             sizeticker += linelen;
502             while (sizeticker >= SIZETICKER)
503             {
504                 error_build(".");
505                 sizeticker -= SIZETICKER;
506             }
507         }
508
509         /* we see an ordinary (non-header, non-message-delimiter line */
510         has_nuls = (linelen != strlen(line));
511
512         /*
513          * The University of Washington IMAP server (the reference
514          * implementation of IMAP4 written by Mark Crispin) relies
515          * on being able to keep base-UID information in a special
516          * message at the head of the mailbox.  This message should
517          * neither be deleted nor forwarded.
518          */
519 #ifdef POP2_ENABLE
520         /*
521          * We disable this check under POP2 because there's no way to
522          * prevent deletion of the message.  So at least we ought to 
523          * forward it to the user so he or she will have some clue
524          * that things have gone awry.
525          */
526         if (protocol->port != 109)
527 #endif /* POP2_ENABLE */
528             if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
529                 free(line);
530                 free(msgblk.headers);
531                 return(PS_RETAINED);
532             }
533
534         /*
535          * This code prevents fetchmail from becoming an accessory after
536          * the fact to upstream sendmails with the `E' option on.  It also
537          * copes with certain brain-dead POP servers (like NT's) that pass
538          * through Unix from_ lines.
539          *
540          * Either of these bugs can result in a non-RFC822 line at the
541          * beginning of the headers.  If fetchmail just passes it
542          * through, the client listener may think the message has *no*
543          * headers (since the first) line it sees doesn't look
544          * RFC822-conformant) and fake up a set.
545          *
546          * What the user would see in this case is bogus (synthesized)
547          * headers, followed by a blank line, followed by the >From, 
548          * followed by the real headers, followed by a blank line,
549          * followed by text.
550          *
551          * We forestall this lossage by tossing anything that looks
552          * like an escaped or passed-through From_ line in headers.
553          * These aren't RFC822 so our conscience is clear...
554          */
555         if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
556         {
557             free(line);
558             continue;
559         }
560
561         /*
562          * If we see a Status line, it may have been inserted by an MUA
563          * on the mail host, or it may have been inserted by the server
564          * program after the headers in the transaction stream.  This
565          * can actually hose some new-mail notifiers such as xbuffy,
566          * which assumes any Status line came from a *local* MDA and
567          * therefore indicates that the message has been seen.
568          *
569          * Some buggy POP servers (including at least the 3.3(20)
570          * version of the one distributed with IMAP) insert empty
571          * Status lines in the transaction stream; we'll chuck those
572          * unconditionally.  Nonempty ones get chucked if the user
573          * turns on the dropstatus flag.
574          */
575         {
576             char        *cp;
577
578             if (!strncasecmp(line, "Status:", 7))
579                 cp = line + 7;
580             else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
581                 cp = line + 17;
582             else
583                 cp = NULL;
584             if (cp) {
585                 while (*cp && isspace(*cp)) cp++;
586                 if (!*cp || ctl->dropstatus)
587                 {
588                     free(line);
589                     continue;
590                 }
591             }
592         }
593
594         if (ctl->rewrite)
595             line = reply_hack(line, ctl->server.truename);
596
597         /*
598          * OK, this is messy.  If we're forwarding by SMTP, it's the
599          * SMTP-receiver's job (according to RFC821, page 22, section
600          * 4.1.1) to generate a Return-Path line on final delivery.
601          * The trouble is, we've already got one because the
602          * mailserver's SMTP thought *it* was responsible for final
603          * delivery.
604          *
605          * Stash away the contents of Return-Path (as modified by reply_hack)
606          * for use in generating MAIL FROM later on, then prevent the header
607          * from being saved with the others.  In effect, we strip it off here.
608          *
609          * If the SMTP server conforms to the standards, and fetchmail gets the
610          * envelope sender from the Return-Path, the new Return-Path should be
611          * exactly the same as the original one.
612          *
613          * We do *not* want to ignore empty Return-Path headers.  These should
614          * be passed through as a way of indicating that a message should
615          * not trigger bounces if delivery fails.  What we *do* need to do is
616          * make sure we never try to rewrite such a blank Return-Path.  We
617          * handle this with a check for <> in the rewrite logic above.
618          */
619         if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
620         {
621             strcpy(msgblk.return_path, cp);
622             if (!ctl->mda) {
623                 free(line);
624                 continue;
625             }
626         }
627
628         if (!msgblk.headers)
629         {
630             oldlen = strlen(line);
631             msgblk.headers = xmalloc(oldlen + 1);
632             (void) strcpy(msgblk.headers, line);
633             free(line);
634             line = msgblk.headers;
635         }
636         else
637         {
638             int newlen;
639
640             newlen = oldlen + strlen(line);
641             msgblk.headers = (char *) realloc(msgblk.headers, newlen + 1);
642             if (msgblk.headers == NULL) {
643                 free(line);
644                 return(PS_IOERR);
645             }
646             strcpy(msgblk.headers + oldlen, line);
647             free(line);
648             line = msgblk.headers + oldlen;
649             oldlen = newlen;
650         }
651
652         if (!strncasecmp("From:", line, 5))
653             from_offs = (line - msgblk.headers);
654         else if (!strncasecmp("Reply-To:", line, 9))
655             reply_to_offs = (line - msgblk.headers);
656         else if (!strncasecmp("Resent-From:", line, 12))
657             resent_from_offs = (line - msgblk.headers);
658         else if (!strncasecmp("Apparently-From:", line, 16))
659             app_from_offs = (line - msgblk.headers);
660         else if (!strncasecmp("Sender:", line, 7))
661             sender_offs = (line - msgblk.headers);
662         else if (!strncasecmp("Resent-Sender:", line, 14))
663             resent_sender_offs = (line - msgblk.headers);
664
665         else if (!strncasecmp("Message-Id:", buf, 11))
666         {
667             if (ctl->server.uidl)
668             {
669                 char id[IDLEN+1];
670
671                 buf[IDLEN+12] = 0;              /* prevent stack overflow */
672                 sscanf(buf+12, "%s", id);
673                 if (!str_find( &ctl->newsaved, num))
674                 {
675                     struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
676                     new->val.status.num = num;
677                 }
678             }
679         }
680
681         else if (!MULTIDROP(ctl))
682             continue;
683
684         else if (!strncasecmp("To:", line, 3)
685                         || !strncasecmp("Cc:", line, 3)
686                         || !strncasecmp("Bcc:", line, 4)
687                         || !strncasecmp("Apparently-To:", line, 14))
688         {
689             *to_chainptr = xmalloc(sizeof(struct addrblk));
690             (*to_chainptr)->offset = (line - msgblk.headers);
691             to_chainptr = &(*to_chainptr)->next; 
692             *to_chainptr = NULL;
693         }
694
695         else if (!strncasecmp("Resent-To:", line, 10)
696                         || !strncasecmp("Resent-Cc:", line, 10)
697                         || !strncasecmp("Resent-Bcc:", line, 11))
698         {
699             *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
700             (*resent_to_chainptr)->offset = (line - msgblk.headers);
701             resent_to_chainptr = &(*resent_to_chainptr)->next; 
702             *resent_to_chainptr = NULL;
703         }
704
705         else if (ctl->server.envelope != STRING_DISABLED)
706         {
707             if (ctl->server.envelope 
708                         && strcasecmp(ctl->server.envelope, "Received"))
709             {
710                 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
711                                                 line,
712                                                 strlen(ctl->server.envelope)))
713                 {                               
714                     if (skipcount++ != ctl->server.envskip)
715                         continue;
716                     env_offs = (line - msgblk.headers);
717                 }    
718             }
719             else if (!received_for && !strncasecmp("Received:", line, 9))
720             {
721                 if (skipcount++ != ctl->server.envskip)
722                     continue;
723                 received_for = parse_received(ctl, line);
724             }
725         }
726     }
727
728  process_headers:
729     /*
730      * We want to detect this early in case there are so few headers that the
731      * dispatch logic barfs.
732      */
733     if (!headers_ok)
734     {
735         if (outlevel > O_SILENT)
736             error(0,0,_("message delimiter found while scanning headers"));
737     }
738
739     /*
740      * Hack time.  If the first line of the message was blank, with no headers
741      * (this happens occasionally due to bad gatewaying software) cons up
742      * a set of fake headers.  
743      *
744      * If you modify the fake header template below, be sure you don't
745      * make either From or To address @-less, otherwise the reply_hack
746      * logic will do bad things.
747      */
748     if (msgblk.headers == (char *)NULL)
749     {
750 #ifdef HAVE_SNPRINTF
751         snprintf(buf, sizeof(buf),
752 #else
753         sprintf(buf, 
754 #endif /* HAVE_SNPRINTF */
755         "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
756                 user, fetchmailhost, ctl->remotename, ctl->server.truename);
757         msgblk.headers = xstrdup(buf);
758     }
759
760     /*
761      * We can now process message headers before reading the text.
762      * In fact we have to, as this will tell us where to forward to.
763      */
764
765     /* Decode MIME encoded headers. We MUST do this before
766      * looking at the Content-Type / Content-Transfer-Encoding
767      * headers (RFC 2046).
768      */
769     if (ctl->mimedecode) {
770         UnMimeHeader(msgblk.headers);
771     }
772     /* Check for MIME headers indicating possible 8-bit data */
773     ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
774
775     /*
776      * If there is a Return-Path address on the message, this was
777      * almost certainly the MAIL FROM address given the originating
778      * sendmail.  This is the best thing to use for logging the
779      * message origin (it sets up the right behavior for bounces and
780      * mailing lists).  Otherwise, fall down to the next available 
781      * envelope address (which is the most probable real sender).
782      * *** The order is important! ***
783      * This is especially useful when receiving mailing list
784      * messages in multidrop mode.  if a local address doesn't
785      * exist, the bounce message won't be returned blindly to the 
786      * author or to the list itself but rather to the list manager
787      * (ex: specified by "Sender:") which is much less annoying.  This 
788      * is true for most mailing list packages.
789      */
790     if( !msgblk.return_path[0] ){
791         char *ap = NULL;
792         if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
793         else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
794         else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
795         else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
796         else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
797         else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
798         if (ap) strcpy( msgblk.return_path, ap );
799     }
800
801     /* cons up a list of local recipients */
802     msgblk.recipients = (struct idlist *)NULL;
803     accept_count = reject_count = 0;
804     /* is this a multidrop box? */
805     if (MULTIDROP(ctl))
806     {
807         if (env_offs > -1)          /* We have the actual envelope addressee */
808             find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
809         else if (received_for)
810             /*
811              * We have the Received for addressee.  
812              * It has to be a mailserver address, or we
813              * wouldn't have got here.
814              * We use find_server_names() to let local 
815              * hostnames go through.
816              */
817             find_server_names(received_for, ctl, &msgblk.recipients);
818 #ifdef SDPS_ENABLE
819         else if (sdps_envto)
820         {
821             find_server_names(sdps_envto, ctl, &msgblk.recipients);
822             free(sdps_envto);
823         }
824 #endif /* SDPS_ENABLE */ 
825         else
826         {
827             /*
828              * We haven't extracted the envelope address.
829              * So check all the "Resent-To" header addresses if 
830              * they exist.  If and only if they don't, consider
831              * the "To" adresses.
832              */
833             register struct addrblk *nextptr;
834             if (resent_to_addrchain) {
835                 /* delete the "To" chain and substitute it 
836                  * with the "Resent-To" list 
837                  */
838                 while (to_addrchain) {
839                     nextptr = to_addrchain->next;
840                     free(to_addrchain);
841                     to_addrchain = nextptr;
842                 }
843                 to_addrchain = resent_to_addrchain;
844                 resent_to_addrchain = NULL;
845             }
846             /* now look for remaining adresses */
847             while (to_addrchain) {
848                 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
849                 nextptr = to_addrchain->next;
850                 free(to_addrchain);
851                 to_addrchain = nextptr;
852             }
853         }
854         if (!accept_count)
855         {
856             no_local_matches = TRUE;
857             save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
858             if (outlevel >= O_DEBUG)
859                 error(0, 0, 
860                       _("no local matches, forwarding to %s"),
861                       run.postmaster);
862         }
863     }
864     else        /* it's a single-drop box, use first localname */
865         save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
866
867
868     /*
869      * Time to either address the message or decide we can't deliver it yet.
870      */
871     if (ctl->errcount > olderrs)        /* there were DNS errors above */
872     {
873         if (outlevel >= O_DEBUG)
874             error(0,0, _("forwarding and deletion suppressed due to DNS errors"));
875         free(msgblk.headers);
876         free_str_list(&msgblk.recipients);
877         return(PS_TRANSIENT);
878     }
879     else
880     {
881         /* set up stuffline() so we can deliver the message body through it */ 
882         if ((n = open_sink(ctl, &msgblk,
883                            &good_addresses, &bad_addresses)) != PS_SUCCESS)
884         {
885             free(msgblk.headers);
886             free_str_list(&msgblk.recipients);
887             return(n);
888         }
889     }
890
891     n = 0;
892     /*
893      * Some server/sendmail combinations cause problems when our
894      * synthetic Received line is before the From header.  Cope
895      * with this...
896      */
897     if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
898         rcv = msgblk.headers;
899     /* handle ">Received:" lines too */
900     while (rcv > msgblk.headers && rcv[-1] != '\n')
901         rcv--;
902     if (rcv > msgblk.headers)
903     {
904         char    c = *rcv;
905
906         *rcv = '\0';
907         n = stuffline(ctl, msgblk.headers);
908         *rcv = c;
909     }
910     if (!run.invisible && n != -1)
911     {
912         /* utter any per-message Received information we need here */
913         sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
914         n = stuffline(ctl, buf);
915         if (n != -1)
916         {
917             /*
918              * This header is technically invalid under RFC822.
919              * POP3, IMAP, etc. are not legal mail-parameter values.
920              *
921              * We used to include ctl->remotename in this log line,
922              * but this can be secure information that would be bad
923              * to reveal.
924              */
925             sprintf(buf, "\tby %s with %s (fetchmail-%s)\r\n",
926                     fetchmailhost,
927                     protocol->name,
928                     RELEASE_ID);
929             n = stuffline(ctl, buf);
930             if (n != -1)
931             {
932                 buf[0] = '\t';
933                 if (good_addresses == 0)
934                 {
935                     sprintf(buf+1, 
936                             "for %s@%s (by default); ",
937                             user, ctl->destaddr);
938                 }
939                 else if (good_addresses == 1)
940                 {
941                     for (idp = msgblk.recipients; idp; idp = idp->next)
942                         if (idp->val.status.mark == XMIT_ACCEPT)
943                             break;      /* only report first address */
944                     if (strchr(idp->id, '@'))
945                         sprintf(buf+1, "for %s", idp->id);
946                     else
947                         /*
948                          * This could be a bit misleading, as destaddr is
949                          * the forwarding host rather than the actual 
950                          * destination.  Most of the time they coincide.
951                          */
952                         sprintf(buf+1, "for %s@%s", idp->id, ctl->destaddr);
953                     sprintf(buf+strlen(buf), " (%s); ",
954                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
955                 }
956                 else
957                     buf[1] = '\0';
958
959                 strcat(buf, rfc822timestamp());
960                 strcat(buf, "\r\n");
961                 n = stuffline(ctl, buf);
962             }
963         }
964     }
965
966     if (n != -1)
967         n = stuffline(ctl, rcv);        /* ship out rest of msgblk.headers */
968
969     if (n == -1)
970     {
971         error(0, errno, _("writing RFC822 msgblk.headers"));
972         release_sink(ctl);
973         free(msgblk.headers);
974         free_str_list(&msgblk.recipients);
975         return(PS_IOERR);
976     }
977     else if (!run.use_syslog && outlevel >= O_VERBOSE)
978         fputs("#", stderr);
979
980     /* write error notifications */
981     if (no_local_matches || has_nuls || bad_addresses)
982     {
983         int     errlen = 0;
984         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
985
986         errmsg = errhd;
987         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
988         if (no_local_matches)
989         {
990             if (reject_count != 1)
991                 strcat(errhd, _("no recipient addresses matched declared local names"));
992             else
993             {
994                 for (idp = msgblk.recipients; idp; idp = idp->next)
995                     if (idp->val.status.mark == XMIT_REJECT)
996                         break;
997                 sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
998             }
999         }
1000
1001         if (has_nuls)
1002         {
1003             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1004                 strcat(errhd, "; ");
1005             strcat(errhd, _("message has embedded NULs"));
1006         }
1007
1008         if (bad_addresses)
1009         {
1010             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1011                 strcat(errhd, "; ");
1012             strcat(errhd, _("SMTP listener rejected local recipient addresses: "));
1013             errlen = strlen(errhd);
1014             for (idp = msgblk.recipients; idp; idp = idp->next)
1015                 if (idp->val.status.mark == XMIT_ANTISPAM)
1016                     errlen += strlen(idp->id) + 2;
1017
1018             xalloca(errmsg, char *, errlen+3);
1019             (void) strcpy(errmsg, errhd);
1020             for (idp = msgblk.recipients; idp; idp = idp->next)
1021                 if (idp->val.status.mark == XMIT_ANTISPAM)
1022                 {
1023                     strcat(errmsg, idp->id);
1024                     if (idp->next)
1025                         strcat(errmsg, ", ");
1026                 }
1027
1028         }
1029
1030         strcat(errmsg, "\r\n");
1031
1032         /* ship out the error line */
1033         stuffline(ctl, errmsg);
1034     }
1035
1036     /* issue the delimiter line */
1037     cp = buf;
1038     *cp++ = '\r';
1039     *cp++ = '\n';
1040     *cp++ = '\0';
1041     stuffline(ctl, buf);
1042
1043     free(msgblk.headers);
1044     free_str_list(&msgblk.recipients);
1045     return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1046 }
1047
1048 static int readbody(int sock, struct query *ctl, flag forward, int len)
1049 /* read and dispose of a message body presented on sock */
1050 /*   ctl:               query control record */
1051 /*   sock:              to which the server is connected */
1052 /*   len:               length of message */
1053 /*   forward:           TRUE to forward */
1054 {
1055     int linelen;
1056     unsigned char buf[MSGBUFSIZE+4];
1057     unsigned char *inbufp = buf;
1058     flag issoftline = FALSE;
1059
1060     /* pass through the text lines */
1061     while (protocol->delimited || len > 0)
1062     {
1063         set_timeout(mytimeout);
1064         if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1065         {
1066             set_timeout(0);
1067             release_sink(ctl);
1068             return(PS_SOCKET);
1069         }
1070         set_timeout(0);
1071
1072         /* write the message size dots */
1073         if (linelen > 0)
1074         {
1075             sizeticker += linelen;
1076             while (sizeticker >= SIZETICKER)
1077             {
1078                 if (!run.use_syslog && outlevel > O_SILENT)
1079                     error_build(".");
1080                 sizeticker -= SIZETICKER;
1081             }
1082         }
1083         len -= linelen;
1084
1085         /* check for end of message */
1086         if (protocol->delimited && *inbufp == '.')
1087             if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1088                 break;
1089             else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1090                 break;
1091             else
1092                 msglen--;       /* subtract the size of the dot escape */
1093
1094         msglen += linelen;
1095
1096         if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1097             issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1098             if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1099             {
1100                 /*
1101                  * Soft linebreak, but less than 200 bytes left in
1102                  * input buffer. Rather than doing a buffer overrun,
1103                  * ignore the soft linebreak, NL-terminate data and
1104                  * deliver what we have now.
1105                  * (Who writes lines longer than 2K anyway?)
1106                  */
1107                 *inbufp = '\n'; *(inbufp+1) = '\0';
1108                 issoftline = 0;
1109             }
1110         }
1111
1112         /* ship out the text line */
1113         if (forward && (!issoftline))
1114         {
1115             int n;
1116             inbufp = buf;
1117
1118             /* guard against very long lines */
1119             buf[MSGBUFSIZE+1] = '\r';
1120             buf[MSGBUFSIZE+2] = '\n';
1121             buf[MSGBUFSIZE+3] = '\0';
1122
1123             n = stuffline(ctl, buf);
1124
1125             if (n < 0)
1126             {
1127                 error(0, errno, _("writing message text"));
1128                 release_sink(ctl);
1129                 return(PS_IOERR);
1130             }
1131             else if (outlevel >= O_VERBOSE)
1132                 fputc('*', stderr);
1133         }
1134     }
1135
1136     return(PS_SUCCESS);
1137 }
1138
1139 #ifdef KERBEROS_V4
1140 int
1141 kerberos_auth (socket, canonical) 
1142 /* authenticate to the server host using Kerberos V4 */
1143 int socket;             /* socket to server host */
1144 #ifdef __FreeBSD__
1145 char *canonical;        /* server name */
1146 #else
1147 const char *canonical;  /* server name */
1148 #endif
1149 {
1150     char * host_primary;
1151     KTEXT ticket;
1152     MSG_DAT msg_data;
1153     CREDENTIALS cred;
1154     Key_schedule schedule;
1155     int rem;
1156   
1157     xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1158     rem = (krb_sendauth (0L, socket, ticket, "pop",
1159                          canonical,
1160                          ((char *) (krb_realmofhost (canonical))),
1161                          ((unsigned long) 0),
1162                          (&msg_data),
1163                          (&cred),
1164                          (schedule),
1165                          ((struct sockaddr_in *) 0),
1166                          ((struct sockaddr_in *) 0),
1167                          "KPOPV0.1"));
1168     if (rem != KSUCCESS)
1169     {
1170         error(0, -1, _("kerberos error %s"), (krb_get_err_text (rem)));
1171         return (PS_AUTHFAIL);
1172     }
1173     return (0);
1174 }
1175 #endif /* KERBEROS_V4 */
1176
1177 #ifdef KERBEROS_V5
1178 int
1179 kerberos5_auth(socket, canonical)
1180 /* authenticate to the server host using Kerberos V5 */
1181 int socket;             /* socket to server host */
1182 const char *canonical;  /* server name */
1183 {
1184     krb5_error_code retval;
1185     krb5_context context;
1186     krb5_ccache ccdef;
1187     krb5_principal client = NULL, server = NULL;
1188     krb5_error *err_ret = NULL;
1189
1190     krb5_auth_context auth_context = NULL;
1191
1192     krb5_init_context(&context);
1193     krb5_init_ets(context);
1194     krb5_auth_con_init(context, &auth_context);
1195
1196     if (retval = krb5_cc_default(context, &ccdef)) {
1197         error(0, 0, "krb5_cc_default: %s", error_message(retval));
1198         return(PS_ERROR);
1199     }
1200
1201     if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1202         error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1203         return(PS_ERROR);
1204     }
1205
1206     if (retval = krb5_sname_to_principal(context, canonical, "pop",
1207            KRB5_NT_UNKNOWN,
1208            &server)) {
1209         error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1210         return(PS_ERROR);
1211     }
1212
1213     retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1214          "KPOPV1.0", client, server,
1215          AP_OPTS_MUTUAL_REQUIRED,
1216          NULL,  /* no data to checksum */
1217          0,   /* no creds, use ccache instead */
1218          ccdef,
1219          &err_ret, 0,
1220
1221          NULL); /* don't need reply */
1222
1223     krb5_free_principal(context, server);
1224     krb5_free_principal(context, client);
1225     krb5_auth_con_free(context, auth_context);
1226
1227     if (retval) {
1228       if (err_ret && err_ret->text.length) {
1229           error(0, 0, _("krb5_sendauth: %s [server says '%*s'] "),
1230             error_message(retval),
1231             err_ret->text.length,
1232             err_ret->text.data);
1233           krb5_free_error(context, err_ret);
1234       } else
1235           error(0, 0, "krb5_sendauth: %s", error_message(retval));
1236       return(PS_ERROR);
1237     }
1238
1239     return 0;
1240 }
1241 #endif /* KERBEROS_V5 */
1242
1243 static void clean_skipped_list(struct idlist **skipped_list)
1244 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1245 {
1246     struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1247     prev = current = head = *skipped_list;
1248
1249     if (!head)
1250         return;
1251     do
1252     {
1253         /* if item has no reference, remove it */
1254         if (current && current->val.status.mark == 0)
1255         {
1256             if (current == head) /* remove first item (head) */
1257             {
1258                 head = current->next;
1259                 if (current->id) free(current->id);
1260                 free(current);
1261                 prev = current = head;
1262             }
1263             else /* remove middle/last item */
1264             {
1265                 tmp = current->next;
1266                 prev->next = tmp;
1267                 if (current->id) free(current->id);
1268                 free(current);
1269                 current = tmp;
1270             }
1271         }
1272         else /* skip this item */
1273         {
1274             prev = current;
1275             current = current->next;
1276         }
1277     } while(current);
1278
1279     *skipped_list = head;
1280 }
1281
1282 static void send_size_warnings(struct query *ctl)
1283 /* send warning mail with skipped msg; reset msg count when user notified */
1284 {
1285     int size, nbr;
1286     int msg_to_send = FALSE;
1287     struct idlist *head=NULL, *current=NULL;
1288     int max_warning_poll_count, good, bad;
1289 #define OVERHD  "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server:"
1290
1291     head = ctl->skipped;
1292     if (!head)
1293         return;
1294
1295     /* don't start a notification message unless we need to */
1296     for (current = head; current; current = current->next)
1297         if (current->val.status.num == 0 && current->val.status.mark)
1298             msg_to_send = TRUE;
1299     if (!msg_to_send)
1300         return;
1301
1302     /*
1303      * There's no good way to recover if we can't send notification mail, 
1304      * but it's not a disaster, either, since the skipped mail will not
1305      * be deleted.
1306      */
1307     if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
1308         return;
1309     stuff_warning(ctl, OVERHD);
1310  
1311     if (run.poll_interval == 0)
1312         max_warning_poll_count = 0;
1313     else
1314         max_warning_poll_count = ctl->warnings/run.poll_interval;
1315
1316     /* parse list of skipped msg, adding items to the mail */
1317     for (current = head; current; current = current->next)
1318     {
1319         if (current->val.status.num == 0 && current->val.status.mark)
1320         {
1321             nbr = current->val.status.mark;
1322             size = atoi(current->id);
1323             stuff_warning(ctl, 
1324                     _("\t%d msg %d octets long skipped by fetchmail."),
1325                     nbr, size);
1326         }
1327         current->val.status.num++;
1328         current->val.status.mark = 0;
1329
1330         if (current->val.status.num >= max_warning_poll_count)
1331             current->val.status.num = 0;
1332     }
1333
1334     close_warning_by_mail(ctl, (struct msgblk *)NULL);
1335 #undef OVERHD
1336 }
1337
1338 int do_protocol(ctl, proto)
1339 /* retrieve messages from server using given protocol method table */
1340 struct query *ctl;              /* parsed options with merged-in defaults */
1341 const struct method *proto;     /* protocol method table */
1342 {
1343     int ok, js;
1344 #ifdef HAVE_VOLATILE
1345     volatile int sock = -1;     /* pacifies -Wall */
1346 #else
1347     int sock = -1;
1348 #endif /* HAVE_VOLATILE */
1349     const char *msg;
1350     void (*sigsave)(int);
1351     struct idlist *current=NULL, *tmp=NULL;
1352
1353     protocol = proto;
1354     ctl->server.base_protocol = protocol;
1355
1356 #ifndef KERBEROS_V4
1357     if (ctl->server.preauthenticate == A_KERBEROS_V4)
1358     {
1359         error(0, -1, _("Kerberos V4 support not linked."));
1360         return(PS_ERROR);
1361     }
1362 #endif /* KERBEROS_V4 */
1363
1364 #ifndef KERBEROS_V5
1365     if (ctl->server.preauthenticate == A_KERBEROS_V5)
1366     {
1367         error(0, -1, _("Kerberos V5 support not linked."));
1368         return(PS_ERROR);
1369     }
1370 #endif /* KERBEROS_V5 */
1371
1372     /* lacking methods, there are some options that may fail */
1373     if (!proto->is_old)
1374     {
1375         /* check for unsupported options */
1376         if (ctl->flush) {
1377             error(0, 0,
1378                     _("Option --flush is not supported with %s"),
1379                     proto->name);
1380             return(PS_SYNTAX);
1381         }
1382         else if (ctl->fetchall) {
1383             error(0, 0,
1384                     _("Option --all is not supported with %s"),
1385                     proto->name);
1386             return(PS_SYNTAX);
1387         }
1388     }
1389     if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1390     {
1391         error(0, 0,
1392                 _("Option --limit is not supported with %s"),
1393                 proto->name);
1394         return(PS_SYNTAX);
1395     }
1396
1397     pass = 0;
1398     tagnum = 0;
1399     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1400     ok = 0;
1401
1402     /* set up the server-nonresponse timeout */
1403     sigsave = signal(SIGALRM, timeout_handler);
1404     mytimeout = ctl->server.timeout;
1405
1406     if ((js = setjmp(restart)) == 1)
1407     {
1408         if (phase == OPEN_WAIT)
1409             error(0, 0,
1410                   _("timeout after %d seconds waiting to connect to server %s."),
1411                   ctl->server.timeout, ctl->server.pollname);
1412         else if (phase == SERVER_WAIT)
1413             error(0, 0,
1414                   _("timeout after %d seconds waiting for server %s."),
1415                   ctl->server.timeout, ctl->server.pollname);
1416         else if (phase == FORWARDING_WAIT)
1417             error(0, 0,
1418                   _("timeout after %d seconds waiting for %s."),
1419                   ctl->server.timeout,
1420                   ctl->mda ? "MDA" : "SMTP");
1421         else if (phase == LISTENER_WAIT)
1422             error(0, 0,
1423                   _("timeout after %d seconds waiting for listener to respond."));
1424         else
1425             error(0, 0, _("timeout after %d seconds."), ctl->server.timeout);
1426
1427         release_sink(ctl);
1428         if (ctl->smtp_socket != -1)
1429             close(ctl->smtp_socket);
1430         if (sock != -1)
1431             SockClose(sock);
1432
1433         /*
1434          * If we've exceeded our threshold for consecutive timeouts, 
1435          * try to notify the user, then mark the connection wedged.
1436          */
1437         if (timeoutcount > MAX_TIMEOUTS 
1438                         && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1439         {
1440             stuff_warning(ctl,
1441                           _("Subject: fetchmail sees repeated timeouts\r\n"));
1442             stuff_warning(ctl,
1443                           _("Fetchmail saw more than %d timouts while attempting to get mail from %s@%s."), 
1444                           MAX_TIMEOUTS,
1445                           ctl->remotename,
1446                           ctl->server.truename);
1447             stuff_warning(ctl, 
1448                           _("This could mean that your mailserver is stuck, or that your SMTP listener"));
1449             stuff_warning(ctl, 
1450                           _("is wedged, or that your mailbox file on the server has been corrupted by"));
1451             stuff_warning(ctl, 
1452                           _("a server error.  You can run `fetchmail -v -v' to diagnose the problem."));
1453             stuff_warning(ctl,
1454                           _("Fetchmail won't poll this mailbox again until you restart it."));
1455             close_warning_by_mail(ctl, (struct msgblk *)NULL);
1456             ctl->wedged = TRUE;
1457         }
1458
1459         ok = PS_ERROR;
1460     }
1461     else
1462     {
1463         char buf[POPBUFSIZE+1], *realhost;
1464         int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1465 #if INET6
1466         int fetches, dispatches;
1467 #else /* INET6 */
1468         int port, fetches, dispatches, oldphase;
1469 #endif /* INET6 */
1470         struct idlist *idp;
1471
1472         /* execute pre-initialization command, if any */
1473         if (ctl->preconnect && (ok = system(ctl->preconnect)))
1474         {
1475             sprintf(buf, _("pre-connection command failed with status %d"), ok);
1476             error(0, 0, buf);
1477             ok = PS_SYNTAX;
1478             goto closeUp;
1479         }
1480
1481         /* open a socket to the mail server */
1482         oldphase = phase;
1483         phase = OPEN_WAIT;
1484         set_timeout(mytimeout);
1485 #if !INET6
1486         port = ctl->server.port ? ctl->server.port : protocol->port;
1487 #endif /* !INET6 */
1488         realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1489 #if INET6
1490         if ((sock = SockOpen(realhost, 
1491                              ctl->server.service ? ctl->server.service : protocol->service,
1492                              ctl->server.netsec)) == -1, ctl->server.plugin
1493             )
1494 #else /* INET6 */
1495         if ((sock = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1496 #endif /* INET6 */
1497         {
1498 #if !INET6
1499             int err_no = errno;
1500 #ifdef HAVE_RES_SEARCH
1501             if (err_no != 0 && h_errno != 0)
1502                 error(0, 0, _("fetchmail: internal inconsistency"));
1503 #endif
1504             /*
1505              * Avoid generating a bogus error every poll cycle when we're
1506              * in daemon mode but the connection to the outside world
1507              * is down.
1508              */
1509             if (err_no == EHOSTUNREACH && run.poll_interval)
1510                 goto ehostunreach;
1511
1512             error_build(_("fetchmail: %s connection to %s failed"), 
1513                          protocol->name, ctl->server.pollname);
1514 #ifdef HAVE_RES_SEARCH
1515             if (h_errno != 0)
1516             {
1517                 if (h_errno == HOST_NOT_FOUND)
1518                     error_complete(0, 0, _(": host is unknown"));
1519                 else if (h_errno == NO_ADDRESS)
1520                     error_complete(0, 0, _(": name is valid but has no IP address"));
1521                 else if (h_errno == NO_RECOVERY)
1522                     error_complete(0, 0, _(": unrecoverable name server error"));
1523                 else if (h_errno == TRY_AGAIN)
1524                     error_complete(0, 0, _(": temporary name server error"));
1525                 else
1526                     error_complete(0, 0, _(": unknown DNS error %d"), h_errno);
1527             }
1528             else
1529 #endif /* HAVE_RES_SEARCH */
1530
1531                 error_complete(0, err_no, "");
1532
1533         ehostunreach:
1534 #endif /* INET6 */
1535             ok = PS_SOCKET;
1536             set_timeout(0);
1537             phase = oldphase;
1538             goto closeUp;
1539         }
1540         set_timeout(0);
1541         phase = oldphase;
1542
1543 #ifdef KERBEROS_V4
1544         if (ctl->server.preauthenticate == A_KERBEROS_V4)
1545         {
1546             set_timeout(mytimeout);
1547             ok = kerberos_auth(sock, ctl->server.truename);
1548             set_timeout(0);
1549             if (ok != 0)
1550                 goto cleanUp;
1551         }
1552 #endif /* KERBEROS_V4 */
1553
1554 #ifdef KERBEROS_V5
1555         if (ctl->server.preauthenticate == A_KERBEROS_V5)
1556         {
1557             set_timeout(mytimeout);
1558             ok = kerberos5_auth(sock, ctl->server.truename);
1559             set_timeout(0);
1560             if (ok != 0)
1561                 goto cleanUp;
1562         }
1563 #endif /* KERBEROS_V5 */
1564
1565         /* accept greeting message from mail server */
1566         ok = (protocol->parse_response)(sock, buf);
1567         if (ok != 0)
1568             goto cleanUp;
1569
1570         /* try to get authorized to fetch mail */
1571         if (protocol->getauth)
1572         {
1573             if (protocol->password_canonify)
1574                 (protocol->password_canonify)(shroud, ctl->password);
1575             else
1576                 strcpy(shroud, ctl->password);
1577
1578             ok = (protocol->getauth)(sock, ctl, buf);
1579             if (ok != 0)
1580             {
1581                 if (ok == PS_LOCKBUSY)
1582                     error(0, -1, _("Lock-busy error on %s@%s"),
1583                           ctl->remotename,
1584                           ctl->server.truename);
1585                 else
1586                 {
1587                     if (ok == PS_ERROR)
1588                         ok = PS_AUTHFAIL;
1589                     error(0, -1, _("Authorization failure on %s@%s"), 
1590                           ctl->remotename,
1591                           ctl->server.truename);
1592
1593                     /*
1594                      * If we're running in background, try to mail the
1595                      * calling user a heads-up about the authentication 
1596                      * failure the first time it happens.
1597                      */
1598                     if (run.poll_interval
1599                         && !ctl->wedged 
1600                         && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1601                     {
1602                         stuff_warning(ctl,
1603                                _("Subject: fetchmail authentication failed\r\n"));
1604                         stuff_warning(ctl,
1605                                 _("Fetchmail could not get mail from %s@%s."), 
1606                                 ctl->remotename,
1607                                 ctl->server.truename);
1608                         stuff_warning(ctl, 
1609                                _("The attempt to get authorization failed."));
1610                         stuff_warning(ctl, 
1611                                _("This probably means your password is invalid."));
1612                         close_warning_by_mail(ctl, (struct msgblk *)NULL);
1613                         ctl->wedged = TRUE;
1614                     }
1615                 }
1616                 goto cleanUp;
1617             }
1618         }
1619
1620         ctl->errcount = fetches = 0;
1621
1622         /* now iterate over each folder selected */
1623         for (idp = ctl->mailboxes; idp; idp = idp->next)
1624         {
1625             pass = 0;
1626             do {
1627                 dispatches = 0;
1628                 ++pass;
1629
1630                 if (outlevel >= O_DEBUG)
1631                     if (idp->id)
1632                         error(0, 0, _("selecting or re-polling folder %s"), idp->id);
1633                     else
1634                         error(0, 0, _("selecting or re-polling default folder"));
1635
1636                 /* compute # of messages and number of new messages waiting */
1637                 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1638                 if (ok != 0)
1639                     goto cleanUp;
1640
1641                 /* 
1642                  * We need the size of each message before it's
1643                  * loaded in order to pass via the ESMTP SIZE
1644                  * option.  If the protocol has a getsizes method,
1645                  * we presume this means it doesn't get reliable
1646                  * sizes from message fetch responses.
1647                  */
1648                 if (count > 0 && proto->getsizes)
1649                 {
1650                     int i;
1651
1652                     xalloca(msgsizes, int *, sizeof(int) * count);
1653                     for (i = 0; i < count; i++)
1654                         msgsizes[i] = -1;
1655
1656                     ok = (proto->getsizes)(sock, count, msgsizes);
1657                     if (ok != 0)
1658                         goto cleanUp;
1659
1660                     if (bytes == -1)
1661                     {
1662                         bytes = 0;
1663                         for (i = 0; i < count; i++)
1664                             bytes += msgsizes[i];
1665                     }
1666                 }
1667
1668                 /* show user how many messages we downloaded */
1669                 if (idp->id)
1670                     (void) sprintf(buf, _("%s at %s (folder %s)"),
1671                                    ctl->remotename, ctl->server.truename, idp->id);
1672                 else
1673                     (void) sprintf(buf, _("%s at %s"),
1674                                    ctl->remotename, ctl->server.truename);
1675                 if (outlevel > O_SILENT)
1676                     if (count == -1)            /* only used for ETRN */
1677                         error(0, 0, _("Polling %s"), ctl->server.truename);
1678                     else if (count != 0)
1679                     {
1680                         if (new != -1 && (count - new) > 0)
1681                             error_build(_("%d %s (%d seen) for %s"),
1682                                   count, count > 1 ? _("messages") :
1683                                                      _("message"),
1684                                   count-new, buf);
1685                         else
1686                             error_build(_("%d %s for %s"), 
1687                                   count, count > 1 ? _("messages") :
1688                                                      _("message"), buf);
1689                         if (bytes == -1)
1690                             error_complete(0, 0, ".");
1691                         else
1692                             error_complete(0, 0, _(" (%d octets)."), bytes);
1693                     }
1694                     else
1695                     {
1696                         /* these are pointless in normal daemon mode */
1697                         if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1698                             error(0, 0, _("No mail for %s"), buf); 
1699                     }
1700
1701                 /* very important, this is where we leave the do loop */ 
1702                 if (count == 0)
1703                     break;
1704
1705                 if (check_only)
1706                 {
1707                     if (new == -1 || ctl->fetchall)
1708                         new = count;
1709                     ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1710                     goto cleanUp;
1711                 }
1712                 else if (count > 0)
1713                 {    
1714                     flag        force_retrieval;
1715
1716                     /*
1717                      * What forces this code is that in POP2 and
1718                      * IMAP2bis you can't fetch a message without
1719                      * having it marked `seen'.  In POP3 and IMAP4, on the
1720                      * other hand, you can (peek_capable is set by 
1721                      * each driver module to convey this; it's not a
1722                      * method constant because of the difference between
1723                      * IMAP2bis and IMAP4, and because POP3 doesn't  peek
1724                      * if fetchall is on).
1725                      *
1726                      * The result of being unable to peek is that if there's
1727                      * any kind of transient error (DNS lookup failure, or
1728                      * sendmail refusing delivery due to process-table limits)
1729                      * the message will be marked "seen" on the server without
1730                      * having been delivered.  This is not a big problem if
1731                      * fetchmail is running in foreground, because the user
1732                      * will see a "skipped" message when it next runs and get
1733                      * clued in.
1734                      *
1735                      * But in daemon mode this leads to the message
1736                      * being silently ignored forever.  This is not
1737                      * acceptable.
1738                      *
1739                      * We compensate for this by checking the error
1740                      * count from the previous pass and forcing all
1741                      * messages to be considered new if it's nonzero.
1742                      */
1743                     force_retrieval = !peek_capable && (ctl->errcount > 0);
1744
1745                     /* read, forward, and delete messages */
1746                     for (num = 1; num <= count; num++)
1747                     {
1748                         flag toolarge = NUM_NONZERO(ctl->limit)
1749                             && msgsizes && (msgsizes[num-1] > ctl->limit);
1750                         flag oldmsg = (protocol->is_old && (protocol->is_old)(sock,ctl,num));
1751                         flag fetch_it = !toolarge 
1752                             && (ctl->fetchall || force_retrieval || !oldmsg);
1753                         flag suppress_delete = FALSE;
1754                         flag suppress_forward = FALSE;
1755                         flag suppress_readbody = FALSE;
1756                         flag retained = FALSE;
1757
1758                         /*
1759                          * This check copes with Post Office/NT's
1760                          * annoying habit of randomly prepending bogus
1761                          * LIST items of length -1.  Patrick Audley
1762                          * <paudley@pobox.com> tells us: LIST shows a
1763                          * size of -1, RETR and TOP return "-ERR
1764                          * System error - couldn't open message", and
1765                          * DELE succeeds but doesn't actually delete
1766                          * the message.
1767                          */
1768                         if (msgsizes && msgsizes[num-1] == -1)
1769                         {
1770                             if (outlevel >= O_VERBOSE)
1771                                 error(0, 0, 
1772                                       _("Skipping message %d, length -1"),
1773                                       num - 1);
1774                             continue;
1775                         }
1776
1777                         /* we may want to reject this message if it's old */
1778                         if (!fetch_it)
1779                         {
1780                             if (outlevel > O_SILENT)
1781                             {
1782                                 error_build(_("skipping message %d"), num);
1783                                 if (toolarge && !check_only) 
1784                                 {
1785                                     char size[32];
1786                                     int cnt;
1787
1788                                     /* convert sz to string */
1789                                     sprintf(size, "%d", msgsizes[num-1]);
1790
1791                                     /* build a list of skipped messages
1792                                      * val.id = size of msg (string cnvt)
1793                                      * val.status.num = warning_poll_count
1794                                      * val.status.mask = nbr of msg this size
1795                                      */
1796
1797                                     current = ctl->skipped;
1798
1799                                     /* initialise warning_poll_count to the
1800                                      * current value so that all new msg will
1801                                      * be included in the next mail
1802                                      */
1803                                     cnt = current? current->val.status.num : 0;
1804
1805                                     /* if entry exists, increment the count */
1806                                     if (current && 
1807                                         str_in_list(&current, size, FALSE))
1808                                     {
1809                                         for ( ; current; 
1810                                                 current = current->next)
1811                                         {
1812                                             if (strcmp(current->id, size) == 0)
1813                                             {
1814                                                 current->val.status.mark++;
1815                                                 break;
1816                                             }
1817                                         }
1818                                     }
1819                                     /* otherwise, create a new entry */
1820                                     /* initialise with current poll count */
1821                                     else
1822                                     {
1823                                         tmp = save_str(&ctl->skipped, size, 1);
1824                                         tmp->val.status.num = cnt;
1825                                     }
1826
1827                                     error_build(_(" (oversized, %d octets)"),
1828                                                 msgsizes[num-1]);
1829                                 }
1830                             }
1831                         }
1832                         else
1833                         {
1834                             flag wholesize = !protocol->fetch_body;
1835
1836                             /* request a message */
1837                             ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1838                             if (ok != 0)
1839                                 goto cleanUp;
1840
1841                             /* -1 means we didn't see a size in the response */
1842                             if (len == -1 && msgsizes)
1843                             {
1844                                 len = msgsizes[num - 1];
1845                                 wholesize = TRUE;
1846                             }
1847
1848                             if (outlevel > O_SILENT)
1849                             {
1850                                 error_build(_("reading message %d of %d"),
1851                                             num,count);
1852
1853                                 if (len > 0)
1854                                     error_build(_(" (%d %soctets)"),
1855                                         len, wholesize ? "" : _("header "));
1856                                 if (outlevel >= O_VERBOSE)
1857                                     error_complete(0, 0, "");
1858                                 else
1859                                     error_build(" ");
1860                             }
1861
1862                             /* 
1863                              * Read the message headers and ship them to the
1864                              * output sink.  
1865                              */
1866                             ok = readheaders(sock, len, msgsizes[num-1],
1867                                              ctl, num);
1868                             if (ok == PS_RETAINED)
1869                                 suppress_forward = retained = TRUE;
1870                             else if (ok == PS_TRANSIENT)
1871                                 suppress_delete = suppress_forward = TRUE;
1872                             else if (ok == PS_REFUSED)
1873                                 suppress_forward = TRUE;
1874                             else if (ok == PS_TRUNCATED)
1875                                 suppress_readbody = TRUE;
1876                             else if (ok)
1877                                 goto cleanUp;
1878
1879                             /* 
1880                              * If we're using IMAP4 or something else that
1881                              * can fetch headers separately from bodies,
1882                              * it's time to request the body now.  This
1883                              * fetch may be skipped if we got an anti-spam
1884                              * or other PS_REFUSED error response during
1885                              * readheaders.
1886                              */
1887                             if (protocol->fetch_body && !suppress_readbody) 
1888                             {
1889                                 if (outlevel >= O_VERBOSE)
1890                                     fputc('\n', stderr);
1891
1892                                 if ((ok = (protocol->trail)(sock, ctl, num)))
1893                                     goto cleanUp;
1894                                 len = 0;
1895                                 if (!suppress_forward)
1896                                 {
1897                                     if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1898                                         goto cleanUp;
1899                                     if (outlevel > O_SILENT && !wholesize)
1900                                         error_build(_(" (%d body octets) "), len);
1901                                 }
1902                             }
1903
1904                             /* process the body now */
1905                             if (len > 0)
1906                             {
1907                                 if (suppress_readbody)
1908                                 {
1909                                   /* When readheaders returns PS_TRUNCATED,
1910                                      the body (which has no content
1911                                      has already been read by readheaders,
1912                                      so we say readbody returned PS_SUCCESS */
1913                                   ok = PS_SUCCESS;
1914                                 }
1915                                 else
1916                                 {
1917                                   ok = readbody(sock,
1918                                                 ctl,
1919                                                 !suppress_forward,
1920                                                 len);
1921                                 }
1922                                 if (ok == PS_TRANSIENT)
1923                                     suppress_delete = suppress_forward = TRUE;
1924                                 else if (ok)
1925                                     goto cleanUp;
1926
1927                                 /* tell server we got it OK and resynchronize */
1928                                 if (protocol->trail)
1929                                 {
1930                                     if (outlevel >= O_VERBOSE)
1931                                         fputc('\n', stderr);
1932
1933                                     ok = (protocol->trail)(sock, ctl, num);
1934                                     if (ok != 0)
1935                                         goto cleanUp;
1936                                 }
1937                             }
1938
1939                             /* count # messages forwarded on this pass */
1940                             if (!suppress_forward)
1941                                 dispatches++;
1942
1943                             /*
1944                              * Check to see if the numbers matched?
1945                              *
1946                              * Yes, some servers foo this up horribly.
1947                              * All IMAP servers seem to get it right, and
1948                              * so does Eudora QPOP at least in 2.xx
1949                              * versions.
1950                              *
1951                              * Microsoft Exchange gets it completely
1952                              * wrong, reporting compressed rather than
1953                              * actual sizes (so the actual length of
1954                              * message is longer than the reported size).
1955                              * Another fine example of Microsoft brain death!
1956                              *
1957                              * Some older POP servers, like the old UCB
1958                              * POP server and the pre-QPOP QUALCOMM
1959                              * versions, report a longer size in the LIST
1960                              * response than actually gets shipped up.
1961                              * It's unclear what is going on here, as the
1962                              * QUALCOMM server (at least) seems to be
1963                              * reporting the on-disk size correctly.
1964                              */
1965                             if (msgsizes && msglen != msgsizes[num-1])
1966                             {
1967                                 if (outlevel >= O_DEBUG)
1968                                     error(0, 0,
1969                                           _("message %d was not the expected length (%d actual != %d expected)"),
1970                                           num, msglen, msgsizes[num-1]);
1971                             }
1972
1973                             /* end-of-message processing starts here */
1974                             if (!close_sink(ctl, &msgblk, !suppress_forward))
1975                             {
1976                                 ctl->errcount++;
1977                                 suppress_delete = TRUE;
1978                             }
1979                             fetches++;
1980                         }
1981
1982                         /*
1983                          * At this point in flow of control, either
1984                          * we've bombed on a protocol error or had
1985                          * delivery refused by the SMTP server
1986                          * (unlikely -- I've never seen it) or we've
1987                          * seen `accepted for delivery' and the
1988                          * message is shipped.  It's safe to mark the
1989                          * message seen and delete it on the server
1990                          * now.
1991                          */
1992
1993                         /* tell the UID code we've seen this */
1994                         if (ctl->newsaved)
1995                         {
1996                             struct idlist       *sdp;
1997
1998                             for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
1999                                 if (sdp->val.status.num == num)
2000                                     sdp->val.status.mark = UID_SEEN;
2001                         }
2002
2003                         /* maybe we delete this message now? */
2004                         if (retained)
2005                         {
2006                             if (outlevel > O_SILENT) 
2007                                 error_complete(0, 0, _(" retained"));
2008                         }
2009                         else if (protocol->delete
2010                                  && !suppress_delete
2011                                  && (fetch_it ? !ctl->keep : ctl->flush))
2012                         {
2013                             deletions++;
2014                             if (outlevel > O_SILENT) 
2015                                 error_complete(0, 0, _(" flushed"));
2016                             ok = (protocol->delete)(sock, ctl, num);
2017                             if (ok != 0)
2018                                 goto cleanUp;
2019 #ifdef POP3_ENABLE
2020                             delete_str(&ctl->newsaved, num);
2021 #endif /* POP3_ENABLE */
2022                         }
2023                         else if (outlevel > O_SILENT) 
2024                             error_complete(0, 0, _(" not flushed"));
2025
2026                         /* perhaps this as many as we're ready to handle */
2027                         if (NUM_NONZERO(ctl->fetchlimit)
2028                                         && ctl->fetchlimit <= fetches)
2029                         {
2030                             error(0, 0, _("fetchlimit reached; %d messages left on server"),
2031                                   count - fetches);
2032                             goto no_error;
2033                         }
2034                     }
2035
2036                     if (!check_only && ctl->skipped)
2037                     {
2038                         clean_skipped_list(&ctl->skipped);
2039                         send_size_warnings(ctl);
2040                     }
2041                 }
2042             } while
2043                   /*
2044                    * Only re-poll if we had some actual forwards, allowed
2045                    * deletions and had no errors.
2046                    * Otherwise it is far too easy to get into infinite loops.
2047                    */
2048                   (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2049         }
2050
2051    no_error:
2052         ok = (protocol->logout_cmd)(sock, ctl);
2053         /*
2054          * Hmmmm...arguably this would be incorrect if we had fetches but
2055          * no dispatches (due to oversized messages, etc.)
2056          */
2057         if (ok == 0)
2058             ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2059         SockClose(sock);
2060         goto closeUp;
2061
2062     cleanUp:
2063         if (ok != 0 && ok != PS_SOCKET)
2064             (protocol->logout_cmd)(sock, ctl);
2065         SockClose(sock);
2066     }
2067
2068     msg = (const char *)NULL;   /* sacrifice to -Wall */
2069     switch (ok)
2070     {
2071     case PS_SOCKET:
2072         msg = _("socket");
2073         break;
2074     case PS_AUTHFAIL:
2075         msg = _("authorization");
2076         break;
2077     case PS_SYNTAX:
2078         msg = _("missing or bad RFC822 header");
2079         break;
2080     case PS_IOERR:
2081         msg = _("MDA");
2082         break;
2083     case PS_ERROR:
2084         msg = _("client/server synchronization");
2085         break;
2086     case PS_PROTOCOL:
2087         msg = _("client/server protocol");
2088         break;
2089     case PS_LOCKBUSY:
2090         msg = _("lock busy on server");
2091         break;
2092     case PS_SMTP:
2093         msg = _("SMTP transaction");
2094         break;
2095     case PS_DNS:
2096         msg = _("DNS lookup");
2097         break;
2098     case PS_UNDEFINED:
2099         error(0, 0, _("undefined"));
2100         break;
2101     }
2102     if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX 
2103                 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL 
2104                 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2105         error(0,-1, _("%s error while fetching from %s"), msg, ctl->server.pollname);
2106
2107 closeUp:
2108     /* execute post-initialization command, if any */
2109     if (ctl->postconnect && (ok = system(ctl->postconnect)))
2110     {
2111         char buf[80];
2112
2113         sprintf(buf, _("post-connection command failed with status %d"), ok);
2114         error(0, 0, buf);
2115         if (ok == PS_SUCCESS)
2116             ok = PS_SYNTAX;
2117     }
2118
2119     signal(SIGALRM, sigsave);
2120     return(ok);
2121 }
2122
2123 #if defined(HAVE_STDARG_H)
2124 void gen_send(int sock, const char *fmt, ... )
2125 #else
2126 void gen_send(sock, fmt, va_alist)
2127 int sock;               /* socket to which server is connected */
2128 const char *fmt;        /* printf-style format */
2129 va_dcl
2130 #endif
2131 /* assemble command in printf(3) style and send to the server */
2132 {
2133     char buf [MSGBUFSIZE+1];
2134     va_list ap;
2135
2136     if (protocol->tagged)
2137         (void) sprintf(buf, "%s ", GENSYM);
2138     else
2139         buf[0] = '\0';
2140
2141 #if defined(HAVE_STDARG_H)
2142     va_start(ap, fmt) ;
2143 #else
2144     va_start(ap);
2145 #endif
2146 #ifdef HAVE_VSNPRINTF
2147     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2148 #else
2149     vsprintf(buf + strlen(buf), fmt, ap);
2150 #endif
2151     va_end(ap);
2152
2153     strcat(buf, "\r\n");
2154     SockWrite(sock, buf, strlen(buf));
2155
2156     if (outlevel >= O_MONITOR)
2157     {
2158         char *cp;
2159
2160         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2161         {
2162             char        *sp;
2163
2164             sp = cp + strlen(shroud);
2165             *cp++ = '*';
2166             while (*sp)
2167                 *cp++ = *sp++;
2168             *cp = '\0';
2169         }
2170         buf[strlen(buf)-2] = '\0';
2171         error(0, 0, "%s> %s", protocol->name, buf);
2172     }
2173 }
2174
2175 int gen_recv(sock, buf, size)
2176 /* get one line of input from the server */
2177 int sock;       /* socket to which server is connected */
2178 char *buf;      /* buffer to receive input */
2179 int size;       /* length of buffer */
2180 {
2181     int oldphase = phase;       /* we don't have to be re-entrant */
2182
2183     phase = SERVER_WAIT;
2184     set_timeout(mytimeout);
2185     if (SockRead(sock, buf, size) == -1)
2186     {
2187         set_timeout(0);
2188         phase = oldphase;
2189         return(PS_SOCKET);
2190     }
2191     else
2192     {
2193         set_timeout(0);
2194         if (buf[strlen(buf)-1] == '\n')
2195             buf[strlen(buf)-1] = '\0';
2196         if (buf[strlen(buf)-1] == '\r')
2197             buf[strlen(buf)-1] = '\0';
2198         if (outlevel >= O_MONITOR)
2199             error(0, 0, "%s< %s", protocol->name, buf);
2200         phase = oldphase;
2201         return(PS_SUCCESS);
2202     }
2203 }
2204
2205 #if defined(HAVE_STDARG_H)
2206 int gen_transact(int sock, const char *fmt, ... )
2207 #else
2208 int gen_transact(int sock, fmt, va_alist)
2209 int sock;               /* socket to which server is connected */
2210 const char *fmt;        /* printf-style format */
2211 va_dcl
2212 #endif
2213 /* assemble command in printf(3) style, send to server, accept a response */
2214 {
2215     int ok;
2216     char buf [MSGBUFSIZE+1];
2217     va_list ap;
2218     int oldphase = phase;       /* we don't have to be re-entrant */
2219
2220     phase = SERVER_WAIT;
2221
2222     if (protocol->tagged)
2223         (void) sprintf(buf, "%s ", GENSYM);
2224     else
2225         buf[0] = '\0';
2226
2227 #if defined(HAVE_STDARG_H)
2228     va_start(ap, fmt) ;
2229 #else
2230     va_start(ap);
2231 #endif
2232 #ifdef HAVE_VSNPRINTF
2233     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2234 #else
2235     vsprintf(buf + strlen(buf), fmt, ap);
2236 #endif
2237     va_end(ap);
2238
2239     strcat(buf, "\r\n");
2240     SockWrite(sock, buf, strlen(buf));
2241
2242     if (outlevel >= O_MONITOR)
2243     {
2244         char *cp;
2245
2246         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2247         {
2248             char        *sp;
2249
2250             sp = cp + strlen(shroud);
2251             *cp++ = '*';
2252             while (*sp)
2253                 *cp++ = *sp++;
2254             *cp = '\0';
2255         }
2256         buf[strlen(buf)-1] = '\0';
2257         error(0, 0, "%s> %s", protocol->name, buf);
2258     }
2259
2260     /* we presume this does its own response echoing */
2261     ok = (protocol->parse_response)(sock, buf);
2262
2263     phase = oldphase;
2264     return(ok);
2265 }
2266
2267 /* driver.c ends here */