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