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