]> Pileus Git - ~andy/fetchmail/blob - driver.c
Avoid false positives in Received parsing.
[~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              * We used to include ctl->remotename in this log line,
919              * but this can be secure information that would be bad
920              * to reveal.
921              */
922             sprintf(buf, "\tby fetchmail-%s %s\r\n",
923                     RELEASE_ID,
924                     protocol->name);
925             n = stuffline(ctl, buf);
926             if (n != -1)
927             {
928                 buf[0] = '\t';
929                 if (good_addresses == 0)
930                 {
931                     sprintf(buf+1, 
932                             "for %s@%s (by default); ",
933                             user, ctl->destaddr);
934                 }
935                 else if (good_addresses == 1)
936                 {
937                     for (idp = msgblk.recipients; idp; idp = idp->next)
938                         if (idp->val.status.mark == XMIT_ACCEPT)
939                             break;      /* only report first address */
940                     if (strchr(idp->id, '@'))
941                         sprintf(buf+1, "for %s", idp->id);
942                     else
943                         sprintf(buf+1, "for %s/%s", idp->id, ctl->destaddr);
944                     sprintf(buf+strlen(buf), " (%s); ",
945                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
946                 }
947                 else
948                     buf[1] = '\0';
949
950                 strcat(buf, rfc822timestamp());
951                 strcat(buf, "\r\n");
952                 n = stuffline(ctl, buf);
953             }
954         }
955     }
956
957     if (n != -1)
958         n = stuffline(ctl, rcv);        /* ship out rest of msgblk.headers */
959
960     if (n == -1)
961     {
962         error(0, errno, _("writing RFC822 msgblk.headers"));
963         release_sink(ctl);
964         free(msgblk.headers);
965         free_str_list(&msgblk.recipients);
966         return(PS_IOERR);
967     }
968     else if (!run.use_syslog && outlevel >= O_VERBOSE)
969         fputs("#", stderr);
970
971     /* write error notifications */
972     if (no_local_matches || has_nuls || bad_addresses)
973     {
974         int     errlen = 0;
975         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
976
977         errmsg = errhd;
978         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
979         if (no_local_matches)
980         {
981             if (reject_count != 1)
982                 strcat(errhd, _("no recipient addresses matched declared local names"));
983             else
984             {
985                 for (idp = msgblk.recipients; idp; idp = idp->next)
986                     if (idp->val.status.mark == XMIT_REJECT)
987                         break;
988                 sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
989             }
990         }
991
992         if (has_nuls)
993         {
994             if (errhd[sizeof("X-Fetchmail-Warning: ")])
995                 strcat(errhd, "; ");
996             strcat(errhd, _("message has embedded NULs"));
997         }
998
999         if (bad_addresses)
1000         {
1001             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1002                 strcat(errhd, "; ");
1003             strcat(errhd, _("SMTP listener rejected local recipient addresses: "));
1004             errlen = strlen(errhd);
1005             for (idp = msgblk.recipients; idp; idp = idp->next)
1006                 if (idp->val.status.mark == XMIT_ANTISPAM)
1007                     errlen += strlen(idp->id) + 2;
1008
1009             xalloca(errmsg, char *, errlen+3);
1010             (void) strcpy(errmsg, errhd);
1011             for (idp = msgblk.recipients; idp; idp = idp->next)
1012                 if (idp->val.status.mark == XMIT_ANTISPAM)
1013                 {
1014                     strcat(errmsg, idp->id);
1015                     if (idp->next)
1016                         strcat(errmsg, ", ");
1017                 }
1018
1019         }
1020
1021         strcat(errmsg, "\r\n");
1022
1023         /* ship out the error line */
1024         stuffline(ctl, errmsg);
1025     }
1026
1027     /* issue the delimiter line */
1028     cp = buf;
1029     *cp++ = '\r';
1030     *cp++ = '\n';
1031     *cp++ = '\0';
1032     stuffline(ctl, buf);
1033
1034     free(msgblk.headers);
1035     free_str_list(&msgblk.recipients);
1036     return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1037 }
1038
1039 static int readbody(int sock, struct query *ctl, flag forward, int len)
1040 /* read and dispose of a message body presented on sock */
1041 /*   ctl:               query control record */
1042 /*   sock:              to which the server is connected */
1043 /*   len:               length of message */
1044 /*   forward:           TRUE to forward */
1045 {
1046     int linelen;
1047     unsigned char buf[MSGBUFSIZE+4];
1048     unsigned char *inbufp = buf;
1049     flag issoftline = FALSE;
1050
1051     /* pass through the text lines */
1052     while (protocol->delimited || len > 0)
1053     {
1054         set_timeout(mytimeout);
1055         if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1056         {
1057             set_timeout(0);
1058             release_sink(ctl);
1059             return(PS_SOCKET);
1060         }
1061         set_timeout(0);
1062
1063         /* write the message size dots */
1064         if (linelen > 0)
1065         {
1066             sizeticker += linelen;
1067             while (sizeticker >= SIZETICKER)
1068             {
1069                 if (!run.use_syslog && outlevel > O_SILENT)
1070                     error_build(".");
1071                 sizeticker -= SIZETICKER;
1072             }
1073         }
1074         len -= linelen;
1075
1076         /* check for end of message */
1077         if (protocol->delimited && *inbufp == '.')
1078             if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1079                 break;
1080             else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1081                 break;
1082             else
1083                 msglen--;       /* subtract the size of the dot escape */
1084
1085         msglen += linelen;
1086
1087         if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1088             issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1089             if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1090             {
1091                 /*
1092                  * Soft linebreak, but less than 200 bytes left in
1093                  * input buffer. Rather than doing a buffer overrun,
1094                  * ignore the soft linebreak, NL-terminate data and
1095                  * deliver what we have now.
1096                  * (Who writes lines longer than 2K anyway?)
1097                  */
1098                 *inbufp = '\n'; *(inbufp+1) = '\0';
1099                 issoftline = 0;
1100             }
1101         }
1102
1103         /* ship out the text line */
1104         if (forward && (!issoftline))
1105         {
1106             int n;
1107             inbufp = buf;
1108
1109             /* guard against very long lines */
1110             buf[MSGBUFSIZE+1] = '\r';
1111             buf[MSGBUFSIZE+2] = '\n';
1112             buf[MSGBUFSIZE+3] = '\0';
1113
1114             n = stuffline(ctl, buf);
1115
1116             if (n < 0)
1117             {
1118                 error(0, errno, _("writing message text"));
1119                 release_sink(ctl);
1120                 return(PS_IOERR);
1121             }
1122             else if (outlevel >= O_VERBOSE)
1123                 fputc('*', stderr);
1124         }
1125     }
1126
1127     return(PS_SUCCESS);
1128 }
1129
1130 #ifdef KERBEROS_V4
1131 int
1132 kerberos_auth (socket, canonical) 
1133 /* authenticate to the server host using Kerberos V4 */
1134 int socket;             /* socket to server host */
1135 #ifdef __FreeBSD__
1136 char *canonical;        /* server name */
1137 #else
1138 const char *canonical;  /* server name */
1139 #endif
1140 {
1141     char * host_primary;
1142     KTEXT ticket;
1143     MSG_DAT msg_data;
1144     CREDENTIALS cred;
1145     Key_schedule schedule;
1146     int rem;
1147   
1148     xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1149     rem = (krb_sendauth (0L, socket, ticket, "pop",
1150                          canonical,
1151                          ((char *) (krb_realmofhost (canonical))),
1152                          ((unsigned long) 0),
1153                          (&msg_data),
1154                          (&cred),
1155                          (schedule),
1156                          ((struct sockaddr_in *) 0),
1157                          ((struct sockaddr_in *) 0),
1158                          "KPOPV0.1"));
1159     if (rem != KSUCCESS)
1160     {
1161         error(0, -1, _("kerberos error %s"), (krb_get_err_text (rem)));
1162         return (PS_AUTHFAIL);
1163     }
1164     return (0);
1165 }
1166 #endif /* KERBEROS_V4 */
1167
1168 #ifdef KERBEROS_V5
1169 int
1170 kerberos5_auth(socket, canonical)
1171 /* authenticate to the server host using Kerberos V5 */
1172 int socket;             /* socket to server host */
1173 const char *canonical;  /* server name */
1174 {
1175     krb5_error_code retval;
1176     krb5_context context;
1177     krb5_ccache ccdef;
1178     krb5_principal client = NULL, server = NULL;
1179     krb5_error *err_ret = NULL;
1180
1181     krb5_auth_context auth_context = NULL;
1182
1183     krb5_init_context(&context);
1184     krb5_init_ets(context);
1185     krb5_auth_con_init(context, &auth_context);
1186
1187     if (retval = krb5_cc_default(context, &ccdef)) {
1188         error(0, 0, "krb5_cc_default: %s", error_message(retval));
1189         return(PS_ERROR);
1190     }
1191
1192     if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1193         error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1194         return(PS_ERROR);
1195     }
1196
1197     if (retval = krb5_sname_to_principal(context, canonical, "pop",
1198            KRB5_NT_UNKNOWN,
1199            &server)) {
1200         error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1201         return(PS_ERROR);
1202     }
1203
1204     retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1205          "KPOPV1.0", client, server,
1206          AP_OPTS_MUTUAL_REQUIRED,
1207          NULL,  /* no data to checksum */
1208          0,   /* no creds, use ccache instead */
1209          ccdef,
1210          &err_ret, 0,
1211
1212          NULL); /* don't need reply */
1213
1214     krb5_free_principal(context, server);
1215     krb5_free_principal(context, client);
1216     krb5_auth_con_free(context, auth_context);
1217
1218     if (retval) {
1219       if (err_ret && err_ret->text.length) {
1220           error(0, 0, _("krb5_sendauth: %s [server says '%*s'] "),
1221             error_message(retval),
1222             err_ret->text.length,
1223             err_ret->text.data);
1224           krb5_free_error(context, err_ret);
1225       } else
1226           error(0, 0, "krb5_sendauth: %s", error_message(retval));
1227       return(PS_ERROR);
1228     }
1229
1230     return 0;
1231 }
1232 #endif /* KERBEROS_V5 */
1233
1234 static void clean_skipped_list(struct idlist **skipped_list)
1235 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1236 {
1237     struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1238     prev = current = head = *skipped_list;
1239
1240     if (!head)
1241         return;
1242     do
1243     {
1244         /* if item has no reference, remove it */
1245         if (current && current->val.status.mark == 0)
1246         {
1247             if (current == head) /* remove first item (head) */
1248             {
1249                 head = current->next;
1250                 if (current->id) free(current->id);
1251                 free(current);
1252                 prev = current = head;
1253             }
1254             else /* remove middle/last item */
1255             {
1256                 tmp = current->next;
1257                 prev->next = tmp;
1258                 if (current->id) free(current->id);
1259                 free(current);
1260                 current = tmp;
1261             }
1262         }
1263         else /* skip this item */
1264         {
1265             prev = current;
1266             current = current->next;
1267         }
1268     } while(current);
1269
1270     *skipped_list = head;
1271 }
1272
1273 static void send_size_warnings(struct query *ctl)
1274 /* send warning mail with skipped msg; reset msg count when user notified */
1275 {
1276     int size, nbr;
1277     int msg_to_send = FALSE;
1278     struct idlist *head=NULL, *current=NULL;
1279     int max_warning_poll_count, good, bad;
1280 #define OVERHD  "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server:"
1281
1282     head = ctl->skipped;
1283     if (!head)
1284         return;
1285
1286     /* don't start a notification message unless we need to */
1287     for (current = head; current; current = current->next)
1288         if (current->val.status.num == 0 && current->val.status.mark)
1289             msg_to_send = TRUE;
1290     if (!msg_to_send)
1291         return;
1292
1293     /*
1294      * There's no good way to recover if we can't send notification mail, 
1295      * but it's not a disaster, either, since the skipped mail will not
1296      * be deleted.
1297      */
1298     if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
1299         return;
1300     stuff_warning(ctl, OVERHD);
1301  
1302     if (run.poll_interval == 0)
1303         max_warning_poll_count = 0;
1304     else
1305         max_warning_poll_count = ctl->warnings/run.poll_interval;
1306
1307     /* parse list of skipped msg, adding items to the mail */
1308     for (current = head; current; current = current->next)
1309     {
1310         if (current->val.status.num == 0 && current->val.status.mark)
1311         {
1312             nbr = current->val.status.mark;
1313             size = atoi(current->id);
1314             stuff_warning(ctl, 
1315                     _("\t%d msg %d octets long skipped by fetchmail."),
1316                     nbr, size);
1317         }
1318         current->val.status.num++;
1319         current->val.status.mark = 0;
1320
1321         if (current->val.status.num >= max_warning_poll_count)
1322             current->val.status.num = 0;
1323     }
1324
1325     close_warning_by_mail(ctl, (struct msgblk *)NULL);
1326 #undef OVERHD
1327 }
1328
1329 int do_protocol(ctl, proto)
1330 /* retrieve messages from server using given protocol method table */
1331 struct query *ctl;              /* parsed options with merged-in defaults */
1332 const struct method *proto;     /* protocol method table */
1333 {
1334     int ok, js;
1335 #ifdef HAVE_VOLATILE
1336     volatile int sock = -1;     /* pacifies -Wall */
1337 #else
1338     int sock = -1;
1339 #endif /* HAVE_VOLATILE */
1340     const char *msg;
1341     void (*sigsave)(int);
1342     struct idlist *current=NULL, *tmp=NULL;
1343
1344     protocol = proto;
1345     ctl->server.base_protocol = protocol;
1346
1347 #ifndef KERBEROS_V4
1348     if (ctl->server.preauthenticate == A_KERBEROS_V4)
1349     {
1350         error(0, -1, _("Kerberos V4 support not linked."));
1351         return(PS_ERROR);
1352     }
1353 #endif /* KERBEROS_V4 */
1354
1355 #ifndef KERBEROS_V5
1356     if (ctl->server.preauthenticate == A_KERBEROS_V5)
1357     {
1358         error(0, -1, _("Kerberos V5 support not linked."));
1359         return(PS_ERROR);
1360     }
1361 #endif /* KERBEROS_V5 */
1362
1363     /* lacking methods, there are some options that may fail */
1364     if (!proto->is_old)
1365     {
1366         /* check for unsupported options */
1367         if (ctl->flush) {
1368             error(0, 0,
1369                     _("Option --flush is not supported with %s"),
1370                     proto->name);
1371             return(PS_SYNTAX);
1372         }
1373         else if (ctl->fetchall) {
1374             error(0, 0,
1375                     _("Option --all is not supported with %s"),
1376                     proto->name);
1377             return(PS_SYNTAX);
1378         }
1379     }
1380     if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1381     {
1382         error(0, 0,
1383                 _("Option --limit is not supported with %s"),
1384                 proto->name);
1385         return(PS_SYNTAX);
1386     }
1387
1388     pass = 0;
1389     tagnum = 0;
1390     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1391     ok = 0;
1392
1393     /* set up the server-nonresponse timeout */
1394     sigsave = signal(SIGALRM, timeout_handler);
1395     mytimeout = ctl->server.timeout;
1396
1397     if ((js = setjmp(restart)) == 1)
1398     {
1399         if (phase == OPEN_WAIT)
1400             error(0, 0,
1401                   _("timeout after %d seconds waiting to connect to server %s."),
1402                   ctl->server.timeout, ctl->server.pollname);
1403         else if (phase == SERVER_WAIT)
1404             error(0, 0,
1405                   _("timeout after %d seconds waiting for server %s."),
1406                   ctl->server.timeout, ctl->server.pollname);
1407         else if (phase == FORWARDING_WAIT)
1408             error(0, 0,
1409                   _("timeout after %d seconds waiting for %s."),
1410                   ctl->server.timeout,
1411                   ctl->mda ? "MDA" : "SMTP");
1412         else if (phase == LISTENER_WAIT)
1413             error(0, 0,
1414                   _("timeout after %d seconds waiting for listener to respond."));
1415         else
1416             error(0, 0, _("timeout after %d seconds."), ctl->server.timeout);
1417
1418         release_sink(ctl);
1419         if (ctl->smtp_socket != -1)
1420             close(ctl->smtp_socket);
1421         if (sock != -1)
1422             SockClose(sock);
1423
1424         /*
1425          * If we've exceeded our threshold for consecutive timeouts, 
1426          * try to notify the user, then mark the connection wedged.
1427          */
1428         if (timeoutcount > MAX_TIMEOUTS 
1429                         && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1430         {
1431             stuff_warning(ctl,
1432                           _("Subject: fetchmail sees repeated timeouts\r\n"));
1433             stuff_warning(ctl,
1434                           _("Fetchmail saw more than %d timouts while attempting to get mail from %s@%s."), 
1435                           MAX_TIMEOUTS,
1436                           ctl->remotename,
1437                           ctl->server.truename);
1438             stuff_warning(ctl, 
1439                           _("This could mean that your mailserver is stuck, or that your SMTP listener"));
1440             stuff_warning(ctl, 
1441                           _("is wedged, or that your mailbox file on the server has been corrupted by"));
1442             stuff_warning(ctl, 
1443                           _("a server error.  You can run `fetchmail -v -v' to diagnose the problem."));
1444             stuff_warning(ctl,
1445                           _("Fetchmail won't poll this mailbox again until you restart it."));
1446             close_warning_by_mail(ctl, (struct msgblk *)NULL);
1447             ctl->wedged = TRUE;
1448         }
1449
1450         ok = PS_ERROR;
1451     }
1452     else
1453     {
1454         char buf[POPBUFSIZE+1], *realhost;
1455         int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1456 #if INET6
1457         int fetches, dispatches;
1458 #else /* INET6 */
1459         int port, fetches, dispatches, oldphase;
1460 #endif /* INET6 */
1461         struct idlist *idp;
1462
1463         /* execute pre-initialization command, if any */
1464         if (ctl->preconnect && (ok = system(ctl->preconnect)))
1465         {
1466             sprintf(buf, _("pre-connection command failed with status %d"), ok);
1467             error(0, 0, buf);
1468             ok = PS_SYNTAX;
1469             goto closeUp;
1470         }
1471
1472         /* open a socket to the mail server */
1473         oldphase = phase;
1474         phase = OPEN_WAIT;
1475         set_timeout(mytimeout);
1476 #if !INET6
1477         port = ctl->server.port ? ctl->server.port : protocol->port;
1478 #endif /* !INET6 */
1479         realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1480 #if INET6
1481         if ((sock = SockOpen(realhost, 
1482                              ctl->server.service ? ctl->server.service : protocol->service,
1483                              ctl->server.netsec)) == -1, ctl->server.plugin
1484             )
1485 #else /* INET6 */
1486         if ((sock = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1487 #endif /* INET6 */
1488         {
1489 #if !INET6
1490             int err_no = errno;
1491 #ifdef HAVE_RES_SEARCH
1492             if (err_no != 0 && h_errno != 0)
1493                 error(0, 0, _("fetchmail: internal inconsistency"));
1494 #endif
1495             /*
1496              * Avoid generating a bogus error every poll cycle when we're
1497              * in daemon mode but the connection to the outside world
1498              * is down.
1499              */
1500             if (err_no == EHOSTUNREACH && run.poll_interval)
1501                 goto ehostunreach;
1502
1503             error_build(_("fetchmail: %s connection to %s failed"), 
1504                          protocol->name, ctl->server.pollname);
1505 #ifdef HAVE_RES_SEARCH
1506             if (h_errno != 0)
1507             {
1508                 if (h_errno == HOST_NOT_FOUND)
1509                     error_complete(0, 0, _(": host is unknown"));
1510                 else if (h_errno == NO_ADDRESS)
1511                     error_complete(0, 0, _(": name is valid but has no IP address"));
1512                 else if (h_errno == NO_RECOVERY)
1513                     error_complete(0, 0, _(": unrecoverable name server error"));
1514                 else if (h_errno == TRY_AGAIN)
1515                     error_complete(0, 0, _(": temporary name server error"));
1516                 else
1517                     error_complete(0, 0, _(": unknown DNS error %d"), h_errno);
1518             }
1519             else
1520 #endif /* HAVE_RES_SEARCH */
1521
1522                 error_complete(0, err_no, "");
1523
1524         ehostunreach:
1525 #endif /* INET6 */
1526             ok = PS_SOCKET;
1527             set_timeout(0);
1528             phase = oldphase;
1529             goto closeUp;
1530         }
1531         set_timeout(0);
1532         phase = oldphase;
1533
1534 #ifdef KERBEROS_V4
1535         if (ctl->server.preauthenticate == A_KERBEROS_V4)
1536         {
1537             set_timeout(mytimeout);
1538             ok = kerberos_auth(sock, ctl->server.truename);
1539             set_timeout(0);
1540             if (ok != 0)
1541                 goto cleanUp;
1542         }
1543 #endif /* KERBEROS_V4 */
1544
1545 #ifdef KERBEROS_V5
1546         if (ctl->server.preauthenticate == A_KERBEROS_V5)
1547         {
1548             set_timeout(mytimeout);
1549             ok = kerberos5_auth(sock, ctl->server.truename);
1550             set_timeout(0);
1551             if (ok != 0)
1552                 goto cleanUp;
1553         }
1554 #endif /* KERBEROS_V5 */
1555
1556         /* accept greeting message from mail server */
1557         ok = (protocol->parse_response)(sock, buf);
1558         if (ok != 0)
1559             goto cleanUp;
1560
1561         /* try to get authorized to fetch mail */
1562         if (protocol->getauth)
1563         {
1564             if (protocol->password_canonify)
1565                 (protocol->password_canonify)(shroud, ctl->password);
1566             else
1567                 strcpy(shroud, ctl->password);
1568
1569             ok = (protocol->getauth)(sock, ctl, buf);
1570             if (ok != 0)
1571             {
1572                 if (ok == PS_LOCKBUSY)
1573                     error(0, -1, _("Lock-busy error on %s@%s"),
1574                           ctl->remotename,
1575                           ctl->server.truename);
1576                 else
1577                 {
1578                     if (ok == PS_ERROR)
1579                         ok = PS_AUTHFAIL;
1580                     error(0, -1, _("Authorization failure on %s@%s"), 
1581                           ctl->remotename,
1582                           ctl->server.truename);
1583
1584                     /*
1585                      * If we're running in background, try to mail the
1586                      * calling user a heads-up about the authentication 
1587                      * failure the first time it happens.
1588                      */
1589                     if (run.poll_interval
1590                         && !ctl->wedged 
1591                         && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1592                     {
1593                         stuff_warning(ctl,
1594                                _("Subject: fetchmail authentication failed\r\n"));
1595                         stuff_warning(ctl,
1596                                 _("Fetchmail could not get mail from %s@%s."), 
1597                                 ctl->remotename,
1598                                 ctl->server.truename);
1599                         stuff_warning(ctl, 
1600                                _("The attempt to get authorization failed."));
1601                         stuff_warning(ctl, 
1602                                _("This probably means your password is invalid."));
1603                         close_warning_by_mail(ctl, (struct msgblk *)NULL);
1604                         ctl->wedged = TRUE;
1605                     }
1606                 }
1607                 goto cleanUp;
1608             }
1609         }
1610
1611         ctl->errcount = fetches = 0;
1612
1613         /* now iterate over each folder selected */
1614         for (idp = ctl->mailboxes; idp; idp = idp->next)
1615         {
1616             pass = 0;
1617             do {
1618                 dispatches = 0;
1619                 ++pass;
1620
1621                 if (outlevel >= O_DEBUG)
1622                     if (idp->id)
1623                         error(0, 0, _("selecting or re-polling folder %s"), idp->id);
1624                     else
1625                         error(0, 0, _("selecting or re-polling default folder"));
1626
1627                 /* compute # of messages and number of new messages waiting */
1628                 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1629                 if (ok != 0)
1630                     goto cleanUp;
1631
1632                 /* 
1633                  * We need the size of each message before it's
1634                  * loaded in order to pass via the ESMTP SIZE
1635                  * option.  If the protocol has a getsizes method,
1636                  * we presume this means it doesn't get reliable
1637                  * sizes from message fetch responses.
1638                  */
1639                 if (count > 0 && proto->getsizes)
1640                 {
1641                     int i;
1642
1643                     xalloca(msgsizes, int *, sizeof(int) * count);
1644                     for (i = 0; i < count; i++)
1645                         msgsizes[i] = -1;
1646
1647                     ok = (proto->getsizes)(sock, count, msgsizes);
1648                     if (ok != 0)
1649                         goto cleanUp;
1650
1651                     if (bytes == -1)
1652                     {
1653                         bytes = 0;
1654                         for (i = 0; i < count; i++)
1655                             bytes += msgsizes[i];
1656                     }
1657                 }
1658
1659                 /* show user how many messages we downloaded */
1660                 if (idp->id)
1661                     (void) sprintf(buf, _("%s at %s (folder %s)"),
1662                                    ctl->remotename, ctl->server.truename, idp->id);
1663                 else
1664                     (void) sprintf(buf, _("%s at %s"),
1665                                    ctl->remotename, ctl->server.truename);
1666                 if (outlevel > O_SILENT)
1667                     if (count == -1)            /* only used for ETRN */
1668                         error(0, 0, _("Polling %s"), ctl->server.truename);
1669                     else if (count != 0)
1670                     {
1671                         if (new != -1 && (count - new) > 0)
1672                             error_build(_("%d %s (%d seen) for %s"),
1673                                   count, count > 1 ? _("messages") :
1674                                                      _("message"),
1675                                   count-new, buf);
1676                         else
1677                             error_build(_("%d %s for %s"), 
1678                                   count, count > 1 ? _("messages") :
1679                                                      _("message"), buf);
1680                         if (bytes == -1)
1681                             error_complete(0, 0, ".");
1682                         else
1683                             error_complete(0, 0, _(" (%d octets)."), bytes);
1684                     }
1685                     else
1686                     {
1687                         /* these are pointless in normal daemon mode */
1688                         if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1689                             error(0, 0, _("No mail for %s"), buf); 
1690                     }
1691
1692                 /* very important, this is where we leave the do loop */ 
1693                 if (count == 0)
1694                     break;
1695
1696                 if (check_only)
1697                 {
1698                     if (new == -1 || ctl->fetchall)
1699                         new = count;
1700                     ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1701                     goto cleanUp;
1702                 }
1703                 else if (count > 0)
1704                 {    
1705                     flag        force_retrieval;
1706
1707                     /*
1708                      * What forces this code is that in POP2 and
1709                      * IMAP2bis you can't fetch a message without
1710                      * having it marked `seen'.  In POP3 and IMAP4, on the
1711                      * other hand, you can (peek_capable is set by 
1712                      * each driver module to convey this; it's not a
1713                      * method constant because of the difference between
1714                      * IMAP2bis and IMAP4, and because POP3 doesn't  peek
1715                      * if fetchall is on).
1716                      *
1717                      * The result of being unable to peek is that if there's
1718                      * any kind of transient error (DNS lookup failure, or
1719                      * sendmail refusing delivery due to process-table limits)
1720                      * the message will be marked "seen" on the server without
1721                      * having been delivered.  This is not a big problem if
1722                      * fetchmail is running in foreground, because the user
1723                      * will see a "skipped" message when it next runs and get
1724                      * clued in.
1725                      *
1726                      * But in daemon mode this leads to the message
1727                      * being silently ignored forever.  This is not
1728                      * acceptable.
1729                      *
1730                      * We compensate for this by checking the error
1731                      * count from the previous pass and forcing all
1732                      * messages to be considered new if it's nonzero.
1733                      */
1734                     force_retrieval = !peek_capable && (ctl->errcount > 0);
1735
1736                     /* read, forward, and delete messages */
1737                     for (num = 1; num <= count; num++)
1738                     {
1739                         flag toolarge = NUM_NONZERO(ctl->limit)
1740                             && msgsizes && (msgsizes[num-1] > ctl->limit);
1741                         flag oldmsg = (protocol->is_old && (protocol->is_old)(sock,ctl,num));
1742                         flag fetch_it = !toolarge 
1743                             && (ctl->fetchall || force_retrieval || !oldmsg);
1744                         flag suppress_delete = FALSE;
1745                         flag suppress_forward = FALSE;
1746                         flag suppress_readbody = FALSE;
1747                         flag retained = FALSE;
1748
1749                         /*
1750                          * This check copes with Post Office/NT's
1751                          * annoying habit of randomly prepending bogus
1752                          * LIST items of length -1.  Patrick Audley
1753                          * <paudley@pobox.com> tells us: LIST shows a
1754                          * size of -1, RETR and TOP return "-ERR
1755                          * System error - couldn't open message", and
1756                          * DELE succeeds but doesn't actually delete
1757                          * the message.
1758                          */
1759                         if (msgsizes && msgsizes[num-1] == -1)
1760                         {
1761                             if (outlevel >= O_VERBOSE)
1762                                 error(0, 0, 
1763                                       _("Skipping message %d, length -1"),
1764                                       num - 1);
1765                             continue;
1766                         }
1767
1768                         /* we may want to reject this message if it's old */
1769                         if (!fetch_it)
1770                         {
1771                             if (outlevel > O_SILENT)
1772                             {
1773                                 error_build(_("skipping message %d"), num);
1774                                 if (toolarge && !check_only) 
1775                                 {
1776                                     char size[32];
1777                                     int cnt;
1778
1779                                     /* convert sz to string */
1780                                     sprintf(size, "%d", msgsizes[num-1]);
1781
1782                                     /* build a list of skipped messages
1783                                      * val.id = size of msg (string cnvt)
1784                                      * val.status.num = warning_poll_count
1785                                      * val.status.mask = nbr of msg this size
1786                                      */
1787
1788                                     current = ctl->skipped;
1789
1790                                     /* initialise warning_poll_count to the
1791                                      * current value so that all new msg will
1792                                      * be included in the next mail
1793                                      */
1794                                     cnt = current? current->val.status.num : 0;
1795
1796                                     /* if entry exists, increment the count */
1797                                     if (current && 
1798                                         str_in_list(&current, size, FALSE))
1799                                     {
1800                                         for ( ; current; 
1801                                                 current = current->next)
1802                                         {
1803                                             if (strcmp(current->id, size) == 0)
1804                                             {
1805                                                 current->val.status.mark++;
1806                                                 break;
1807                                             }
1808                                         }
1809                                     }
1810                                     /* otherwise, create a new entry */
1811                                     /* initialise with current poll count */
1812                                     else
1813                                     {
1814                                         tmp = save_str(&ctl->skipped, size, 1);
1815                                         tmp->val.status.num = cnt;
1816                                     }
1817
1818                                     error_build(_(" (oversized, %d octets)"),
1819                                                 msgsizes[num-1]);
1820                                 }
1821                             }
1822                         }
1823                         else
1824                         {
1825                             flag wholesize = !protocol->fetch_body;
1826
1827                             /* request a message */
1828                             ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1829                             if (ok != 0)
1830                                 goto cleanUp;
1831
1832                             /* -1 means we didn't see a size in the response */
1833                             if (len == -1 && msgsizes)
1834                             {
1835                                 len = msgsizes[num - 1];
1836                                 wholesize = TRUE;
1837                             }
1838
1839                             if (outlevel > O_SILENT)
1840                             {
1841                                 error_build(_("reading message %d of %d"),
1842                                             num,count);
1843
1844                                 if (len > 0)
1845                                     error_build(_(" (%d %soctets)"),
1846                                         len, wholesize ? "" : _("header "));
1847                                 if (outlevel >= O_VERBOSE)
1848                                     error_complete(0, 0, "");
1849                                 else
1850                                     error_build(" ");
1851                             }
1852
1853                             /* 
1854                              * Read the message headers and ship them to the
1855                              * output sink.  
1856                              */
1857                             ok = readheaders(sock, len, msgsizes[num-1],
1858                                              ctl, num);
1859                             if (ok == PS_RETAINED)
1860                                 suppress_forward = retained = TRUE;
1861                             else if (ok == PS_TRANSIENT)
1862                                 suppress_delete = suppress_forward = TRUE;
1863                             else if (ok == PS_REFUSED)
1864                                 suppress_forward = TRUE;
1865                             else if (ok == PS_TRUNCATED)
1866                                 suppress_readbody = TRUE;
1867                             else if (ok)
1868                                 goto cleanUp;
1869
1870                             /* 
1871                              * If we're using IMAP4 or something else that
1872                              * can fetch headers separately from bodies,
1873                              * it's time to request the body now.  This
1874                              * fetch may be skipped if we got an anti-spam
1875                              * or other PS_REFUSED error response during
1876                              * readheaders.
1877                              */
1878                             if (protocol->fetch_body && !suppress_readbody) 
1879                             {
1880                                 if (outlevel >= O_VERBOSE)
1881                                     fputc('\n', stderr);
1882
1883                                 if ((ok = (protocol->trail)(sock, ctl, num)))
1884                                     goto cleanUp;
1885                                 len = 0;
1886                                 if (!suppress_forward)
1887                                 {
1888                                     if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1889                                         goto cleanUp;
1890                                     if (outlevel > O_SILENT && !wholesize)
1891                                         error_build(_(" (%d body octets) "), len);
1892                                 }
1893                             }
1894
1895                             /* process the body now */
1896                             if (len > 0)
1897                             {
1898                                 if (suppress_readbody)
1899                                 {
1900                                   /* When readheaders returns PS_TRUNCATED,
1901                                      the body (which has no content
1902                                      has already been read by readheaders,
1903                                      so we say readbody returned PS_SUCCESS */
1904                                   ok = PS_SUCCESS;
1905                                 }
1906                                 else
1907                                 {
1908                                   ok = readbody(sock,
1909                                                 ctl,
1910                                                 !suppress_forward,
1911                                                 len);
1912                                 }
1913                                 if (ok == PS_TRANSIENT)
1914                                     suppress_delete = suppress_forward = TRUE;
1915                                 else if (ok)
1916                                     goto cleanUp;
1917
1918                                 /* tell server we got it OK and resynchronize */
1919                                 if (protocol->trail)
1920                                 {
1921                                     if (outlevel >= O_VERBOSE)
1922                                         fputc('\n', stderr);
1923
1924                                     ok = (protocol->trail)(sock, ctl, num);
1925                                     if (ok != 0)
1926                                         goto cleanUp;
1927                                 }
1928                             }
1929
1930                             /* count # messages forwarded on this pass */
1931                             if (!suppress_forward)
1932                                 dispatches++;
1933
1934                             /*
1935                              * Check to see if the numbers matched?
1936                              *
1937                              * Yes, some servers foo this up horribly.
1938                              * All IMAP servers seem to get it right, and
1939                              * so does Eudora QPOP at least in 2.xx
1940                              * versions.
1941                              *
1942                              * Microsoft Exchange gets it completely
1943                              * wrong, reporting compressed rather than
1944                              * actual sizes (so the actual length of
1945                              * message is longer than the reported size).
1946                              * Another fine example of Microsoft brain death!
1947                              *
1948                              * Some older POP servers, like the old UCB
1949                              * POP server and the pre-QPOP QUALCOMM
1950                              * versions, report a longer size in the LIST
1951                              * response than actually gets shipped up.
1952                              * It's unclear what is going on here, as the
1953                              * QUALCOMM server (at least) seems to be
1954                              * reporting the on-disk size correctly.
1955                              */
1956                             if (msgsizes && msglen != msgsizes[num-1])
1957                             {
1958                                 if (outlevel >= O_DEBUG)
1959                                     error(0, 0,
1960                                           _("message %d was not the expected length (%d actual != %d expected)"),
1961                                           num, msglen, msgsizes[num-1]);
1962                             }
1963
1964                             /* end-of-message processing starts here */
1965                             if (!close_sink(ctl, &msgblk, !suppress_forward))
1966                             {
1967                                 ctl->errcount++;
1968                                 suppress_delete = TRUE;
1969                             }
1970                             fetches++;
1971                         }
1972
1973                         /*
1974                          * At this point in flow of control, either
1975                          * we've bombed on a protocol error or had
1976                          * delivery refused by the SMTP server
1977                          * (unlikely -- I've never seen it) or we've
1978                          * seen `accepted for delivery' and the
1979                          * message is shipped.  It's safe to mark the
1980                          * message seen and delete it on the server
1981                          * now.
1982                          */
1983
1984                         /* tell the UID code we've seen this */
1985                         if (ctl->newsaved)
1986                         {
1987                             struct idlist       *sdp;
1988
1989                             for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
1990                                 if (sdp->val.status.num == num)
1991                                     sdp->val.status.mark = UID_SEEN;
1992                         }
1993
1994                         /* maybe we delete this message now? */
1995                         if (retained)
1996                         {
1997                             if (outlevel > O_SILENT) 
1998                                 error_complete(0, 0, _(" retained"));
1999                         }
2000                         else if (protocol->delete
2001                                  && !suppress_delete
2002                                  && (fetch_it ? !ctl->keep : ctl->flush))
2003                         {
2004                             deletions++;
2005                             if (outlevel > O_SILENT) 
2006                                 error_complete(0, 0, _(" flushed"));
2007                             ok = (protocol->delete)(sock, ctl, num);
2008                             if (ok != 0)
2009                                 goto cleanUp;
2010 #ifdef POP3_ENABLE
2011                             delete_str(&ctl->newsaved, num);
2012 #endif /* POP3_ENABLE */
2013                         }
2014                         else if (outlevel > O_SILENT) 
2015                             error_complete(0, 0, _(" not flushed"));
2016
2017                         /* perhaps this as many as we're ready to handle */
2018                         if (NUM_NONZERO(ctl->fetchlimit)
2019                                         && ctl->fetchlimit <= fetches)
2020                         {
2021                             error(0, 0, _("fetchlimit reached; %d messages left on server"),
2022                                   count - fetches);
2023                             goto no_error;
2024                         }
2025                     }
2026
2027                     if (!check_only && ctl->skipped)
2028                     {
2029                         clean_skipped_list(&ctl->skipped);
2030                         send_size_warnings(ctl);
2031                     }
2032                 }
2033             } while
2034                   /*
2035                    * Only re-poll if we had some actual forwards, allowed
2036                    * deletions and had no errors.
2037                    * Otherwise it is far too easy to get into infinite loops.
2038                    */
2039                   (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2040         }
2041
2042    no_error:
2043         ok = (protocol->logout_cmd)(sock, ctl);
2044         /*
2045          * Hmmmm...arguably this would be incorrect if we had fetches but
2046          * no dispatches (due to oversized messages, etc.)
2047          */
2048         if (ok == 0)
2049             ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2050         SockClose(sock);
2051         goto closeUp;
2052
2053     cleanUp:
2054         if (ok != 0 && ok != PS_SOCKET)
2055             (protocol->logout_cmd)(sock, ctl);
2056         SockClose(sock);
2057     }
2058
2059     msg = (const char *)NULL;   /* sacrifice to -Wall */
2060     switch (ok)
2061     {
2062     case PS_SOCKET:
2063         msg = _("socket");
2064         break;
2065     case PS_AUTHFAIL:
2066         msg = _("authorization");
2067         break;
2068     case PS_SYNTAX:
2069         msg = _("missing or bad RFC822 header");
2070         break;
2071     case PS_IOERR:
2072         msg = _("MDA");
2073         break;
2074     case PS_ERROR:
2075         msg = _("client/server synchronization");
2076         break;
2077     case PS_PROTOCOL:
2078         msg = _("client/server protocol");
2079         break;
2080     case PS_LOCKBUSY:
2081         msg = _("lock busy on server");
2082         break;
2083     case PS_SMTP:
2084         msg = _("SMTP transaction");
2085         break;
2086     case PS_DNS:
2087         msg = _("DNS lookup");
2088         break;
2089     case PS_UNDEFINED:
2090         error(0, 0, _("undefined"));
2091         break;
2092     }
2093     if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX 
2094                 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL 
2095                 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2096         error(0,-1, _("%s error while fetching from %s"), msg, ctl->server.pollname);
2097
2098 closeUp:
2099     /* execute post-initialization command, if any */
2100     if (ctl->postconnect && (ok = system(ctl->postconnect)))
2101     {
2102         char buf[80];
2103
2104         sprintf(buf, _("post-connection command failed with status %d"), ok);
2105         error(0, 0, buf);
2106         if (ok == PS_SUCCESS)
2107             ok = PS_SYNTAX;
2108     }
2109
2110     signal(SIGALRM, sigsave);
2111     return(ok);
2112 }
2113
2114 #if defined(HAVE_STDARG_H)
2115 void gen_send(int sock, const char *fmt, ... )
2116 #else
2117 void gen_send(sock, fmt, va_alist)
2118 int sock;               /* socket to which server is connected */
2119 const char *fmt;        /* printf-style format */
2120 va_dcl
2121 #endif
2122 /* assemble command in printf(3) style and send to the server */
2123 {
2124     char buf [MSGBUFSIZE+1];
2125     va_list ap;
2126
2127     if (protocol->tagged)
2128         (void) sprintf(buf, "%s ", GENSYM);
2129     else
2130         buf[0] = '\0';
2131
2132 #if defined(HAVE_STDARG_H)
2133     va_start(ap, fmt) ;
2134 #else
2135     va_start(ap);
2136 #endif
2137 #ifdef HAVE_VSNPRINTF
2138     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2139 #else
2140     vsprintf(buf + strlen(buf), fmt, ap);
2141 #endif
2142     va_end(ap);
2143
2144     strcat(buf, "\r\n");
2145     SockWrite(sock, buf, strlen(buf));
2146
2147     if (outlevel >= O_MONITOR)
2148     {
2149         char *cp;
2150
2151         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2152         {
2153             char        *sp;
2154
2155             sp = cp + strlen(shroud);
2156             *cp++ = '*';
2157             while (*sp)
2158                 *cp++ = *sp++;
2159             *cp = '\0';
2160         }
2161         buf[strlen(buf)-2] = '\0';
2162         error(0, 0, "%s> %s", protocol->name, buf);
2163     }
2164 }
2165
2166 int gen_recv(sock, buf, size)
2167 /* get one line of input from the server */
2168 int sock;       /* socket to which server is connected */
2169 char *buf;      /* buffer to receive input */
2170 int size;       /* length of buffer */
2171 {
2172     int oldphase = phase;       /* we don't have to be re-entrant */
2173
2174     phase = SERVER_WAIT;
2175     set_timeout(mytimeout);
2176     if (SockRead(sock, buf, size) == -1)
2177     {
2178         set_timeout(0);
2179         phase = oldphase;
2180         return(PS_SOCKET);
2181     }
2182     else
2183     {
2184         set_timeout(0);
2185         if (buf[strlen(buf)-1] == '\n')
2186             buf[strlen(buf)-1] = '\0';
2187         if (buf[strlen(buf)-1] == '\r')
2188             buf[strlen(buf)-1] = '\0';
2189         if (outlevel >= O_MONITOR)
2190             error(0, 0, "%s< %s", protocol->name, buf);
2191         phase = oldphase;
2192         return(PS_SUCCESS);
2193     }
2194 }
2195
2196 #if defined(HAVE_STDARG_H)
2197 int gen_transact(int sock, const char *fmt, ... )
2198 #else
2199 int gen_transact(int sock, fmt, va_alist)
2200 int sock;               /* socket to which server is connected */
2201 const char *fmt;        /* printf-style format */
2202 va_dcl
2203 #endif
2204 /* assemble command in printf(3) style, send to server, accept a response */
2205 {
2206     int ok;
2207     char buf [MSGBUFSIZE+1];
2208     va_list ap;
2209     int oldphase = phase;       /* we don't have to be re-entrant */
2210
2211     phase = SERVER_WAIT;
2212
2213     if (protocol->tagged)
2214         (void) sprintf(buf, "%s ", GENSYM);
2215     else
2216         buf[0] = '\0';
2217
2218 #if defined(HAVE_STDARG_H)
2219     va_start(ap, fmt) ;
2220 #else
2221     va_start(ap);
2222 #endif
2223 #ifdef HAVE_VSNPRINTF
2224     vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2225 #else
2226     vsprintf(buf + strlen(buf), fmt, ap);
2227 #endif
2228     va_end(ap);
2229
2230     strcat(buf, "\r\n");
2231     SockWrite(sock, buf, strlen(buf));
2232
2233     if (outlevel >= O_MONITOR)
2234     {
2235         char *cp;
2236
2237         if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2238         {
2239             char        *sp;
2240
2241             sp = cp + strlen(shroud);
2242             *cp++ = '*';
2243             while (*sp)
2244                 *cp++ = *sp++;
2245             *cp = '\0';
2246         }
2247         buf[strlen(buf)-1] = '\0';
2248         error(0, 0, "%s> %s", protocol->name, buf);
2249     }
2250
2251     /* we presume this does its own response echoing */
2252     ok = (protocol->parse_response)(sock, buf);
2253
2254     phase = oldphase;
2255     return(ok);
2256 }
2257
2258 /* driver.c ends here */