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