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