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