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