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