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