]> Pileus Git - ~andy/fetchmail/blob - fetchmail.c
Minor update.
[~andy/fetchmail] / fetchmail.c
1 /*
2  * fetchmail.c -- main driver module for fetchmail
3  *
4  * For license terms, see the file COPYING in this directory.
5  */
6 #include "config.h"
7
8 #include <stdio.h>
9 #if defined(STDC_HEADERS)
10 #include <stdlib.h>
11 #endif
12 #if defined(HAVE_UNISTD_H)
13 #include <unistd.h>
14 #endif
15 #include <fcntl.h>
16 #include <string.h>
17 #include <signal.h>
18 #if defined(HAVE_SYSLOG)
19 #include <syslog.h>
20 #endif
21 #include <pwd.h>
22 #ifdef __FreeBSD__
23 #include <grp.h>
24 #endif
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>   /* needed for Sun 4.1.2 */
29 #ifdef HAVE_SETRLIMIT
30 #include <sys/resource.h>
31 #endif /* HAVE_SETRLIMIT */
32 #include <sys/utsname.h>
33
34 #ifdef HAVE_NET_SOCKET_H
35 #include <net/socket.h>
36 #endif
37 #ifdef HAVE_GETHOSTBYNAME
38 #include <netdb.h>
39 #endif /* HAVE_GETHOSTBYNAME */
40
41 #ifdef HESIOD
42 #include <hesiod.h>
43 #endif
44
45 #include "getopt.h"
46 #include "fetchmail.h"
47 #include "socket.h"
48 #include "tunable.h"
49 #include "smtp.h"
50 #include "netrc.h"
51 #include "i18n.h"
52
53 #ifndef ENETUNREACH
54 #define ENETUNREACH   128       /* Interactive doesn't know this */
55 #endif /* ENETUNREACH */
56
57 /* prototypes for internal functions */
58 static int load_params(int, char **, int);
59 static void dump_params (struct runctl *runp, struct query *, flag implicit);
60 static int query_host(struct query *);
61
62 /* controls the detail level of status/progress messages written to stderr */
63 int outlevel;               /* see the O_.* constants above */
64
65 /* miscellaneous global controls */
66 struct runctl run;          /* global controls for this run */
67 flag nodetach;              /* if TRUE, don't detach daemon process */
68 flag quitmode;              /* if --quit was set */
69 flag check_only;            /* if --probe was set */
70 flag versioninfo;           /* emit only version info */
71 char *user;                 /* the name of the invoking user */
72 char *home;                 /* invoking user's home directory */
73 char *fmhome;               /* fetchmail's home directory */
74 char *program_name;         /* the name to prefix error messages with */
75 flag configdump;            /* dump control blocks for configurator */
76 const char *fetchmailhost;  /* either `localhost' or the host's FQDN */
77
78 #if NET_SECURITY
79 void *request = NULL;
80 int requestlen = 0;
81 #endif /* NET_SECURITY */
82
83 static char *lockfile;          /* name of lockfile */
84 static int lock_acquired;       /* have we acquired a lock */
85 static int querystatus;         /* status of query */
86 static int successes;           /* count number of successful polls */
87 static struct runctl cmd_run;   /* global options set from command line */
88 static time_t parsetime;        /* time of last parse */
89
90 static void terminate_run(int);
91 static void terminate_poll(int);
92
93 #ifdef HAVE_ON_EXIT
94 static void unlockit(int n, void *p)
95 #else
96 static void unlockit(void)
97 #endif
98 /* must-do actions for exit (but we can't count on being able to do malloc) */
99 {
100     if (lockfile && lock_acquired)
101         unlink(lockfile);
102 }
103
104 #ifdef __FreeBSD__
105 /* drop SGID kmem privileage until we need it */
106 static void dropprivs(void)
107 {
108     struct group *gr;
109     gid_t        egid;
110     gid_t        rgid;
111     
112     egid = getegid();
113     rgid = getgid();
114     gr = getgrgid(egid);
115     
116     if (gr && !strcmp(gr->gr_name, "kmem"))
117     {
118         extern void interface_set_gids(gid_t egid, gid_t rgid);
119         interface_set_gids(egid, rgid);
120         setegid(rgid);
121     }
122 }
123 #endif
124
125 int main(int argc, char **argv)
126 {
127     int st, bkgd = FALSE;
128     int parsestatus, implicitmode = FALSE;
129     FILE        *lockfp;
130     struct query *ctl;
131     netrc_entry *netrc_list;
132     char *netrc_file, *tmpbuf;
133     pid_t pid;
134     int lastsig = 0;
135
136 #ifdef __FreeBSD__
137     dropprivs();
138 #endif
139
140     envquery(argc, argv);
141 #ifdef ENABLE_NLS
142     bindtextdomain(PACKAGE, LOCALEDIR);
143     textdomain(PACKAGE);
144 #endif
145
146     /*
147      * Note: because we can't initialize reporting before we  know whether
148      * syslog is supposed to be on, this message will go to stdout and
149      * be lost when running in background.
150      */
151     if (outlevel >= O_VERBOSE)
152     {
153         int i;
154
155         report(stdout, "fetchmail: invoked with");
156         for (i = 0; i < argc; i++)
157             report(stdout, " %s", argv[i]);
158         report(stdout, "\n");
159     }
160
161 #define IDFILE_NAME     ".fetchids"
162     run.idfile = (char *) xmalloc(strlen(fmhome)+sizeof(IDFILE_NAME)+2);
163     strcpy(run.idfile, fmhome);
164     strcat(run.idfile, "/");
165     strcat(run.idfile, IDFILE_NAME);
166   
167     outlevel = O_NORMAL;
168
169     /*
170      * We used to arrange for the lockfile to be removed on exit close
171      * to where the lock was asserted.  Now we need to do it here, because
172      * we might have re-executed in background with an existing lockfile
173      * as the result of a changed rcfile (see the code near the execvp(3)
174      * call near the beginning of the polling loop for details).  We want
175      * to be sure the lockfile gets nuked on any error exit, basically.
176      */
177 #ifdef HAVE_ATEXIT
178     atexit(unlockit);
179 #endif
180 #ifdef HAVE_ON_EXIT
181     on_exit(unlockit, (char *)NULL);
182 #endif
183
184     if ((parsestatus = parsecmdline(argc,argv, &cmd_run, &cmd_opts)) < 0)
185         exit(PS_SYNTAX);
186
187     if (versioninfo)
188     {
189         printf(_("This is fetchmail release %s"), VERSION);
190 #ifdef POP2_ENABLE
191         printf("+POP2");
192 #endif /* POP2_ENABLE */
193 #ifndef POP3_ENABLE
194         printf("-POP3");
195 #endif /* POP3_ENABLE */
196 #ifndef IMAP_ENABLE
197         printf("-IMAP");
198 #endif /* IMAP_ENABLE */
199 #ifdef GSSAPI
200         printf("+IMAP-GSS");
201 #endif /* GSSAPI */
202 #ifdef RPA_ENABLE
203         printf("+RPA");
204 #endif /* RPA_ENABLE */
205 #ifdef NTLM_ENABLE
206         printf("+NTLM");
207 #endif /* NTLM_ENABLE */
208 #ifdef SDPS_ENABLE
209         printf("+SDPS");
210 #endif /* SDPS_ENABLE */
211 #ifndef ETRN_ENABLE
212         printf("-ETRN");
213 #endif /* ETRN_ENABLE */
214 #ifdef SSL_ENABLE
215         printf("+SSL");
216 #endif
217 #if OPIE_ENABLE
218         printf("+OPIE");
219 #endif /* OPIE_ENABLE */
220 #if INET6_ENABLE
221         printf("+INET6");
222 #endif /* INET6_ENABLE */
223 #if NET_SECURITY
224         printf("+NETSEC");
225 #endif /* NET_SECURITY */
226 #ifdef HAVE_SOCKS
227         printf("+SOCKS");
228 #endif /* HAVE_SOCKS */
229 #if ENABLE_NLS
230         printf("+NLS");
231 #endif /* ENABLE_NLS */
232         putchar('\n');
233         fflush(stdout);
234
235         /* this is an attempt to help remote debugging */
236         system("uname -a");
237     }
238
239     /* avoid parsing the config file if all we're doing is killing a daemon */ 
240     if (!(quitmode && argc == 2))
241         implicitmode = load_params(argc, argv, optind);
242
243 #if defined(HAVE_SYSLOG)
244     /* logging should be set up early in case we were restarted from exec */
245     if (run.use_syslog)
246     {
247 #if defined(LOG_MAIL)
248         openlog(program_name, LOG_PID, LOG_MAIL);
249 #else
250         /* Assume BSD4.2 openlog with two arguments */
251         openlog(program_name, LOG_PID);
252 #endif
253         report_init(-1);
254     }
255     else
256 #endif
257         report_init((run.poll_interval == 0 || nodetach) && !run.logfile);
258
259     /* set up to do lock protocol */
260 #define FETCHMAIL_PIDFILE       "fetchmail.pid"
261     if (!getuid()) {
262         xalloca(tmpbuf, char *,
263                 sizeof(PID_DIR) + sizeof(FETCHMAIL_PIDFILE));
264         sprintf(tmpbuf, "%s/%s", PID_DIR, FETCHMAIL_PIDFILE);
265     } else {
266         xalloca(tmpbuf, char *, strlen(fmhome) + sizeof(FETCHMAIL_PIDFILE) + 2);
267         strcpy(tmpbuf, fmhome);
268         strcat(tmpbuf, "/");
269         if (fmhome == home)
270            strcat(tmpbuf, ".");
271         strcat(tmpbuf, FETCHMAIL_PIDFILE);
272     }
273 #undef FETCHMAIL_PIDFILE
274
275 #ifdef HAVE_SETRLIMIT
276     /*
277      * Before getting passwords, disable core dumps unless -v -d0 mode is on.
278      * Core dumps could otherwise contain passwords to be scavenged by a
279      * cracker.
280      */
281     if (outlevel < O_VERBOSE || run.poll_interval > 0)
282     {
283         struct rlimit corelimit;
284         corelimit.rlim_cur = 0;
285         corelimit.rlim_max = 0;
286         setrlimit(RLIMIT_CORE, &corelimit);
287     }
288 #endif /* HAVE_SETRLIMIT */
289
290 #define NETRC_FILE      ".netrc"
291     /* parse the ~/.netrc file (if present) for future password lookups. */
292     xalloca(netrc_file, char *, strlen(home) + sizeof(NETRC_FILE) + 2);
293     strcpy (netrc_file, home);
294     strcat (netrc_file, "/");
295     strcat (netrc_file, NETRC_FILE);
296     netrc_list = parse_netrc(netrc_file);
297 #undef NETRC_FILE
298
299     /* pick up passwords where we can */ 
300     for (ctl = querylist; ctl; ctl = ctl->next)
301     {
302         if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
303         {
304             if (ctl->server.preauthenticate == A_KERBEROS_V4 ||
305                         ctl->server.preauthenticate == A_KERBEROS_V5 ||
306                         ctl->server.preauthenticate == A_SSH ||
307 #ifdef GSSAPI
308                         ctl->server.protocol == P_IMAP_GSS ||
309 #endif /* GSSAPI */
310                         ctl->server.protocol == P_IMAP_K4)
311                 /* Server won't care what the password is, but there
312                    must be some non-null string here.  */
313                 ctl->password = ctl->remotename;
314             else
315             {
316                 netrc_entry *p;
317
318                 /* look up the pollname and account in the .netrc file. */
319                 p = search_netrc(netrc_list,
320                                  ctl->server.pollname, ctl->remotename);
321                 /* if we find a matching entry with a password, use it */
322                 if (p && p->password)
323                     ctl->password = xstrdup(p->password);
324
325                 /* otherwise try with "via" name if there is one */
326                 else if (ctl->server.via)
327                 {
328                     p = search_netrc(netrc_list, 
329                                      ctl->server.via, ctl->remotename);
330                     if (p && p->password)
331                         ctl->password = xstrdup(p->password);
332                 }
333             }
334         }
335     }
336
337     /* perhaps we just want to check options? */
338     if (versioninfo)
339     {
340         int havercfile = access(rcfile, 0);
341
342         printf(_("Taking options from command line%s%s\n"),
343                                 havercfile ? "" :  _(" and "),
344                                 havercfile ? "" : rcfile);
345
346         if (outlevel >= O_VERBOSE)
347             printf(_("Lockfile at %s\n"), tmpbuf);
348
349         if (querylist == NULL)
350             fprintf(stderr,
351                     _("No mailservers set up -- perhaps %s is missing?\n"),
352                     rcfile);
353         else
354             dump_params(&run, querylist, implicitmode);
355         exit(0);
356     }
357
358     /* dump options as a Python dictionary, for configurator use */
359     if (configdump)
360     {
361         dump_config(&run, querylist);
362         exit(0);
363     }
364
365     /* check for another fetchmail running concurrently */
366     pid = -1;
367     if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
368     {
369         report(stderr,_("fetchmail: cannot allocate memory for lock name.\n"));
370         exit(PS_EXCLUDE);
371     }
372     else
373         (void) strcpy(lockfile, tmpbuf);
374     if ((lockfp = fopen(lockfile, "r")) != NULL )
375     {
376         bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
377
378         if (kill(pid, 0) == -1) {
379             fprintf(stderr,_("fetchmail: removing stale lockfile\n"));
380             pid = -1;
381             bkgd = FALSE;
382             unlink(lockfile);
383         }
384         fclose(lockfp); /* not checking should be safe, file mode was "r" */
385     }
386
387     /* if no mail servers listed and nothing in background, we're done */
388     if (!(quitmode && argc == 2) && pid == -1 && querylist == NULL) {
389         (void)fputs(_("fetchmail: no mailservers have been specified.\n"),stderr);
390         exit(PS_SYNTAX);
391     }
392
393     /* perhaps user asked us to kill the other fetchmail */
394     if (quitmode)
395     {
396         if (pid == -1) 
397         {
398             fprintf(stderr,_("fetchmail: no other fetchmail is running\n"));
399             if (argc == 2)
400                 exit(PS_EXCLUDE);
401         }
402         else if (kill(pid, SIGTERM) < 0)
403         {
404             fprintf(stderr,_("fetchmail: error killing %s fetchmail at %d; bailing out.\n"),
405                     bkgd ? _("background") : _("foreground"), pid);
406             exit(PS_EXCLUDE);
407         }
408         else
409         {
410             fprintf(stderr,_("fetchmail: %s fetchmail at %d killed.\n"),
411                     bkgd ? _("background") : _("foreground"), pid);
412             unlink(lockfile);
413             if (argc == 2)
414                 exit(0);
415             else
416                 pid = -1; 
417         }
418     }
419
420     /* another fetchmail is running -- wake it up or die */
421     if (pid != -1)
422     {
423         if (check_only)
424         {
425             fprintf(stderr,
426                  _("fetchmail: can't check mail while another fetchmail to same host is running.\n"));
427             return(PS_EXCLUDE);
428         }
429         else if (!implicitmode)
430         {
431             fprintf(stderr,
432                  _("fetchmail: can't poll specified hosts with another fetchmail running at %d.\n"),
433                  pid);
434                 return(PS_EXCLUDE);
435         }
436         else if (!bkgd)
437         {
438             fprintf(stderr,
439                  _("fetchmail: another foreground fetchmail is running at %d.\n"),
440                  pid);
441                 return(PS_EXCLUDE);
442         }
443         else if (argc > 1)
444         {
445             /* this test enables re-execing on a changed rcfile */
446             if (getpid() == pid)
447                 lock_acquired = TRUE;
448             else
449             {
450                 fprintf(stderr,
451                         _("fetchmail: can't accept options while a background fetchmail is running.\n"));
452                 return(PS_EXCLUDE);
453             }
454         }
455         else if (kill(pid, SIGUSR1) == 0)
456         {
457             fprintf(stderr,
458                     _("fetchmail: background fetchmail at %d awakened.\n"),
459                     pid);
460             return(0);
461         }
462         else
463         {
464             /*
465              * Should never happen -- possible only if a background fetchmail
466              * croaks after the first kill probe above but before the
467              * SIGUSR1/SIGHUP transmission.
468              */
469             fprintf(stderr,
470                     _("fetchmail: elder sibling at %d died mysteriously.\n"),
471                     pid);
472             return(PS_UNDEFINED);
473         }
474     }
475
476     /* pick up interactively any passwords we need but don't have */ 
477     for (ctl = querylist; ctl; ctl = ctl->next)
478     {
479         if (ctl->active && !(implicitmode && ctl->server.skip)
480                 && ctl->server.protocol != P_ETRN 
481                 && ctl->server.protocol != P_IMAP_K4
482 #ifdef GSSAPI
483                 && ctl->server.protocol != P_IMAP_GSS
484 #endif /* GSSAPI */
485                 && !ctl->password)
486         {
487             if (!isatty(0))
488             {
489                 fprintf(stderr,
490                         _("fetchmail: can't find a password for %s@%s.\n"),
491                         ctl->remotename, ctl->server.pollname);
492                 return(PS_AUTHFAIL);
493             }
494             else
495             {
496                 char* password_prompt = _("Enter password for %s@%s: ");
497
498                 xalloca(tmpbuf, char *, strlen(password_prompt) +
499                         strlen(ctl->remotename) +
500                         strlen(ctl->server.pollname) + 1);
501                 (void) sprintf(tmpbuf, password_prompt,
502                                ctl->remotename, ctl->server.pollname);
503                 ctl->password = xstrdup((char *)fm_getpassword(tmpbuf));
504             }
505         }
506     }
507
508     /*
509      * Time to initiate the SOCKS library (this is not mandatory: it just
510      * registers the correct application name for logging purpose. If you
511      * have some problem, comment out these lines).
512      */
513 #ifdef HAVE_SOCKS
514     SOCKSinit("fetchmail");
515 #endif /* HAVE_SOCKS */
516
517     /*
518      * Maybe time to go to demon mode...
519      */
520     if (run.poll_interval)
521     {
522         if (!nodetach)
523             daemonize(run.logfile, terminate_run);
524         report(stdout, _("starting fetchmail %s daemon \n"), VERSION);
525
526         /*
527          * We'll set up a handler for these when we're sleeping,
528          * but ignore them otherwise so as not to interrupt a poll.
529          */
530         signal(SIGUSR1, SIG_IGN);
531         if (run.poll_interval && !getuid())
532             signal(SIGHUP, SIG_IGN);
533     }
534     else if (run.logfile && access(run.logfile, F_OK) == 0)
535     {
536         freopen(run.logfile, "a", stdout);
537         freopen(run.logfile, "a", stderr);
538     }
539
540
541 #ifdef linux
542     interface_init();
543 #endif /* linux */
544
545     /* beyond here we don't want more than one fetchmail running per user */
546     umask(0077);
547     signal(SIGABRT, terminate_run);
548     signal(SIGINT, terminate_run);
549     signal(SIGTERM, terminate_run);
550     signal(SIGALRM, terminate_run);
551     signal(SIGPIPE, terminate_run);
552     signal(SIGQUIT, terminate_run);
553
554     /* here's the exclusion lock */
555 #ifndef O_SYNC
556 #define O_SYNC  0       /* use it if we have it */
557 #endif
558     if ((st = open(lockfile, O_WRONLY|O_CREAT|O_EXCL|O_SYNC, 0666)) != -1)
559     {
560         sprintf(tmpbuf,"%d", getpid());
561         write(st, tmpbuf, strlen(tmpbuf));
562         if (run.poll_interval)
563         {
564             sprintf(tmpbuf," %d", run.poll_interval);
565             write(st, tmpbuf, strlen(tmpbuf));
566         }
567         close(st);      /* should be safe, fd was opened with O_SYNC */
568         lock_acquired = TRUE;
569     }
570
571     /*
572      * Query all hosts. If there's only one, the error return will
573      * reflect the status of that transaction.
574      */
575     do {
576         /* 
577          * Check to see if the rcfile has been touched.  If so,
578          * re-exec so the file will be reread.  Doing it this way
579          * avoids all the complications of trying to deallocate the
580          * in-core control structures -- and the potential memory
581          * leaks...
582          */
583         struct stat     rcstat;
584
585         if (stat(rcfile, &rcstat) == -1)
586         {
587             if (errno != ENOENT)
588                 report(stderr, 
589                        _("couldn't time-check %s (error %d)\n"),
590                        rcfile, errno);
591         }
592         else if (rcstat.st_mtime > parsetime)
593         {
594             report(stdout, _("restarting fetchmail (%s changed)\n"), rcfile);
595             execvp("fetchmail", argv);
596             report(stderr, _("attempt to re-exec fetchmail failed\n"));
597         }
598
599 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
600         /*
601          * This was an efficiency hack that backfired.  The theory
602          * was that using TCP/IP for DNS queries would get us better
603          * reliability and shave off some per-UDP-packet costs.
604          * Unfortunately it interacted badly with diald, which effectively 
605          * filters out DNS queries over TCP/IP for reasons having to do
606          * with some obscure kernel problem involving bootstrapping of
607          * dynamically-addressed links.  I don't understand this mess
608          * and don't want to, so it's "See ya!" to this hack.
609          */
610         sethostent(TRUE);       /* use TCP/IP for mailserver queries */
611 #endif /* HAVE_RES_SEARCH */
612
613         batchcount = 0;
614         for (ctl = querylist; ctl; ctl = ctl->next)
615         {
616             if (ctl->active && !(implicitmode && ctl->server.skip))
617             {
618                 if (ctl->wedged)
619                 {
620                     report(stderr, 
621                           _("poll of %s skipped (failed authentication or too many timeouts)\n"),
622                           ctl->server.pollname);
623                     continue;
624                 }
625
626                 /* check skip interval first so that it counts all polls */
627                 if (run.poll_interval && ctl->server.interval) 
628                 {
629                     if (ctl->server.poll_count++ % ctl->server.interval) 
630                     {
631                         if (outlevel >= O_VERBOSE)
632                             report(stdout,
633                                     _("interval not reached, not querying %s\n"),
634                                     ctl->server.pollname);
635                         continue;
636                     }
637                 }
638
639 #if (defined(linux) && !INET6_ENABLE) || defined(__FreeBSD__)
640                 /*
641                  * Don't do monitoring if we were woken by a signal.
642                  * Note that interface_approve() does its own error logging.
643                  */
644                 if (!interface_approve(&ctl->server, !lastsig))
645                     continue;
646 #endif /* (defined(linux) && !INET6_ENABLE) || defined(__FreeBSD__) */
647
648                 querystatus = query_host(ctl);
649
650 #ifdef POP3_ENABLE
651                 /* leave the UIDL state alone if there have been any errors */
652                 if (!check_only && !querystatus)
653                     uid_swap_lists(ctl);
654 #endif  /* POP3_ENABLE */
655
656                 if (querystatus == PS_SUCCESS)
657                     successes++;
658                 else if (!check_only && 
659                          ((querystatus!=PS_NOMAIL) || (outlevel==O_DEBUG)))
660                 switch(querystatus)
661                 {
662                 case PS_SUCCESS:
663                     report(stdout, "Query status=0 (SUCCESS)\n"); break ;
664                 case PS_NOMAIL: 
665                     report(stdout, "Query status=1 (NOMAIL)\n"); break ;
666                 case PS_SOCKET:
667                     report(stdout, "Query status=2 (SOCKET)\n"); break ;
668                 case PS_AUTHFAIL:
669                     report(stdout, "Query status=3 (AUTHFAIL)\n"); break ;
670                 case PS_PROTOCOL:
671                     report(stdout, "Query status=4 (PROTOCOL)\n"); break ;
672                 case PS_SYNTAX:
673                     report(stdout, "Query status=5 (SYNTAX)\n"); break ;
674                 case PS_IOERR:
675                     report(stdout, "Query status=6 (IOERR)\n"); break ;
676                 case PS_ERROR:
677                     report(stdout, "Query status=7 (ERROR)\n"); break ;
678                 case PS_EXCLUDE:
679                     report(stdout, "Query status=8 (EXCLUDE)\n"); break ;
680                 case PS_LOCKBUSY:
681                     report(stdout, "Query status=9 (LOCKBUSY)\n"); break ;
682                 case PS_SMTP:
683                     report(stdout, "Query status=10 (SMTP)\n"); break ;
684                 case PS_DNS:
685                     report(stdout, "Query status=11 (DNS)\n"); break ;
686                 case PS_BSMTP:
687                     report(stdout, "Query status=12 (BSMTP)\n"); break ;
688                 case PS_MAXFETCH:
689                     report(stdout, "Query status=13 (MAXFETCH)\n"); break ;
690                 default:
691                     report(stdout, _("Query status=%d\n"), querystatus); break;
692                 }
693
694 #if (defined(linux) && !INET6_ENABLE) || defined (__FreeBSD__)
695                 if (ctl->server.monitor)
696                 {
697                     /*
698                      * Allow some time for the link to quiesce.  One
699                      * second is usually sufficient, three is safe.
700                      * Note:  this delay is important - don't remove!
701                      */
702                     sleep(3);
703                     interface_note_activity(&ctl->server);
704                 }
705 #endif /* (defined(linux) && !INET6_ENABLE) || defined(__FreeBSD__) */
706             }
707         }
708
709 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
710         endhostent();           /* release TCP/IP connection to nameserver */
711 #endif /* HAVE_RES_SEARCH */
712
713         /* close connections cleanly */
714         terminate_poll(0);
715
716         /*
717          * OK, we've polled.  Now sleep.
718          */
719         if (run.poll_interval)
720         {
721             /* 
722              * Because passwords can expire, it may happen that *all*
723              * hosts are now out of the loop due to authfail
724              * conditions.  If this happens daemon-mode fetchmail
725              * should softly and silently vanish away, rather than
726              * spinning uselessly.
727              */
728             int unwedged = 0;
729
730             for (ctl = querylist; ctl; ctl = ctl->next)
731                 if (ctl->active && !(implicitmode && ctl->server.skip))
732                     if (!ctl->wedged)
733                         unwedged++;
734             if (!unwedged)
735             {
736                 report(stderr, _("All connections are wedged.  Exiting.\n"));
737                 /* FIXME: someday, send notification mail */
738                 exit(PS_AUTHFAIL);
739             }
740
741             if (outlevel >= O_VERBOSE)
742                 report(stdout, 
743                        _("fetchmail: sleeping at %s\n"), rfc822timestamp());
744
745             /*
746              * OK, now pause util it's time for the next poll cycle.
747              * A nonzero return indicates we received a wakeup signal;
748              * unwedge all servers in case the problem has been
749              * manually repaired.
750              */
751             if ((lastsig = interruptible_idle(run.poll_interval)))
752             {
753 #ifdef SYS_SIGLIST_DECLARED
754                 report(stdout, 
755                        _("awakened by %s\n"), sys_siglist[lastsig]);
756 #else
757                 report(stdout, 
758                        _("awakened by signal %d\n"), lastsig);
759 #endif
760                 for (ctl = querylist; ctl; ctl = ctl->next)
761                     ctl->wedged = FALSE;
762             }
763
764             if (outlevel >= O_VERBOSE)
765                 report(stdout, _("awakened at %s\n"), rfc822timestamp());
766         }
767     } while
768         (run.poll_interval);
769
770     if (outlevel >= O_VERBOSE)
771         report(stdout, _("normal termination, status %d\n"),
772                 successes ? PS_SUCCESS : querystatus);
773
774     terminate_run(0);
775     exit(successes ? PS_SUCCESS : querystatus);
776 }
777
778 static void list_merge(struct idlist **dstl, struct idlist **srcl, int force)
779 {
780     /*
781      * If force is off, modify dstl fields only when they're empty (treat srcl
782      * as defaults).  If force is on, modify each dstl field whenever scrcl
783      * is nonempty (treat srcl as an override).  
784      */
785     if (force ? !!*srcl : !*dstl)
786     {
787         struct idlist *cpl = copy_str_list(*srcl);
788
789         append_str_list(dstl, &cpl);
790     }
791 }
792
793 static void optmerge(struct query *h2, struct query *h1, int force)
794 /* merge two options records */
795 {
796     list_merge(&h2->server.localdomains, &h1->server.localdomains, force);
797     list_merge(&h2->localnames, &h1->localnames, force);
798     list_merge(&h2->mailboxes, &h1->mailboxes, force);
799     list_merge(&h2->smtphunt, &h1->smtphunt, force);
800     list_merge(&h2->antispam, &h1->antispam, force);
801
802 #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld
803     FLAG_MERGE(server.via);
804     FLAG_MERGE(server.protocol);
805 #if INET6_ENABLE
806     FLAG_MERGE(server.service);
807     FLAG_MERGE(server.netsec);
808 #else /* INET6_ENABLE */
809     FLAG_MERGE(server.port);
810 #endif /* INET6_ENABLE */
811     FLAG_MERGE(server.interval);
812     FLAG_MERGE(server.preauthenticate);
813     FLAG_MERGE(server.timeout);
814     FLAG_MERGE(server.envelope);
815     FLAG_MERGE(server.envskip);
816     FLAG_MERGE(server.qvirtual);
817     FLAG_MERGE(server.skip);
818     FLAG_MERGE(server.dns);
819     FLAG_MERGE(server.checkalias);
820     FLAG_MERGE(server.uidl);
821
822 #if defined(linux) || defined(__FreeBSD__)
823     FLAG_MERGE(server.interface);
824     FLAG_MERGE(server.monitor);
825     FLAG_MERGE(server.interface_pair);
826 #endif /* linux || defined(__FreeBSD__) */
827
828     FLAG_MERGE(server.plugin);
829     FLAG_MERGE(server.plugout);
830
831     FLAG_MERGE(wildcard);
832     FLAG_MERGE(remotename);
833     FLAG_MERGE(password);
834     FLAG_MERGE(mda);
835     FLAG_MERGE(bsmtp);
836     FLAG_MERGE(listener);
837     FLAG_MERGE(smtpaddress);
838     FLAG_MERGE(smtpname);
839     FLAG_MERGE(preconnect);
840     FLAG_MERGE(postconnect);
841
842     FLAG_MERGE(keep);
843     FLAG_MERGE(flush);
844     FLAG_MERGE(fetchall);
845     FLAG_MERGE(rewrite);
846     FLAG_MERGE(forcecr);
847     FLAG_MERGE(stripcr);
848     FLAG_MERGE(pass8bits);
849     FLAG_MERGE(dropstatus);
850     FLAG_MERGE(mimedecode);
851     FLAG_MERGE(idle);
852     FLAG_MERGE(limit);
853     FLAG_MERGE(warnings);
854     FLAG_MERGE(fetchlimit);
855     FLAG_MERGE(batchlimit);
856 #ifdef  SSL_ENABLE
857     FLAG_MERGE(use_ssl);
858     FLAG_MERGE(sslkey);
859     FLAG_MERGE(sslcert);
860 #endif
861     FLAG_MERGE(expunge);
862
863     FLAG_MERGE(properties);
864 #undef FLAG_MERGE
865 }
866
867 static int load_params(int argc, char **argv, int optind)
868 {
869     int implicitmode, st;
870     struct passwd *pw;
871     struct query def_opts, *ctl;
872     struct stat rcstat;
873
874     run.bouncemail = TRUE;
875
876     memset(&def_opts, '\0', sizeof(struct query));
877     def_opts.smtp_socket = -1;
878     def_opts.smtpaddress = (char *)0;
879 #define ANTISPAM(n)     save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = (n)
880     ANTISPAM(571);      /* sendmail */
881     ANTISPAM(550);      /* old exim */
882     ANTISPAM(501);      /* new exim */
883     ANTISPAM(554);      /* Postfix */
884 #undef ANTISPAM
885
886     def_opts.server.protocol = P_AUTO;
887     def_opts.server.timeout = CLIENT_TIMEOUT;
888     def_opts.warnings = WARNING_INTERVAL;
889     def_opts.remotename = user;
890     def_opts.listener = SMTP_MODE;
891
892     /* note the parse time, so we can pick up on modifications */
893     parsetime = 0;      /* foil compiler warnings */
894     if (stat(rcfile, &rcstat) != -1)
895         parsetime = rcstat.st_mtime;
896     else if (errno != ENOENT)
897         report(stderr, _("couldn't time-check the run-control file\n"));
898
899     /* this builds the host list */
900     if ((st = prc_parse_file(rcfile, !versioninfo)) != 0)
901         /*
902          * FIXME: someday, send notification mail here if backgrounded.
903          * Right now, that can happen if the user changes the rcfile
904          * while the fetchmail is running in background.  Do similarly
905          * for the other exit() calls in this function.
906          */
907         exit(st);
908
909     if ((implicitmode = (optind >= argc)))
910     {
911         for (ctl = querylist; ctl; ctl = ctl->next)
912             ctl->active = TRUE;
913     }
914     else
915         for (; optind < argc; optind++) 
916         {
917             flag        predeclared =  FALSE;
918
919             /*
920              * If hostname corresponds to a host known from the rc file,
921              * simply declare it active.  Otherwise synthesize a host
922              * record from command line and defaults
923              */
924             for (ctl = querylist; ctl; ctl = ctl->next)
925                 if (!strcmp(ctl->server.pollname, argv[optind])
926                         || str_in_list(&ctl->server.akalist, argv[optind], TRUE))
927                 {
928                     /* Is this correct? */
929                     if (predeclared && outlevel == O_VERBOSE)
930                         fprintf(stderr,_("Warning: multiple mentions of host %s in config file\n"),argv[optind]);
931                     ctl->active = TRUE;
932                     predeclared = TRUE;
933                 }
934
935             if (!predeclared)
936             {
937                 /*
938                  * Allocate and link record without copying in
939                  * command-line args; we'll do that with the optmerge
940                  * call later on.
941                  */
942                 ctl = hostalloc((struct query *)NULL);
943                 ctl->server.via =
944                     ctl->server.pollname = xstrdup(argv[optind]);
945                 ctl->active = TRUE;
946                 ctl->server.lead_server = (struct hostdata *)NULL;
947             }
948         }
949
950     /*
951      * If there's a defaults record, merge it and lose it.
952      */ 
953     if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
954     {
955         for (ctl = querylist->next; ctl; ctl = ctl->next)
956             optmerge(ctl, querylist, FALSE);
957         querylist = querylist->next;
958     }
959
960     /* don't allow a defaults record after the first */
961     for (ctl = querylist; ctl; ctl = ctl->next)
962         if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
963             exit(PS_SYNTAX);
964
965     /* use localhost if we never fetch the FQDN of this host */
966     fetchmailhost = "localhost";
967
968     /* here's where we override globals */
969     if (cmd_run.logfile)
970         run.logfile = cmd_run.logfile;
971     if (cmd_run.idfile)
972         run.idfile = cmd_run.idfile;
973     /* do this before the keep/fetchall test below, otherwise -d0 may fail */
974     if (cmd_run.poll_interval >= 0)
975         run.poll_interval = cmd_run.poll_interval;
976     if (cmd_run.invisible)
977         run.invisible = cmd_run.invisible;
978     if (cmd_run.use_syslog)
979         run.use_syslog = (cmd_run.use_syslog == FLAG_TRUE);
980     if (cmd_run.postmaster)
981         run.postmaster = cmd_run.postmaster;
982     if (cmd_run.bouncemail)
983         run.bouncemail = cmd_run.bouncemail;
984
985     /* check and daemon options are not compatible */
986     if (check_only && run.poll_interval)
987         run.poll_interval = 0;
988
989     /* merge in wired defaults, do sanity checks and prepare internal fields */
990     for (ctl = querylist; ctl; ctl = ctl->next)
991     {
992         ctl->wedged = FALSE;
993
994         if (configdump || (ctl->active && !(implicitmode && ctl->server.skip)))
995         {
996             /* merge in defaults */
997             optmerge(ctl, &def_opts, FALSE);
998
999             /* force command-line options */
1000             optmerge(ctl, &cmd_opts, TRUE);
1001
1002             /* this code enables flags to be turned off */
1003 #define DEFAULT(flag, dflt)     if (flag == FLAG_TRUE)\
1004                                         flag = TRUE;\
1005                                 else if (flag == FLAG_FALSE)\
1006                                         flag = FALSE;\
1007                                 else\
1008                                         flag = (dflt)
1009             DEFAULT(ctl->keep, FALSE);
1010             DEFAULT(ctl->fetchall, FALSE);
1011             DEFAULT(ctl->flush, FALSE);
1012             DEFAULT(ctl->rewrite, TRUE);
1013             DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL)); 
1014             DEFAULT(ctl->forcecr, FALSE);
1015             DEFAULT(ctl->pass8bits, FALSE);
1016             DEFAULT(ctl->dropstatus, FALSE);
1017             DEFAULT(ctl->mimedecode, FALSE);
1018             DEFAULT(ctl->idle, FALSE);
1019             DEFAULT(ctl->server.dns, TRUE);
1020             DEFAULT(ctl->server.uidl, FALSE);
1021 #ifdef  SSL_ENABLE
1022             DEFAULT(ctl->use_ssl, FALSE);
1023 #endif
1024             DEFAULT(ctl->server.checkalias, FALSE);
1025 #undef DEFAULT
1026
1027             /*
1028              * DNS support is required for some protocols.  We used to
1029              * do this unconditionally, but it made fetchmail excessively
1030              * vulnerable to misconfigured DNS setups.
1031              *
1032              * If we're using ETRN, the smtp hunt list is the list of
1033              * systems we're polling on behalf of; these have to be 
1034              * fully-qualified domain names.  The default for this list
1035              * should be the FQDN of localhost.
1036              *
1037              * If we're using Kerberos for authentication, we need 
1038              * the FQDN in order to generate capability keys.
1039              */
1040             if (ctl->server.protocol == P_ETRN
1041                          || ctl->server.preauthenticate == A_KERBEROS_V4
1042                          || ctl->server.preauthenticate == A_KERBEROS_V5)
1043                 if (strcmp(fetchmailhost, "localhost") == 0)
1044                         fetchmailhost = host_fqdn();
1045
1046             /*
1047              * Make sure we have a nonempty host list to forward to.
1048              */
1049             if (!ctl->smtphunt)
1050                 save_str(&ctl->smtphunt, fetchmailhost, FALSE);
1051
1052             /* if `user' doesn't name a real local user, try to run as root */
1053             if ((pw = getpwnam(user)) == (struct passwd *)NULL)
1054                 ctl->uid = 0;
1055             else
1056                 ctl->uid = pw->pw_uid;  /* for local delivery via MDA */
1057             if (!ctl->localnames)       /* for local delivery via SMTP */
1058                 save_str_pair(&ctl->localnames, user, NULL);
1059
1060 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
1061             /* can't handle multidrop mailboxes unless we can do DNS lookups */
1062             if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
1063             {
1064                 ctl->server.dns = FALSE;
1065                 report(stderr, _("fetchmail: warning: no DNS available to check multidrop fetches from %s\n"), ctl->server.pollname);
1066             }
1067 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
1068
1069             /*
1070              *
1071              * Compute the true name of the mailserver host.  
1072              * There are two clashing cases here:
1073              *
1074              * (1) The poll name is a label, possibly on one of several
1075              *     poll configurations for the same host.  In this case 
1076              *     the `via' option will be present and give the true name.
1077              *
1078              * (2) The poll name is the true one, the via name is 
1079              *     localhost.   This is going to be typical for ssh-using
1080              *     configurations.
1081              *
1082              * We're going to assume the via name is true unless it's
1083              * localhost.
1084              */
1085             if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
1086                 ctl->server.queryname = xstrdup(ctl->server.via);
1087             else
1088                 ctl->server.queryname = xstrdup(ctl->server.pollname);
1089
1090 #ifdef HESIOD
1091         /* If either the pollname or vianame are "hesiod" we want to
1092            lookup the user's hesiod pobox host */
1093
1094         if (!strcasecmp(ctl->server.queryname, "hesiod")) {
1095             struct hes_postoffice *hes_p;
1096             hes_p = hes_getmailhost(ctl->remotename);
1097             if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
1098                  free(ctl->server.queryname);
1099                  ctl->server.queryname = xstrdup(hes_p->po_host);
1100                  if (ctl->server.via)
1101                      free(ctl->server.via);
1102                  ctl->server.via = xstrdup(hes_p->po_host);
1103             } else {
1104                  report(stderr,
1105                         _("couldn't find HESIOD pobox for %s\n"),
1106                         ctl->remotename);
1107             }
1108         }
1109 #endif /* HESIOD */
1110
1111             /*
1112              * We may have to canonicalize the server truename for later use.
1113              * Do this just once for each lead server, if necessary, in order
1114              * to minimize DNS round trips.
1115              */
1116             if (ctl->server.lead_server)
1117             {
1118                 char    *leadname = ctl->server.lead_server->truename;
1119
1120                 /* prevent core dump from ill-formed or duplicate entry */
1121                 if (!leadname)
1122                 {
1123                     report(stderr, 
1124                            _("Lead server has no name.\n"));
1125                     exit(PS_SYNTAX);
1126                 }
1127
1128                 ctl->server.truename = xstrdup(leadname);
1129             }
1130 #ifdef HAVE_GETHOSTBYNAME
1131             else if (!configdump && (ctl->server.preauthenticate==A_KERBEROS_V4 ||
1132                 ctl->server.preauthenticate==A_KERBEROS_V5 ||
1133                       (ctl->server.dns && MULTIDROP(ctl))))
1134             {
1135                 struct hostent  *namerec;
1136
1137                 /* compute the canonical name of the host */
1138                 errno = 0;
1139                 namerec = gethostbyname(ctl->server.queryname);
1140                 if (namerec == (struct hostent *)NULL)
1141                 {
1142                     report(stderr,
1143                           _("couldn't find canonical DNS name of %s\n"),
1144                           ctl->server.pollname);
1145                     exit(PS_DNS);
1146                 }
1147                 else
1148                     ctl->server.truename=xstrdup((char *)namerec->h_name);
1149             }
1150 #endif /* HAVE_GETHOSTBYNAME */
1151             else {
1152 #ifdef HAVE_GETHOSTBYNAME
1153               struct hostent    *namerec;
1154
1155               /* <fetchmail@mail.julianhaight.com>
1156                  Get the host's IP, so we can report it like this:
1157
1158                  Received: from hostname [10.0.0.1]
1159
1160                  do we actually need to gethostbyname to find the IP?
1161                  it seems like it would be faster to do this later, when
1162                  we are actually resolving the hostname for a connection,
1163                  but I ain't that smart, so I don't know where to make
1164                  the change later..
1165               */
1166               errno = 0;
1167               namerec = gethostbyname(ctl->server.queryname);
1168               if (namerec == (struct hostent *)NULL)
1169                 {
1170                   report(stderr,
1171                          _("couldn't find canonical DNS name of %s\n"),
1172                          ctl->server.pollname);
1173                   exit(PS_DNS);
1174                 }
1175               else {
1176                 ctl->server.truename=xstrdup((char *)namerec->h_name);
1177                 ctl->server.trueaddr=xmalloc(namerec->h_length);
1178                 memcpy(ctl->server.trueaddr, 
1179                        namerec->h_addr_list[0],
1180                        namerec->h_length);
1181               }
1182 #else
1183               ctl->server.truename = xstrdup(ctl->server.queryname);
1184 #endif /* HAVE_GETHOSTBYNAME */
1185             }
1186
1187             /* if no folders were specified, set up the null one as default */
1188             if (!ctl->mailboxes)
1189                 save_str(&ctl->mailboxes, (char *)NULL, 0);
1190
1191             /* maybe user overrode timeout on command line? */
1192             if (ctl->server.timeout == -1)      
1193                 ctl->server.timeout = CLIENT_TIMEOUT;
1194
1195 #if !INET6_ENABLE
1196             /* sanity checks */
1197             if (ctl->server.port < 0)
1198             {
1199                 (void) fprintf(stderr,
1200                                _("%s configuration invalid, port number cannot be negative\n"),
1201                                ctl->server.pollname);
1202                 exit(PS_SYNTAX);
1203             }
1204             if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
1205             {
1206                 (void) fprintf(stderr,
1207                                _("%s configuration invalid, RPOP requires a privileged port\n"),
1208                                ctl->server.pollname);
1209                 exit(PS_SYNTAX);
1210             }
1211             if (ctl->listener == LMTP_MODE)
1212             {
1213                 struct idlist   *idp;
1214
1215                 for (idp = ctl->smtphunt; idp; idp = idp->next)
1216                 {
1217                     char        *cp;
1218
1219                     if (!(cp = strrchr(idp->id, '/')) ||
1220                                 (atoi(++cp) == SMTP_PORT))
1221                     {
1222                         (void) fprintf(stderr,
1223                                        _("%s configuration invalid, LMTP can't use default SMTP port\n"),
1224                                        ctl->server.pollname);
1225                         exit(PS_SYNTAX);
1226                     }
1227                 }
1228             }
1229 #endif /* !INET6_ENABLE */
1230
1231             /*
1232              * "I beg to you, have mercy on the week minds like myself."
1233              * wrote Pehr Anderson.  Your petition is granted.
1234              */
1235             if (ctl->fetchall && ctl->keep && run.poll_interval && !nodetach)
1236             {
1237                 (void) fprintf(stderr,
1238                                _("Both fetchall and keep on in daemon mode is a mistake!\n"));
1239                 exit(PS_SYNTAX);
1240             }
1241         }
1242     }
1243
1244 #ifdef POP3_ENABLE
1245     /* initialize UID handling */
1246     if (!versioninfo && (st = prc_filecheck(run.idfile, !versioninfo)) != 0)
1247         exit(st);
1248     else
1249         initialize_saved_lists(querylist, run.idfile);
1250 #endif /* POP3_ENABLE */
1251
1252     /*
1253      * If the user didn't set a last-resort user to get misaddressed
1254      * multidrop mail, set an appropriate default here.
1255      */
1256     if (!run.postmaster)
1257     {
1258         if (getuid())                           /* ordinary user */
1259             run.postmaster = user;
1260         else                                    /* root */
1261             run.postmaster = "postmaster";
1262     }
1263
1264     return(implicitmode);
1265 }
1266
1267 static void terminate_poll(int sig)
1268 /* to be executed at the end of a poll cycle */
1269 {
1270     /*
1271      * Close all SMTP delivery sockets.  For optimum performance
1272      * we'd like to hold them open til end of run, but (1) this
1273      * loses if our poll interval is longer than the MTA's inactivity
1274      * timeout, and (2) some MTAs (like smail) don't deliver after
1275      * each message, but rather queue up mail and wait to actually
1276      * deliver it until the input socket is closed. 
1277      *
1278      * Sending SMTP QUIT on signal is theoretically nice, but led to a 
1279      * subtle bug.  If fetchmail was terminated by signal while it was 
1280      * shipping message text, it would hang forever waiting for a
1281      * command acknowledge.  In theory we could enable the QUIT
1282      * only outside of the message send.  In practice, we don't
1283      * care.  All mailservers hang up on a dropped TCP/IP connection
1284      * anyway.
1285      */
1286
1287     if (sig != 0)
1288         report(stdout, _("terminated with signal %d\n"), sig);
1289     else
1290     {
1291         struct query *ctl;
1292
1293         /* terminate all SMTP connections cleanly */
1294         for (ctl = querylist; ctl; ctl = ctl->next)
1295             if (ctl->smtp_socket != -1)
1296             {
1297                 SMTP_quit(ctl->smtp_socket);
1298                 SockClose(ctl->smtp_socket);
1299                 ctl->smtp_socket = -1;
1300             }
1301     }
1302
1303 #ifdef POP3_ENABLE
1304     /*
1305      * Update UID information at end of each poll, rather than at end
1306      * of run, because that way we don't lose all UIDL information since
1307      * the beginning of time if fetchmail crashes.
1308      */
1309     if (!check_only)
1310         write_saved_lists(querylist, run.idfile);
1311 #endif /* POP3_ENABLE */
1312 }
1313
1314 static void terminate_run(int sig)
1315 /* to be executed on normal or signal-induced termination */
1316 {
1317     struct query        *ctl;
1318
1319     terminate_poll(sig);
1320
1321     /* 
1322      * Craig Metz, the RFC1938 one-time-password guy, points out:
1323      * "Remember that most kernels don't zero pages before handing them to the
1324      * next process and many kernels share pages between user and kernel space.
1325      * You'd be very surprised what you can find from a short program to do a
1326      * malloc() and then dump the contents of the pages you got. By zeroing
1327      * the secrets at end of run (earlier if you can), you make sure the next
1328      * guy can't get the password/pass phrase."
1329      *
1330      * Right you are, Craig!
1331      */
1332     for (ctl = querylist; ctl; ctl = ctl->next)
1333         if (ctl->password)
1334           memset(ctl->password, '\0', strlen(ctl->password));
1335
1336 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
1337     unlockit();
1338 #endif
1339
1340     exit(successes ? PS_SUCCESS : querystatus);
1341 }
1342
1343 /*
1344  * Sequence of protocols to try when autoprobing, most capable to least.
1345  */
1346 static const int autoprobe[] = 
1347 {
1348 #ifdef IMAP_ENABLE
1349     P_IMAP,
1350 #endif /* IMAP_ENABLE */
1351 #ifdef POP3_ENABLE
1352     P_POP3,
1353 #endif /* POP3_ENABLE */
1354 #ifdef POP2_ENABLE
1355     P_POP2
1356 #endif /* POP2_ENABLE */
1357 };
1358
1359 static int query_host(struct query *ctl)
1360 /* perform fetch transaction with single host */
1361 {
1362     int i, st;
1363
1364     /*
1365      * If we're syslogging the progress messages are automatically timestamped.
1366      * Force timestamping if we're going to a logfile.
1367      */
1368     if (outlevel >= O_VERBOSE || (run.logfile && outlevel > O_SILENT))
1369     {
1370         report(stdout, _("%s querying %s (protocol %s) at %s\n"),
1371                VERSION,
1372                ctl->server.pollname,
1373                showproto(ctl->server.protocol),
1374                rfc822timestamp());
1375     }
1376     switch (ctl->server.protocol) {
1377     case P_AUTO:
1378         for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
1379         {
1380             ctl->server.protocol = autoprobe[i];
1381             if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
1382                 break;
1383         }
1384         ctl->server.protocol = P_AUTO;
1385         return(st);
1386     case P_POP2:
1387 #ifdef POP2_ENABLE
1388         return(doPOP2(ctl));
1389 #else
1390         report(stderr, _("POP2 support is not configured.\n"));
1391         return(PS_PROTOCOL);
1392 #endif /* POP2_ENABLE */
1393         break;
1394     case P_POP3:
1395     case P_APOP:
1396     case P_RPOP:
1397 #ifdef POP3_ENABLE
1398         return(doPOP3(ctl));
1399 #else
1400         report(stderr, _("POP3 support is not configured.\n"));
1401         return(PS_PROTOCOL);
1402 #endif /* POP3_ENABLE */
1403         break;
1404     case P_IMAP:
1405     case P_IMAP_K4:
1406     case P_IMAP_CRAM_MD5:
1407     case P_IMAP_LOGIN:
1408 #ifdef GSSAPI
1409     case P_IMAP_GSS:
1410 #endif /* GSSAPI */
1411 #ifdef IMAP_ENABLE
1412         return(doIMAP(ctl));
1413 #else
1414         report(stderr, _("IMAP support is not configured.\n"));
1415         return(PS_PROTOCOL);
1416 #endif /* IMAP_ENABLE */
1417     case P_ETRN:
1418 #ifndef ETRN_ENABLE
1419         report(stderr, _("ETRN support is not configured.\n"));
1420         return(PS_PROTOCOL);
1421 #else
1422 #ifdef HAVE_GETHOSTBYNAME
1423         return(doETRN(ctl));
1424 #else
1425         report(stderr, _("Cannot support ETRN without gethostbyname(2).\n"));
1426         return(PS_PROTOCOL);
1427 #endif /* HAVE_GETHOSTBYNAME */
1428 #endif /* ETRN_ENABLE */
1429     default:
1430         report(stderr, _("unsupported protocol selected.\n"));
1431         return(PS_PROTOCOL);
1432     }
1433 }
1434
1435 static void dump_params (struct runctl *runp,
1436                          struct query *querylist, flag implicit)
1437 /* display query parameters in English */
1438 {
1439     struct query *ctl;
1440
1441     if (runp->poll_interval)
1442         printf(_("Poll interval is %d seconds\n"), runp->poll_interval);
1443     if (runp->logfile)
1444         printf(_("Logfile is %s\n"), runp->logfile);
1445     if (strcmp(runp->idfile, IDFILE_NAME))
1446         printf(_("Idfile is %s\n"), runp->idfile);
1447 #if defined(HAVE_SYSLOG)
1448     if (runp->use_syslog)
1449         printf(_("Progress messages will be logged via syslog\n"));
1450 #endif
1451     if (runp->invisible)
1452         printf(_("Fetchmail will masquerade and will not generate Received\n"));
1453     if (runp->postmaster)
1454         printf(_("Fetchmail will forward misaddressed multidrop messages to %s.\n"),
1455                runp->postmaster);
1456
1457     if (!runp->bouncemail)
1458         printf(_("Fetchmail will direct error mail to the postmaster.\n"));
1459     else if (outlevel >= O_VERBOSE)
1460         printf(_("Fetchmail will direct error mail to the sender.\n"));
1461
1462     for (ctl = querylist; ctl; ctl = ctl->next)
1463     {
1464         if (!ctl->active || (implicit && ctl->server.skip))
1465             continue;
1466
1467         printf(_("Options for retrieving from %s@%s:\n"),
1468                ctl->remotename, visbuf(ctl->server.pollname));
1469
1470         if (ctl->server.via && (ctl->server.protocol != P_ETRN))
1471             printf(_("  Mail will be retrieved via %s\n"), ctl->server.via);
1472
1473         if (ctl->server.interval)
1474             printf(_("  Poll of this server will occur every %d intervals.\n"),
1475                    ctl->server.interval);
1476         if (ctl->server.truename)
1477             printf(_("  True name of server is %s.\n"), ctl->server.truename);
1478         if (ctl->server.skip || outlevel >= O_VERBOSE)
1479             printf(_("  This host %s be queried when no host is specified.\n"),
1480                    ctl->server.skip ? _("will not") : _("will"));
1481         /*
1482          * Don't poll for password when there is one or when using the ETRN
1483          * or IMAP-GSS protocol
1484          */
1485         /* ETRN, IMAP_GSS, and IMAP_K4 do not need a password, so skip this */
1486         if ( (ctl->server.protocol != P_ETRN)
1487 #ifdef GSSAPI
1488                                 && (ctl->server.protocol != P_IMAP_GSS)
1489 #endif /* GSSAPI */
1490                                 && (ctl->server.protocol != P_IMAP_K4) ) {
1491                 if (!ctl->password)
1492                         printf(_("  Password will be prompted for.\n"));
1493                 else if (outlevel >= O_VERBOSE)
1494                 {
1495                         if (ctl->server.protocol == P_APOP)
1496                                 printf(_("  APOP secret = \"%s\".\n"),
1497                                                         visbuf(ctl->password));
1498                         else if (ctl->server.protocol == P_RPOP)
1499                                 printf(_("  RPOP id = \"%s\".\n"),
1500                                                         visbuf(ctl->password));
1501                         else
1502                                 printf(_("  Password = \"%s\".\n"),
1503                                                         visbuf(ctl->password));
1504                 }
1505         }
1506
1507         if (ctl->server.protocol == P_POP3 
1508 #if INET6_ENABLE
1509             && ctl->server.service && !strcmp(ctl->server.service, KPOP_PORT)
1510 #else /* INET6_ENABLE */
1511             && ctl->server.port == KPOP_PORT
1512 #endif /* INET6_ENABLE */
1513             && (ctl->server.preauthenticate == A_KERBEROS_V4 ||
1514                 ctl->server.preauthenticate == A_KERBEROS_V5))
1515             printf(_("  Protocol is KPOP with Kerberos %s authentication"),
1516                    ctl->server.preauthenticate == A_KERBEROS_V5 ? "V" : "IV");
1517         else
1518             printf(_("  Protocol is %s"), showproto(ctl->server.protocol));
1519 #if INET6_ENABLE
1520         if (ctl->server.service)
1521             printf(_(" (using service %s)"), ctl->server.service);
1522         if (ctl->server.netsec)
1523             printf(_(" (using network security options %s)"), ctl->server.netsec);
1524 #else /* INET6_ENABLE */
1525         if (ctl->server.port)
1526             printf(_(" (using port %d)"), ctl->server.port);
1527 #endif /* INET6_ENABLE */
1528         else if (outlevel >= O_VERBOSE)
1529             printf(_(" (using default port)"));
1530         if (ctl->server.uidl && (ctl->server.protocol != P_ETRN))
1531             printf(_(" (forcing UIDL use)"));
1532         putchar('.');
1533         putchar('\n');
1534         if (ctl->server.preauthenticate == A_KERBEROS_V4)
1535             printf(_("  Kerberos V4 preauthentication enabled.\n"));
1536         else if (ctl->server.preauthenticate == A_KERBEROS_V5)
1537             printf(_("  Kerberos V5 preauthentication enabled.\n"));
1538         else if (ctl->server.preauthenticate == A_SSH)
1539             printf(_("  End-to-end encryption assumed.\n"));
1540 #ifdef  SSL_ENABLE
1541         if (ctl->use_ssl)
1542             printf("  SSL encrypted sessions enabled.\n");
1543 #endif
1544         if (ctl->server.timeout > 0)
1545             printf(_("  Server nonresponse timeout is %d seconds"), ctl->server.timeout);
1546         if (ctl->server.timeout ==  CLIENT_TIMEOUT)
1547             printf(_(" (default).\n"));
1548         else
1549             printf(".\n");
1550
1551         if (ctl->server.protocol != P_ETRN) {
1552                 if (!ctl->mailboxes->id)
1553                     printf(_("  Default mailbox selected.\n"));
1554                 else
1555                 {
1556                     struct idlist *idp;
1557
1558                     printf(_("  Selected mailboxes are:"));
1559                     for (idp = ctl->mailboxes; idp; idp = idp->next)
1560                         printf(" %s", idp->id);
1561                     printf("\n");
1562                 }
1563                 printf(_("  %s messages will be retrieved (--all %s).\n"),
1564                        ctl->fetchall ? _("All") : _("Only new"),
1565                        ctl->fetchall ? "on" : "off");
1566                 printf(_("  Fetched messages %s be kept on the server (--keep %s).\n"),
1567                        ctl->keep ? _("will") : _("will not"),
1568                        ctl->keep ? "on" : "off");
1569                 printf(_("  Old messages %s be flushed before message retrieval (--flush %s).\n"),
1570                        ctl->flush ? _("will") : _("will not"),
1571                        ctl->flush ? "on" : "off");
1572                 printf(_("  Rewrite of server-local addresses is %s (--norewrite %s).\n"),
1573                        ctl->rewrite ? _("enabled") : _("disabled"),
1574                        ctl->rewrite ? "off" : "on");
1575                 printf(_("  Carriage-return stripping is %s (stripcr %s).\n"),
1576                        ctl->stripcr ? _("enabled") : _("disabled"),
1577                        ctl->stripcr ? "on" : "off");
1578                 printf(_("  Carriage-return forcing is %s (forcecr %s).\n"),
1579                        ctl->forcecr ? _("enabled") : _("disabled"),
1580                        ctl->forcecr ? "on" : "off");
1581                 printf(_("  Interpretation of Content-Transfer-Encoding is %s (pass8bits %s).\n"),
1582                        ctl->pass8bits ? _("disabled") : _("enabled"),
1583                        ctl->pass8bits ? "on" : "off");
1584                 printf(_("  MIME decoding is %s (mimedecode %s).\n"),
1585                        ctl->mimedecode ? _("enabled") : _("disabled"),
1586                        ctl->mimedecode ? "on" : "off");
1587                 printf(_("  Idle after poll is %s (idle %s).\n"),
1588                        ctl->idle ? _("enabled") : _("disabled"),
1589                        ctl->idle ? "on" : "off");
1590                 printf(_("  Nonempty Status lines will be %s (dropstatus %s)\n"),
1591                        ctl->dropstatus ? _("discarded") : _("kept"),
1592                        ctl->dropstatus ? "on" : "off");
1593                 if (NUM_NONZERO(ctl->limit))
1594                 {
1595                     if (NUM_NONZERO(ctl->limit))
1596                         printf(_("  Message size limit is %d octets (--limit %d).\n"), 
1597                                ctl->limit, ctl->limit);
1598                     else if (outlevel >= O_VERBOSE)
1599                         printf(_("  No message size limit (--limit 0).\n"));
1600                     if (run.poll_interval > 0)
1601                         printf(_("  Message size warning interval is %d seconds (--warnings %d).\n"), 
1602                                ctl->warnings, ctl->warnings);
1603                     else if (outlevel >= O_VERBOSE)
1604                         printf(_("  Size warnings on every poll (--warnings 0).\n"));
1605                 }
1606                 if (NUM_NONZERO(ctl->fetchlimit))
1607                     printf(_("  Received-message limit is %d (--fetchlimit %d).\n"),
1608                            ctl->fetchlimit, ctl->fetchlimit);
1609                 else if (outlevel >= O_VERBOSE)
1610                     printf(_("  No received-message limit (--fetchlimit 0).\n"));
1611                 if (NUM_NONZERO(ctl->batchlimit))
1612                     printf(_("  SMTP message batch limit is %d.\n"), ctl->batchlimit);
1613                 else if (outlevel >= O_VERBOSE)
1614                     printf(_("  No SMTP message batch limit (--batchlimit 0).\n"));
1615                 if (ctl->server.protocol != P_ETRN)
1616                 {
1617                     if (NUM_NONZERO(ctl->expunge))
1618                         printf(_("  Deletion interval between expunges forced to %d (--expunge %d).\n"), ctl->expunge, ctl->expunge);
1619                     else if (outlevel >= O_VERBOSE)
1620                         printf(_("  No forced expunges (--expunge 0).\n"));
1621                 }
1622         }
1623         if (ctl->bsmtp)
1624             printf(_("  Messages will be appended to %s as BSMTP\n"), visbuf(ctl->bsmtp));
1625         else if (ctl->mda && (ctl->server.protocol != P_ETRN))
1626             printf(_("  Messages will be delivered with \"%s\".\n"), visbuf(ctl->mda));
1627         else
1628         {
1629             struct idlist *idp;
1630
1631             printf(_("  Messages will be %cMTP-forwarded to:"), ctl->listener);
1632             for (idp = ctl->smtphunt; idp; idp = idp->next)
1633             {
1634                 printf(" %s", idp->id);
1635                 if (!idp->val.status.mark)
1636                     printf(_(" (default)"));
1637             }
1638             printf("\n");
1639             if (ctl->smtpaddress)
1640                 printf(_("  Host part of MAIL FROM line will be %s\n"),
1641                        ctl->smtpaddress);
1642         }
1643         if (ctl->server.protocol != P_ETRN)
1644         {
1645                 if (ctl->antispam != (struct idlist *)NULL)
1646                 {
1647                     struct idlist *idp;
1648
1649                     printf(_("  Recognized listener spam block responses are:"));
1650                     for (idp = ctl->antispam; idp; idp = idp->next)
1651                         printf(" %d", idp->val.status.num);
1652                     printf("\n");
1653                 }
1654                 else if (outlevel >= O_VERBOSE)
1655                     printf(_("  Spam-blocking disabled\n"));
1656         }
1657         if (ctl->preconnect)
1658             printf(_("  Server connection will be brought up with \"%s\".\n"),
1659                    visbuf(ctl->preconnect));
1660         else if (outlevel >= O_VERBOSE)
1661             printf(_("  No pre-connection command.\n"));
1662         if (ctl->postconnect)
1663             printf(_("  Server connection will be taken down with \"%s\".\n"),
1664                    visbuf(ctl->postconnect));
1665         else if (outlevel >= O_VERBOSE)
1666             printf(_("  No post-connection command.\n"));
1667         if (ctl->server.protocol != P_ETRN) {
1668                 if (!ctl->localnames)
1669                     printf(_("  No localnames declared for this host.\n"));
1670                 else
1671                 {
1672                     struct idlist *idp;
1673                     int count = 0;
1674
1675                     for (idp = ctl->localnames; idp; idp = idp->next)
1676                         ++count;
1677
1678                     if (count > 1 || ctl->wildcard)
1679                         printf(_("  Multi-drop mode: "));
1680                     else
1681                         printf(_("  Single-drop mode: "));
1682
1683                     printf(_("%d local name(s) recognized.\n"), count);
1684                     if (outlevel >= O_VERBOSE)
1685                     {
1686                         for (idp = ctl->localnames; idp; idp = idp->next)
1687                             if (idp->val.id2)
1688                                 printf("\t%s -> %s\n", idp->id, idp->val.id2);
1689                             else
1690                                 printf("\t%s\n", idp->id);
1691                         if (ctl->wildcard)
1692                             fputs("\t*\n", stdout);
1693                     }
1694
1695                     if (count > 1 || ctl->wildcard)
1696                     {
1697                         printf(_("  DNS lookup for multidrop addresses is %s.\n"),
1698                                ctl->server.dns ? _("enabled") : _("disabled"));
1699                         if (ctl->server.dns)
1700                         {
1701                             printf(_("  Server aliases will be compared with multidrop addresses by "));
1702                             if (ctl->server.checkalias)
1703                                 printf(_("IP address.\n"));
1704                             else
1705                                 printf(_("name.\n"));
1706                         }
1707                         if (ctl->server.envelope == STRING_DISABLED)
1708                             printf(_("  Envelope-address routing is disabled\n"));
1709                         else
1710                         {
1711                             printf(_("  Envelope header is assumed to be: %s\n"),
1712                                    ctl->server.envelope ? ctl->server.envelope:_("Received"));
1713                             if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1714                                 printf(_("  Number of envelope header to be parsed: %d\n"),
1715                                        ctl->server.envskip);
1716                             if (ctl->server.qvirtual)
1717                                 printf(_("  Prefix %s will be removed from user id\n"),
1718                                        ctl->server.qvirtual);
1719                             else if (outlevel >= O_VERBOSE) 
1720                                 printf(_("  No prefix stripping\n"));
1721                         }
1722
1723                         if (ctl->server.akalist)
1724                         {
1725                             struct idlist *idp;
1726
1727                             printf(_("  Predeclared mailserver aliases:"));
1728                             for (idp = ctl->server.akalist; idp; idp = idp->next)
1729                                 printf(" %s", idp->id);
1730                             putchar('\n');
1731                         }
1732                         if (ctl->server.localdomains)
1733                         {
1734                             struct idlist *idp;
1735
1736                             printf(_("  Local domains:"));
1737                             for (idp = ctl->server.localdomains; idp; idp = idp->next)
1738                                 printf(" %s", idp->id);
1739                             putchar('\n');
1740                         }
1741                     }
1742                 }
1743         }
1744 #if defined(linux) || defined(__FreeBSD__)
1745         if (ctl->server.interface)
1746             printf(_("  Connection must be through interface %s.\n"), ctl->server.interface);
1747         else if (outlevel >= O_VERBOSE)
1748             printf(_("  No interface requirement specified.\n"));
1749         if (ctl->server.monitor)
1750             printf(_("  Polling loop will monitor %s.\n"), ctl->server.monitor);
1751         else if (outlevel >= O_VERBOSE)
1752             printf(_("  No monitor interface specified.\n"));
1753 #endif
1754
1755         if (ctl->server.plugin)
1756             printf(_("  Server connections will be made via plugin %s (--plugin %s).\n"), ctl->server.plugin, ctl->server.plugin);
1757         else if (outlevel >= O_VERBOSE)
1758             printf(_("  No plugin command specified.\n"));
1759         if (ctl->server.plugout)
1760             printf(_("  Listener connections will be made via plugout %s (--plugout %s).\n"), ctl->server.plugout, ctl->server.plugout);
1761         else if (outlevel >= O_VERBOSE)
1762             printf(_("  No plugout command specified.\n"));
1763
1764         if (ctl->server.protocol > P_POP2 && (ctl->server.protocol != P_ETRN))
1765         {
1766             if (!ctl->oldsaved)
1767                 printf(_("  No UIDs saved from this host.\n"));
1768             else
1769             {
1770                 struct idlist *idp;
1771                 int count = 0;
1772
1773                 for (idp = ctl->oldsaved; idp; idp = idp->next)
1774                     ++count;
1775
1776                 printf(_("  %d UIDs saved.\n"), count);
1777                 if (outlevel >= O_VERBOSE)
1778                     for (idp = ctl->oldsaved; idp; idp = idp->next)
1779                         printf("\t%s\n", idp->id);
1780             }
1781         }
1782
1783         if (ctl->properties)
1784             printf(_("  Pass-through properties \"%s\".\n"),
1785                    visbuf(ctl->properties));
1786     }
1787 }
1788
1789 /* fetchmail.c ends here */