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