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