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