]> Pileus Git - ~andy/fetchmail/blob - fetchmail.c
Rediff patch.
[~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 #include <stdlib.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <syslog.h>
15 #include <pwd.h>
16 #ifdef __FreeBSD__
17 #include <grp.h>
18 #endif
19 #include <errno.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/resource.h>
23
24 #ifdef HAVE_SOCKS
25 #include <socks.h> /* SOCKSinit() */
26 #endif /* HAVE_SOCKS */
27
28 #include <langinfo.h>
29
30 #include "fetchmail.h"
31 #include "socket.h"
32 #include "tunable.h"
33 #include "smtp.h"
34 #include "netrc.h"
35 #include "gettext.h"
36 #include "lock.h"
37
38 /* need these (and sys/types.h) for res_init() */
39 #include <netinet/in.h>
40 #include <arpa/nameser.h>
41 #include <resolv.h>
42
43 #ifndef ENETUNREACH
44 #define ENETUNREACH   128       /* Interactive doesn't know this */
45 #endif /* ENETUNREACH */
46
47 /* prototypes for internal functions */
48 static int load_params(int, char **, int);
49 static void dump_params (struct runctl *runp, struct query *, flag implicit);
50 static int query_host(struct query *);
51
52 /* controls the detail level of status/progress messages written to stderr */
53 int outlevel;               /* see the O_.* constants above */
54
55 /* miscellaneous global controls */
56 struct runctl run;          /* global controls for this run */
57 flag nodetach;              /* if TRUE, don't detach daemon process */
58 flag quitmode;              /* if --quit was set */
59 int  quitind;               /* optind after position of last --quit option */
60 flag check_only;            /* if --probe was set */
61 flag versioninfo;           /* emit only version info */
62 char *user;                 /* the name of the invoking user */
63 char *home;                 /* invoking user's home directory */
64 char *fmhome;               /* fetchmail's home directory */
65 const char *program_name;   /* the name to prefix error messages with */
66 flag configdump;            /* dump control blocks for configurator */
67 const char *fetchmailhost;  /* either `localhost' or the host's FQDN */
68
69 static int quitonly;        /* if we should quit after killing the running daemon */
70
71 static int querystatus;         /* status of query */
72 static int successes;           /* count number of successful polls */
73 static int activecount;         /* count number of active entries */
74 static struct runctl cmd_run;   /* global options set from command line */
75 static time_t parsetime;        /* time of last parse */
76
77 static void terminate_run(int);
78 static void terminate_poll(int);
79
80 #ifdef HAVE_LIBPWMD
81 static pwm_t *pwm;              /* the handle */
82 static const char *pwmd_socket; /* current socket */
83 static const char *pwmd_file;   /* current file */
84 #endif
85
86 #if defined(__FreeBSD__) && defined(__FreeBSD_USE_KVM)
87 /* drop SGID kmem privileage until we need it */
88 static void dropprivs(void)
89 {
90     struct group *gr;
91     gid_t        egid;
92     gid_t        rgid;
93     
94     egid = getegid();
95     rgid = getgid();
96     gr = getgrgid(egid);
97     
98     if (gr && !strcmp(gr->gr_name, "kmem"))
99     {
100         extern void interface_set_gids(gid_t egid, gid_t rgid);
101         interface_set_gids(egid, rgid);
102         setegid(rgid);
103     }
104 }
105 #endif
106
107 #include <locale.h>
108 #if defined(ENABLE_NLS)
109 /** returns timestamp in current locale,
110  * and resets LC_TIME locale to POSIX. */
111 static char *timestamp (void)
112 {
113     time_t      now;
114     static char buf[60]; /* RATS: ignore */
115
116     time (&now);
117     setlocale (LC_TIME, "");
118     strftime (buf, sizeof (buf), "%c", localtime(&now));
119     setlocale (LC_TIME, "C");
120     return (buf);
121 }
122 #else
123 #define timestamp rfc822timestamp
124 #endif
125
126 static void donothing(int sig) 
127 {
128     set_signal_handler(sig, donothing);
129     lastsig = sig;
130 }
131
132 static void printcopyright(FILE *fp) {
133         fprintf(fp, GT_("Copyright (C) 2002, 2003 Eric S. Raymond\n"
134                    "Copyright (C) 2004 Matthias Andree, Eric S. Raymond,\n"
135                    "                   Robert M. Funk, Graham Wilson\n"
136                    "Copyright (C) 2005 - 2006, 2010 - 2012 Sunil Shetye\n"
137                    "Copyright (C) 2005 - 2012 Matthias Andree\n"
138                    ));
139         fprintf(fp, GT_("Fetchmail comes with ABSOLUTELY NO WARRANTY. This is free software, and you\n"
140                    "are welcome to redistribute it under certain conditions. For details,\n"
141                    "please see the file COPYING in the source or documentation directory.\n"));
142 #ifdef SSL_ENABLE
143         /* Do not translate this */
144         fprintf(fp, "This product includes software developed by the OpenSSL Project\nfor use in the OpenSSL Toolkit. (http://www.openssl.org/)\n");
145 #endif
146 }
147
148 const char *iana_charset;
149
150 #ifdef HAVE_LIBPWMD
151 static void exit_with_pwmd_error(gpg_error_t error)
152 {
153     gpg_err_code_t code = gpg_err_code(error);
154
155     report(stderr, GT_("pwmd: error %i: %s\n"), code, pwmd_strerror(error));
156
157     if (pwm) {
158         pwmd_close(pwm);
159         pwm = NULL;
160     }
161
162     /* Don't exit if daemonized. There may be other active accounts. */
163     if (isatty(1))
164         exit(PS_UNDEFINED);
165 }
166
167 static int do_pwmd_connect(const char *socketname, const char *filename)
168 {
169     static int init;
170     gpg_error_t rc;
171     pwmd_socket_t s;
172
173     if (!init) {
174         pwmd_init();
175         init = 1;
176     }
177
178     if (!pwm || (pwm && socketname && !pwmd_socket) ||
179             (pwm && !socketname && pwmd_socket) ||
180             (pwm && socketname && pwmd_socket && strcmp(socketname, pwmd_socket))) {
181         if (pwm)
182             pwmd_close(pwm);
183
184         pwm = pwmd_new("Fetchmail");
185         rc = pwmd_connect_url(pwm, socketname);
186
187         if (rc) {
188             exit_with_pwmd_error(rc);
189             return 1;
190         }
191     }
192
193     if (run.pinentry_timeout > 0) {
194         rc = pwmd_setopt(pwm, PWMD_OPTION_PINENTRY_TIMEOUT,
195                 run.pinentry_timeout);
196
197         if (rc) {
198             exit_with_pwmd_error(rc);
199             return 1;
200         }
201     }
202
203     rc = pwmd_socket_type(pwm, &s);
204
205     if (rc) {
206         exit_with_pwmd_error(rc);
207         return 1;
208     }
209
210     if (!pwmd_file || strcmp(filename, pwmd_file)) {
211         if (s == PWMD_SOCKET_SSH)
212             /* use a local pinentry since X11 forwarding is broken. */
213             rc = pwmd_open2(pwm, filename);
214         else
215             rc = pwmd_open(pwm, filename);
216
217         if (rc) {
218             exit_with_pwmd_error(rc);
219             return 1;
220         }
221     }
222
223     /* May be null to use the default of ~/.pwmd/socket. */
224     pwmd_socket = socketname;
225     pwmd_file = filename;
226     return 0;
227 }
228
229 static int get_pwmd_details(const char *pwmd_account, int protocol,
230         struct query *ctl)
231 {
232     const char *prot = showproto(protocol);
233     gpg_error_t error;
234     char *result;
235     char *tmp = xstrdup(pwmd_account);
236     int i;
237
238     for (i = 0; tmp[i]; i++) {
239         if (i && tmp[i] == '^')
240             tmp[i] = '\t';
241     }
242
243     /*
244      * Get the hostname for this protocol. Element path must be
245      * account->[protocol]->hostname.
246      */
247     error = pwmd_command(pwm, &result, "GET %s\t%s\thostname", tmp, prot);
248
249     if (error) {
250         if (gpg_err_code(error) == GPG_ERR_NOT_FOUND) {
251             report(stderr, GT_("pwmd: %s->%s->hostname: %s\n"), pwmd_account, prot, pwmd_strerror(error));
252             pwmd_close(pwm);
253             pwm = NULL;
254
255             if (isatty(1))
256                 exit(PS_SYNTAX);
257
258             return 1;
259         }
260         else {
261             exit_with_pwmd_error(error);
262             return 1;
263         }
264     }
265
266     if (ctl->server.pollname != ctl->server.via)
267         xfree(ctl->server.via);
268
269     ctl->server.via = xstrdup(result);
270
271     if (ctl->server.queryname)
272         xfree(ctl->server.queryname);
273
274     ctl->server.queryname = xstrdup(ctl->server.via);
275
276     if (ctl->server.truename)
277         xfree(ctl->server.truename);
278
279     ctl->server.truename = xstrdup(ctl->server.queryname);
280     pwmd_free(result);
281
282     /*
283      * Server port. Fetchmail tries standard ports for known services so it
284      * should be alright if this element isn't found. ctl->server.protocol is
285      * already set. This sets ctl->server.service.
286      */
287     error = pwmd_command(pwm, &result, "GET %s\t%s\tport", tmp, prot);
288
289     if (error) {
290         if (gpg_err_code(error) == GPG_ERR_NOT_FOUND)
291             report(stderr, GT_("pwmd: %s->%s->port: %s\n"), pwmd_account, prot, pwmd_strerror(error));
292         else {
293             exit_with_pwmd_error(error);
294             return 1;
295         }
296     }
297     else {
298         if (ctl->server.service)
299             xfree(ctl->server.service);
300
301         ctl->server.service = xstrdup(result);
302         pwmd_free(result);
303     }
304
305     /*
306      * Get the remote username. Element must be account->username.
307      */
308     error = pwmd_command(pwm, &result, "GET %s\tusername", tmp);
309
310     if (error) {
311         if (gpg_err_code(error) == GPG_ERR_NOT_FOUND) {
312             report(stderr, GT_("pwmd: %s->username: %s\n"), pwmd_account, pwmd_strerror(error));
313
314             if (!isatty(1)) {
315                 pwmd_close(pwm);
316                 pwm = NULL;
317                 return 1;
318             }
319         }
320         else {
321             exit_with_pwmd_error(error);
322             return 1;
323         }
324     }
325     else {
326         if (ctl->remotename)
327             xfree(ctl->remotename);
328
329         if (ctl->server.esmtp_name)
330             xfree(ctl->server.esmtp_name);
331
332         ctl->remotename = xstrdup(result);
333         ctl->server.esmtp_name = xstrdup(result);
334         pwmd_free(result);
335     }
336
337     /*
338      * Get the remote password. Element must be account->password.
339      */
340     error = pwmd_command(pwm, &result, "GET %s\tpassword", tmp);
341
342     if (error) {
343         if (gpg_err_code(error) == GPG_ERR_NOT_FOUND) {
344             report(stderr, GT_("pwmd: %s->password: %s\n"), pwmd_account, pwmd_strerror(error));
345
346             if (!isatty(1)) {
347                 pwmd_close(pwm);
348                 pwm = NULL;
349                 return 1;
350             }
351         }
352         else {
353             exit_with_pwmd_error(error);
354             return 1;
355         }
356     }
357     else {
358         if (ctl->password)
359             xfree(ctl->password);
360
361         ctl->password= xstrdup(result);
362         pwmd_free(result);
363     }
364
365 #ifdef SSL_ENABLE
366     /*
367      * If there is a ssl element and set to 1, enable ssl for this account.
368      * Element path must be account->[protocol]->ssl.
369      */
370     error = pwmd_command(pwm, &result, "GET %s\t%s\tssl", tmp, prot);
371
372     if (error) {
373         if (gpg_err_code(error) == GPG_ERR_NOT_FOUND) {
374             report(stderr, GT_("pwmd: %s->%s->ssl: %s\n"), pwmd_account, prot, pwmd_strerror(error));
375
376             if (!isatty(1)) {
377                 pwmd_close(pwm);
378                 pwm = NULL;
379                 return 1;
380             }
381         }
382         else {
383             exit_with_pwmd_error(error);
384             return 1;
385         }
386     }
387     else {
388         ctl->use_ssl = atoi(result) >= 1 ? FLAG_TRUE : FLAG_FALSE;
389         pwmd_free(result);
390     }
391
392     /*
393      * account->[protocol]->sslfingerprint.
394      */
395     error = pwmd_command(pwm, &result, "GET %s\t%s\tsslfingerprint", tmp, prot);
396
397     if (error) {
398         if (gpg_err_code(error) == GPG_ERR_NOT_FOUND) {
399             report(stderr, GT_("pwmd: %s->%s->sslfingerprint: %s\n"), pwmd_account, prot, pwmd_strerror(error));
400
401             if (!isatty(1)) {
402                 pwmd_close(pwm);
403                 pwm = NULL;
404                 return 1;
405             }
406         }
407         else {
408             exit_with_pwmd_error(error);
409             return 1;
410         }
411     }
412     else {
413         if (ctl->sslfingerprint)
414             xfree(ctl->sslfingerprint);
415
416         ctl->sslfingerprint = xstrdup(result);
417         pwmd_free(result);
418     }
419 #endif
420
421     xfree(tmp);
422     return 0;
423 }
424 #endif
425
426 int main(int argc, char **argv)
427 {
428     int bkgd = FALSE;
429     int implicitmode = FALSE;
430     flag safewithbg = FALSE; /** if parsed options are compatible with a
431                               fetchmail copy running in the background */
432     struct query *ctl;
433     netrc_entry *netrc_list;
434     char *netrc_file, *tmpbuf;
435     pid_t pid;
436     int lastsig = 0;
437
438 #if defined(__FreeBSD__) && defined(__FreeBSD_USE_KVM)
439     dropprivs();
440 #endif
441
442     envquery(argc, argv);
443 #ifdef ENABLE_NLS
444     setlocale (LC_ALL, "");
445     bindtextdomain(PACKAGE, LOCALEDIR);
446     textdomain(PACKAGE);
447     iana_charset = norm_charmap(nl_langinfo(CODESET)); /* normalize local
448                                                           charset to
449                                                           IANA charset. */
450 #else
451     iana_charset = "US-ASCII";
452 #endif
453
454     if (getuid() == 0) {
455         report(stderr, GT_("WARNING: Running as root is discouraged.\n"));
456     }
457
458     /*
459      * Note: because we can't initialize reporting before we  know whether
460      * syslog is supposed to be on, this message will go to stdout and
461      * be lost when running in background.
462      */
463     if (outlevel >= O_VERBOSE)
464     {
465         int i;
466
467         report(stdout, GT_("fetchmail: invoked with"));
468         for (i = 0; i < argc; i++)
469             report(stdout, " %s", argv[i]);
470         report(stdout, "\n");
471     }
472
473 #define IDFILE_NAME     ".fetchids"
474     run.idfile = prependdir (IDFILE_NAME, fmhome);
475
476     outlevel = O_NORMAL;
477
478     /*
479      * We used to arrange for the lock to be removed on exit close
480      * to where the lock was asserted.  Now we need to do it here, because
481      * we might have re-executed in background with an existing lock
482      * as the result of a changed rcfile (see the code near the execvp(3)
483      * call near the beginning of the polling loop for details).  We want
484      * to be sure the lock gets nuked on any error exit, basically.
485      */
486     fm_lock_dispose();
487
488 #ifdef HAVE_GETCWD
489     /* save the current directory */
490     if (getcwd (currentwd, sizeof (currentwd)) == NULL) {
491         report(stderr, GT_("could not get current working directory\n"));
492         currentwd[0] = 0;
493     }
494 #endif
495
496     {
497         int i;
498
499         i = parsecmdline(argc, argv, &cmd_run, &cmd_opts, &safewithbg);
500         if (i < 0)
501             exit(PS_SYNTAX);
502
503         if (quitmode && quitind == argc)
504             quitonly = 1;
505     }
506
507     if (versioninfo)
508     {
509         const char *features = 
510 #ifndef POP3_ENABLE
511         "-POP3"
512 #endif /* POP3_ENABLE */
513 #ifndef IMAP_ENABLE
514         "-IMAP"
515 #endif /* IMAP_ENABLE */
516 #ifdef GSSAPI
517         "+GSS"
518 #endif /* GSSAPI */
519 #ifdef RPA_ENABLE
520         "+RPA"
521 #endif /* RPA_ENABLE */
522 #ifdef NTLM_ENABLE
523         "+NTLM"
524 #endif /* NTLM_ENABLE */
525 #ifdef SDPS_ENABLE
526         "+SDPS"
527 #endif /* SDPS_ENABLE */
528 #ifndef ETRN_ENABLE
529         "-ETRN"
530 #endif /* ETRN_ENABLE */
531 #ifndef ODMR_ENABLE
532         "-ODMR"
533 #endif /* ODMR_ENABLE */
534 #ifdef SSL_ENABLE
535         "+SSL"
536 #endif
537 #ifdef OPIE_ENABLE
538         "+OPIE"
539 #endif /* OPIE_ENABLE */
540 #ifdef HAVE_PKG_hesiod
541         "+HESIOD"
542 #endif
543 #ifdef HAVE_SOCKS
544         "+SOCKS"
545 #endif /* HAVE_SOCKS */
546 #ifdef ENABLE_NLS
547         "+NLS"
548 #endif /* ENABLE_NLS */
549 #ifdef KERBEROS_V5
550         "+KRB5"
551 #endif /* KERBEROS_V5 */
552 #ifdef HAVE_LIBPWMD
553         "+PWMD"
554 #endif /* HAVE_LIBPWMD */
555         ".\n";
556         printf(GT_("This is fetchmail release %s"), VERSION);
557         fputs(features, stdout);
558         puts("");
559         printcopyright(stdout);
560         puts("");
561         fputs("Fallback MDA: ", stdout);
562 #ifdef FALLBACK_MDA
563         fputs(FALLBACK_MDA, stdout);
564 #else
565         fputs("(none)", stdout);
566 #endif
567         putchar('\n');
568         fflush(stdout);
569
570         /* this is an attempt to help remote debugging */
571         if (system("uname -a")) { /* NOOP to quench GCC complaint */ }
572     }
573
574     /* avoid parsing the config file if all we're doing is killing a daemon */
575     if (!quitonly)
576         implicitmode = load_params(argc, argv, optind);
577
578     /* precedence: logfile (if effective) overrides syslog. */
579     if (run.logfile && run.poll_interval && !nodetach) {
580         run.use_syslog = 0;
581     }
582
583     /* logging should be set up early in case we were restarted from exec */
584     if (run.use_syslog)
585     {
586         openlog(program_name, LOG_PID, LOG_MAIL);
587         report_init(-1);
588     }
589     else
590         report_init((run.poll_interval == 0 || nodetach) && !run.logfile);
591
592 #ifdef POP3_ENABLE
593     /* initialize UID handling */
594     {
595         int st;
596
597         if (!versioninfo && (st = prc_filecheck(run.idfile, !versioninfo)) != 0)
598             exit(st);
599         else
600             initialize_saved_lists(querylist, run.idfile);
601     }
602 #endif /* POP3_ENABLE */
603
604     /* construct the lockfile */
605     fm_lock_setup(&run);
606
607     /*
608      * Before getting passwords, disable core dumps unless -v -d0 mode is on.
609      * Core dumps could otherwise contain passwords to be scavenged by a
610      * cracker.
611      */
612     if (outlevel < O_VERBOSE || run.poll_interval > 0)
613     {
614         struct rlimit corelimit;
615         corelimit.rlim_cur = 0;
616         corelimit.rlim_max = 0;
617         setrlimit(RLIMIT_CORE, &corelimit);
618     }
619
620 #define NETRC_FILE      ".netrc"
621     /* parse the ~/.netrc file (if present) for future password lookups. */
622     netrc_file = prependdir (NETRC_FILE, home);
623     netrc_list = parse_netrc(netrc_file);
624     free(netrc_file);
625 #undef NETRC_FILE
626
627     /* pick up passwords where we can */ 
628     for (ctl = querylist; ctl; ctl = ctl->next)
629     {
630         if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
631         {
632             if (NO_PASSWORD(ctl))
633                 /* Server won't care what the password is, but there
634                    must be some non-null string here.  */
635                 ctl->password = ctl->remotename;
636             else
637             {
638                 netrc_entry *p;
639
640                 /* look up the pollname and account in the .netrc file. */
641                 p = search_netrc(netrc_list,
642                                  ctl->server.pollname, ctl->remotename);
643                 /* if we find a matching entry with a password, use it */
644                 if (p && p->password)
645                     ctl->password = xstrdup(p->password);
646
647                 /* otherwise try with "via" name if there is one */
648                 else if (ctl->server.via)
649                 {
650                     p = search_netrc(netrc_list, 
651                                      ctl->server.via, ctl->remotename);
652                     if (p && p->password)
653                         ctl->password = xstrdup(p->password);
654                 }
655             }
656         }
657     }
658
659     free_netrc(netrc_list);
660     netrc_list = 0;
661
662     /* perhaps we just want to check options? */
663     if (versioninfo)
664     {
665         int havercfile = access(rcfile, 0);
666
667         printf(GT_("Taking options from command line%s%s\n"),
668                                 havercfile ? "" :  GT_(" and "),
669                                 havercfile ? "" : rcfile);
670
671         if (querylist == NULL)
672             fprintf(stderr,
673                     GT_("No mailservers set up -- perhaps %s is missing?\n"),
674                     rcfile);
675         else
676             dump_params(&run, querylist, implicitmode);
677         exit(0);
678     }
679
680     /* dump options as a Python dictionary, for configurator use */
681     if (configdump)
682     {
683         dump_config(&run, querylist);
684         exit(0);
685     }
686
687     /* check for another fetchmail running concurrently */
688     pid = fm_lock_state();
689     bkgd = (pid < 0);
690     pid = bkgd ? -pid : pid;
691
692     /* if no mail servers listed and nothing in background, we're done */
693     if (!quitonly && pid == 0 && querylist == NULL) {
694         (void)fputs(GT_("fetchmail: no mailservers have been specified.\n"),stderr);
695         exit(PS_SYNTAX);
696     }
697
698     /* perhaps user asked us to kill the other fetchmail */
699     if (quitmode)
700     {
701         if (pid == 0 || pid == getpid())
702             /* this test enables re-execing on a changed rcfile
703              * for pid == getpid() */
704         {
705             if (quitonly) {
706                 fprintf(stderr,GT_("fetchmail: no other fetchmail is running\n"));
707                 exit(PS_EXCLUDE);
708             }
709         }
710         else if (kill(pid, SIGTERM) < 0)
711         {
712             fprintf(stderr,GT_("fetchmail: error killing %s fetchmail at %ld; bailing out.\n"),
713                     bkgd ? GT_("background") : GT_("foreground"), (long)pid);
714             exit(PS_EXCLUDE);
715         }
716         else
717         {
718             int maxwait;
719
720             if (outlevel > O_SILENT)
721                 fprintf(stderr,GT_("fetchmail: %s fetchmail at %ld killed.\n"),
722                         bkgd ? GT_("background") : GT_("foreground"), (long)pid);
723             /* We used to nuke the other process's lock here, with
724              * fm_lock_release(), which is broken. The other process
725              * needs to clear its lock by itself. */
726             if (quitonly)
727                 exit(0);
728
729             /* wait for other process to exit */
730             maxwait = 10; /* seconds */
731             while (kill(pid, 0) == 0 && --maxwait >= 0) {
732                 sleep(1);
733             }
734             pid = 0;
735         }
736     }
737
738     /* another fetchmail is running -- wake it up or die */
739     if (pid != 0)
740     {
741         if (check_only)
742         {
743             fprintf(stderr,
744                  GT_("fetchmail: can't check mail while another fetchmail to same host is running.\n"));
745             return(PS_EXCLUDE);
746         }
747         else if (!implicitmode)
748         {
749             fprintf(stderr,
750                  GT_("fetchmail: can't poll specified hosts with another fetchmail running at %ld.\n"),
751                  (long)pid);
752                 return(PS_EXCLUDE);
753         }
754         else if (!bkgd)
755         {
756             fprintf(stderr,
757                  GT_("fetchmail: another foreground fetchmail is running at %ld.\n"),
758                  (long)pid);
759                 return(PS_EXCLUDE);
760         }
761         else if (getpid() == pid)
762             /* this test enables re-execing on a changed rcfile */
763             fm_lock_assert();
764         else if (argc > 1 && !safewithbg)
765         {
766             fprintf(stderr,
767                     GT_("fetchmail: can't accept options while a background fetchmail is running.\n"));
768             {
769                 int i;
770                 fprintf(stderr, "argc = %d, arg list:\n", argc);
771                 for (i = 1; i < argc; i++) fprintf(stderr, "arg %d = \"%s\"\n", i, argv[i]);
772             }
773             return(PS_EXCLUDE);
774         }
775         else if (kill(pid, SIGUSR1) == 0)
776         {
777             if (outlevel > O_SILENT)
778                 fprintf(stderr,
779                         GT_("fetchmail: background fetchmail at %ld awakened.\n"),
780                         (long)pid);
781             return(0);
782         }
783         else
784         {
785             /*
786              * Should never happen -- possible only if a background fetchmail
787              * croaks after the first kill probe above but before the
788              * SIGUSR1/SIGHUP transmission.
789              */
790             fprintf(stderr,
791                     GT_("fetchmail: elder sibling at %ld died mysteriously.\n"),
792                     (long)pid);
793             return(PS_UNDEFINED);
794         }
795     }
796
797     /* pick up interactively any passwords we need but don't have */ 
798     for (ctl = querylist; ctl; ctl = ctl->next)
799     {
800         if (ctl->active && !(implicitmode && ctl->server.skip)
801                 && !NO_PASSWORD(ctl) && !ctl->password)
802         {
803             if (!isatty(0))
804             {
805                 fprintf(stderr,
806                         GT_("fetchmail: can't find a password for %s@%s.\n"),
807                         ctl->remotename, ctl->server.pollname);
808                 return(PS_AUTHFAIL);
809             } else {
810                 const char* password_prompt = GT_("Enter password for %s@%s: ");
811                 size_t pplen = strlen(password_prompt) + strlen(ctl->remotename) + strlen(ctl->server.pollname) + 1;
812
813                 tmpbuf = (char *)xmalloc(pplen);
814                 snprintf(tmpbuf, pplen, password_prompt,
815                         ctl->remotename, ctl->server.pollname);
816                 ctl->password = xstrdup((char *)fm_getpassword(tmpbuf));
817                 free(tmpbuf);
818             }
819         }
820     }
821
822     /*
823      * Time to initiate the SOCKS library (this is not mandatory: it just
824      * registers the correct application name for logging purpose. If you
825      * have some problem, comment out these lines).
826      */
827 #ifdef HAVE_SOCKS
828     SOCKSinit("fetchmail");
829 #endif /* HAVE_SOCKS */
830
831     /* avoid zombies from plugins */
832     deal_with_sigchld();
833
834     /* Fix up log destination - if the if() is true, the precedence rule
835      * above hasn't killed off the syslog option, because the logfile
836      * option is ineffective (because we're not detached or not in
837      * deamon mode), so kill it for the benefit of other parts of the
838      * code. */
839     if (run.logfile && run.use_syslog)
840         run.logfile = 0;
841
842     /*
843      * Maybe time to go to demon mode...
844      */
845     if (run.poll_interval)
846     {
847         if (!nodetach) {
848             int rc;
849
850             rc = daemonize(run.logfile);
851             if (rc) {
852                 report(stderr, GT_("fetchmail: Cannot detach into background. Aborting.\n"));
853                 exit(rc);
854             }
855         }
856         report(stdout, GT_("starting fetchmail %s daemon\n"), VERSION);
857
858         /*
859          * We'll set up a handler for these when we're sleeping,
860          * but ignore them otherwise so as not to interrupt a poll.
861          */
862         set_signal_handler(SIGUSR1, SIG_IGN);
863         if (run.poll_interval && getuid() == ROOT_UID)
864             set_signal_handler(SIGHUP, SIG_IGN);
865     }
866     else
867     {
868         /* not in daemon mode */
869         if (run.logfile && !nodetach && access(run.logfile, F_OK) == 0)
870         {
871             if (!freopen(run.logfile, "a", stdout))
872                     report(stderr, GT_("could not open %s to append logs to\n"), run.logfile);
873             if (!freopen(run.logfile, "a", stderr))
874                     report(stdout, GT_("could not open %s to append logs to\n"), run.logfile);
875             if (run.use_syslog)
876                 report(stdout, GT_("fetchmail: Warning: syslog and logfile are set. Check both for logs!\n"));
877         }
878     }
879
880     interface_init();
881
882     /* beyond here we don't want more than one fetchmail running per user */
883     umask(0077);
884     set_signal_handler(SIGABRT, terminate_run);
885     set_signal_handler(SIGINT, terminate_run);
886     set_signal_handler(SIGTERM, terminate_run);
887     set_signal_handler(SIGALRM, terminate_run);
888     set_signal_handler(SIGPIPE, SIG_IGN);
889     set_signal_handler(SIGQUIT, terminate_run);
890
891     /* here's the exclusion lock */
892     fm_lock_or_die();
893
894     if (check_only && outlevel >= O_VERBOSE) {
895         report(stdout, GT_("--check mode enabled, not fetching mail\n"));
896     }
897
898     /*
899      * Query all hosts. If there's only one, the error return will
900      * reflect the status of that transaction.
901      */
902     do {
903         /* 
904          * Check to see if the rcfile has been touched.  If so,
905          * re-exec so the file will be reread.  Doing it this way
906          * avoids all the complications of trying to deallocate the
907          * in-core control structures -- and the potential memory
908          * leaks...
909          */
910         struct stat     rcstat;
911 #ifdef HAVE_LIBPWMD
912         time_t now;
913
914         time(&now);
915 #endif
916
917         if (strcmp(rcfile, "-") == 0) {
918             /* do nothing */
919         } else if (stat(rcfile, &rcstat) == -1) {
920             if (errno != ENOENT)
921                 report(stderr, 
922                        GT_("couldn't time-check %s (error %d)\n"),
923                        rcfile, errno);
924         }
925 #ifdef HAVE_LIBPWMD
926         /*
927          * isatty() to make sure this is a background process since the
928          * lockfile is removed after each invokation.
929          */
930         else if (!isatty(1) && rcstat.st_mtime > parsetime)
931 #else
932         else if (rcstat.st_mtime > parsetime)
933 #endif
934         {
935             report(stdout, GT_("restarting fetchmail (%s changed)\n"), rcfile);
936
937 #ifdef HAVE_GETCWD
938             /* restore the startup directory */
939             if (!currentwd[0] || chdir (currentwd) == -1)
940                 report(stderr, GT_("attempt to re-exec may fail as directory has not been restored\n"));
941 #endif
942
943             /*
944              * Matthias Andree: Isn't this prone to introduction of
945              * "false" programs by interfering with PATH? Those
946              * path-searching execs might not be the best ideas for
947              * this reason.
948              *
949              * Rob Funk: But is there any way for someone to modify
950              * the PATH variable of a running fetchmail?  I don't know
951              * of a way.
952              *
953              * Dave's change makes fetchmail restart itself in exactly
954              * the way it was started from the shell (or shell script)
955              * in the first place.  If you're concerned about PATH
956              * contamination, call fetchmail initially with a full
957              * path, and use Dave's patch.
958              *
959              * Not using a -p variant of exec means that the restart
960              * will break if both (a) the user depended on PATH to
961              * call fetchmail in the first place, and (b) the system
962              * doesn't save the whole path in argv[0] if the whole
963              * path wasn't used in the initial call.  (If I recall
964              * correctly, Linux saves it but many other Unices don't.)
965              */
966             execvp(argv[0], argv);
967             report(stderr, GT_("attempt to re-exec fetchmail failed\n"));
968         }
969
970 #ifdef HAVE_RES_SEARCH
971         /* Boldly assume that we also have res_init() if we have
972          * res_search(), and call res_init() to re-read the resolv.conf
973          * file, so that we can pick up changes to that file that are
974          * written by dhpccd, dhclient, pppd, openvpn and similar. */
975
976         /* NOTE: This assumes that /etc/resolv.conf is written
977          * atomically (i. e. a temporary file is written, flushed and
978          * then renamed into place). To fix Debian Bug#389270. */
979
980         /* NOTE: If this leaks memory or doesn't re-read
981          * /etc/resolv.conf, we're in trouble. The res_init() interface
982          * is only lightly documented :-( */
983         res_init();
984 #endif
985
986         activecount = 0;
987         batchcount = 0;
988         for (ctl = querylist; ctl; ctl = ctl->next)
989             if (ctl->active)
990             {
991                 activecount++;
992                 if (!(implicitmode && ctl->server.skip))
993                 {
994                     if (ctl->wedged)
995                     {
996                         report(stderr, 
997                                GT_("poll of %s skipped (failed authentication or too many timeouts)\n"),
998                                ctl->server.pollname);
999                         continue;
1000                     }
1001
1002                     /* check skip interval first so that it counts all polls */
1003                     if (run.poll_interval && ctl->server.interval) 
1004                     {
1005                         if (ctl->server.poll_count++ % ctl->server.interval) 
1006                         {
1007                             if (outlevel >= O_VERBOSE)
1008                                 report(stdout,
1009                                        GT_("interval not reached, not querying %s\n"),
1010                                        ctl->server.pollname);
1011                             continue;
1012                         }
1013                     }
1014
1015 #ifdef CAN_MONITOR
1016                     /*
1017                      * Don't do monitoring if we were woken by a signal.
1018                      * Note that interface_approve() does its own error logging.
1019                      */
1020                     if (!interface_approve(&ctl->server, !lastsig))
1021                         continue;
1022 #endif /* CAN_MONITOR */
1023
1024                     dofastuidl = 0; /* this is reset in the driver if required */
1025
1026 #ifdef HAVE_LIBPWMD
1027                     /*
1028                      * At each poll interval, check the pwmd server for
1029                      * changes in host and auth settings.
1030                      */
1031                     if (ctl->pwmd_file) {
1032                         if (do_pwmd_connect(ctl->pwmd_socket, ctl->pwmd_file))
1033                             continue;
1034
1035                         if (get_pwmd_details(ctl->server.pollname, ctl->server.protocol, ctl))
1036                             continue;
1037                     }
1038 #endif
1039                     querystatus = query_host(ctl);
1040
1041                     if (NUM_NONZERO(ctl->fastuidl))
1042                         ctl->fastuidlcount = (ctl->fastuidlcount + 1) % ctl->fastuidl;
1043 #ifdef POP3_ENABLE
1044                     /* leave the UIDL state alone if there have been any errors */
1045                     if (!check_only &&
1046                                 ((querystatus==PS_SUCCESS) || (querystatus==PS_NOMAIL) || (querystatus==PS_MAXFETCH)))
1047                         uid_swap_lists(ctl);
1048                     else
1049                         uid_discard_new_list(ctl);
1050                     uid_reset_num(ctl);
1051 #endif  /* POP3_ENABLE */
1052
1053                     if (querystatus == PS_SUCCESS)
1054                         successes++;
1055                     else if (!check_only && 
1056                              ((querystatus!=PS_NOMAIL) || (outlevel==O_DEBUG)))
1057                         switch(querystatus)
1058                         {
1059                         case PS_SUCCESS:
1060                             report(stdout,GT_("Query status=0 (SUCCESS)\n"));break;
1061                         case PS_NOMAIL: 
1062                             report(stdout,GT_("Query status=1 (NOMAIL)\n")); break;
1063                         case PS_SOCKET:
1064                             report(stdout,GT_("Query status=2 (SOCKET)\n")); break;
1065                         case PS_AUTHFAIL:
1066                             report(stdout,GT_("Query status=3 (AUTHFAIL)\n"));break;
1067                         case PS_PROTOCOL:
1068                             report(stdout,GT_("Query status=4 (PROTOCOL)\n"));break;
1069                         case PS_SYNTAX:
1070                             report(stdout,GT_("Query status=5 (SYNTAX)\n")); break;
1071                         case PS_IOERR:
1072                             report(stdout,GT_("Query status=6 (IOERR)\n"));  break;
1073                         case PS_ERROR:
1074                             report(stdout,GT_("Query status=7 (ERROR)\n"));  break;
1075                         case PS_EXCLUDE:
1076                             report(stdout,GT_("Query status=8 (EXCLUDE)\n")); break;
1077                         case PS_LOCKBUSY:
1078                             report(stdout,GT_("Query status=9 (LOCKBUSY)\n"));break;
1079                         case PS_SMTP:
1080                             report(stdout,GT_("Query status=10 (SMTP)\n")); break;
1081                         case PS_DNS:
1082                             report(stdout,GT_("Query status=11 (DNS)\n")); break;
1083                         case PS_BSMTP:
1084                             report(stdout,GT_("Query status=12 (BSMTP)\n")); break;
1085                         case PS_MAXFETCH:
1086                             report(stdout,GT_("Query status=13 (MAXFETCH)\n"));break;
1087                         default:
1088                             report(stdout,GT_("Query status=%d\n"),querystatus);
1089                             break;
1090                         }
1091
1092 #ifdef CAN_MONITOR
1093                     if (ctl->server.monitor)
1094                     {
1095                         /*
1096                          * Allow some time for the link to quiesce.  One
1097                          * second is usually sufficient, three is safe.
1098                          * Note:  this delay is important - don't remove!
1099                          */
1100                         sleep(3);
1101                         interface_note_activity(&ctl->server);
1102                     }
1103 #endif /* CAN_MONITOR */
1104                 }
1105             }
1106
1107 #ifdef HAVE_LIBPWMD
1108         if (pwm) {
1109             pwmd_close(pwm);
1110             pwm = NULL;
1111         }
1112 #endif
1113
1114         /* close connections cleanly */
1115         terminate_poll(0);
1116
1117         /*
1118          * OK, we've polled.  Now sleep.
1119          */
1120         if (run.poll_interval)
1121         {
1122             /* 
1123              * Because passwords can expire, it may happen that *all*
1124              * hosts are now out of the loop due to authfail
1125              * conditions.  If this happens daemon-mode fetchmail
1126              * should softly and silently vanish away, rather than
1127              * spinning uselessly.
1128              */
1129             int unwedged = 0;
1130
1131             for (ctl = querylist; ctl; ctl = ctl->next)
1132                 if (ctl->active && !(implicitmode && ctl->server.skip))
1133                     if (!ctl->wedged)
1134                         unwedged++;
1135             if (!unwedged)
1136             {
1137                 report(stderr, GT_("All connections are wedged.  Exiting.\n"));
1138                 /* FIXME: someday, send notification mail */
1139                 exit(PS_AUTHFAIL);
1140             }
1141
1142             if ((outlevel > O_SILENT && !run.use_syslog && isatty(1))
1143                     || outlevel > O_NORMAL)
1144                 report(stdout,
1145                        GT_("sleeping at %s for %d seconds\n"), timestamp(), run.poll_interval);
1146
1147             /*
1148              * With this simple hack, we make it possible for a foreground 
1149              * fetchmail to wake up one in daemon mode.  What we want is the
1150              * side effect of interrupting any sleep that may be going on,
1151              * forcing fetchmail to re-poll its hosts.  The second line is
1152              * for people who think all system daemons wake up on SIGHUP.
1153              */
1154             set_signal_handler(SIGUSR1, donothing);
1155             if (getuid() == ROOT_UID)
1156                 set_signal_handler(SIGHUP, donothing);
1157
1158             /*
1159              * OK, now pause until it's time for the next poll cycle.
1160              * A nonzero return indicates we received a wakeup signal;
1161              * unwedge all servers in case the problem has been
1162              * manually repaired.
1163              */
1164             if ((lastsig = interruptible_idle(run.poll_interval)))
1165             {
1166                 if (outlevel > O_SILENT)
1167 #ifdef SYS_SIGLIST_DECLARED
1168                     report(stdout, 
1169                        GT_("awakened by %s\n"), sys_siglist[lastsig]);
1170 #else
1171                     report(stdout, 
1172                        GT_("awakened by signal %d\n"), lastsig);
1173 #endif
1174                 for (ctl = querylist; ctl; ctl = ctl->next)
1175                     ctl->wedged = FALSE;
1176             }
1177
1178             if ((outlevel > O_SILENT && !run.use_syslog && isatty(1))
1179                     || outlevel > O_NORMAL)
1180                 report(stdout, GT_("awakened at %s\n"), timestamp());
1181         }
1182     } while (run.poll_interval);
1183
1184     if (outlevel >= O_VERBOSE)
1185         report(stdout, GT_("normal termination, status %d\n"),
1186                 successes ? PS_SUCCESS : querystatus);
1187
1188     terminate_run(0);
1189
1190     if (successes)
1191         exit(PS_SUCCESS);
1192     else if (querystatus)
1193         exit(querystatus);
1194     else
1195         /* in case we interrupted before a successful fetch */
1196         exit(PS_NOMAIL);
1197 }
1198
1199 static void list_merge(struct idlist **dstl, struct idlist **srcl, int force)
1200 {
1201     /*
1202      * If force is off, modify dstl fields only when they're empty (treat srcl
1203      * as defaults).  If force is on, modify each dstl field whenever scrcl
1204      * is nonempty (treat srcl as an override).  
1205      */
1206     if (force ? !!*srcl : !*dstl)
1207     {
1208         struct idlist *cpl = copy_str_list(*srcl);
1209
1210         append_str_list(dstl, &cpl);
1211     }
1212 }
1213
1214 static void optmerge(struct query *h2, struct query *h1, int force)
1215 /* merge two options records */
1216 {
1217     list_merge(&h2->server.localdomains, &h1->server.localdomains, force);
1218     list_merge(&h2->localnames, &h1->localnames, force);
1219     list_merge(&h2->mailboxes, &h1->mailboxes, force);
1220     list_merge(&h2->smtphunt, &h1->smtphunt, force);
1221     list_merge(&h2->domainlist, &h1->domainlist, force);
1222     list_merge(&h2->antispam, &h1->antispam, force);
1223
1224 #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld
1225     FLAG_MERGE(server.via);
1226     FLAG_MERGE(server.protocol);
1227     FLAG_MERGE(server.service);
1228     FLAG_MERGE(server.interval);
1229     FLAG_MERGE(server.authenticate);
1230     FLAG_MERGE(server.timeout);
1231     FLAG_MERGE(server.envelope);
1232     FLAG_MERGE(server.envskip);
1233     FLAG_MERGE(server.qvirtual);
1234     FLAG_MERGE(server.skip);
1235     FLAG_MERGE(server.dns);
1236     FLAG_MERGE(server.checkalias);
1237     FLAG_MERGE(server.principal);
1238
1239 #ifdef CAN_MONITOR
1240     FLAG_MERGE(server.interface);
1241     FLAG_MERGE(server.interface_pair);
1242     FLAG_MERGE(server.monitor);
1243 #endif
1244
1245     FLAG_MERGE(server.plugin);
1246     FLAG_MERGE(server.plugout);
1247     FLAG_MERGE(server.tracepolls);
1248     FLAG_MERGE(server.badheader);
1249     FLAG_MERGE(server.retrieveerror);
1250
1251     FLAG_MERGE(wildcard);
1252     FLAG_MERGE(remotename);
1253     FLAG_MERGE(password);
1254     FLAG_MERGE(mda);
1255     FLAG_MERGE(bsmtp);
1256     FLAG_MERGE(listener);
1257     FLAG_MERGE(smtpaddress);
1258     FLAG_MERGE(smtpname);
1259     FLAG_MERGE(preconnect);
1260     FLAG_MERGE(postconnect);
1261
1262     FLAG_MERGE(keep);
1263     FLAG_MERGE(flush);
1264     FLAG_MERGE(limitflush);
1265     FLAG_MERGE(fetchall);
1266     FLAG_MERGE(rewrite);
1267     FLAG_MERGE(forcecr);
1268     FLAG_MERGE(stripcr);
1269     FLAG_MERGE(pass8bits);
1270     FLAG_MERGE(dropstatus);
1271     FLAG_MERGE(dropdelivered);
1272     FLAG_MERGE(mimedecode);
1273     FLAG_MERGE(idle);
1274     FLAG_MERGE(limit);
1275     FLAG_MERGE(warnings);
1276     FLAG_MERGE(fetchlimit);
1277     FLAG_MERGE(fetchsizelimit);
1278     FLAG_MERGE(fastuidl);
1279     FLAG_MERGE(batchlimit);
1280 #ifdef  SSL_ENABLE
1281     FLAG_MERGE(use_ssl);
1282     FLAG_MERGE(sslkey);
1283     FLAG_MERGE(sslcert);
1284     FLAG_MERGE(sslproto);
1285     FLAG_MERGE(sslcertck);
1286     FLAG_MERGE(sslcertfile);
1287     FLAG_MERGE(sslcertpath);
1288     FLAG_MERGE(sslcommonname);
1289     FLAG_MERGE(sslfingerprint);
1290 #endif
1291     FLAG_MERGE(expunge);
1292
1293     FLAG_MERGE(properties);
1294 #undef FLAG_MERGE
1295 }
1296
1297 /** Load configuration files.
1298  * \return - true if no servers found on the command line
1299  *         - false if servers found on the command line */
1300 static int load_params(int argc, char **argv, int optind)
1301 {
1302     int implicitmode, st;
1303     struct passwd *pw;
1304     struct query def_opts, *ctl;
1305     struct stat rcstat;
1306     char *p;
1307
1308     run.bouncemail = TRUE;
1309     run.softbounce = TRUE;      /* treat permanent errors as temporary */
1310     run.spambounce = FALSE;     /* don't bounce back to innocent bystanders */
1311
1312     memset(&def_opts, '\0', sizeof(struct query));
1313     def_opts.smtp_socket = -1;
1314     def_opts.smtpaddress = (char *)0;
1315     def_opts.smtpname = (char *)0;
1316     def_opts.server.protocol = P_AUTO;
1317     def_opts.server.timeout = CLIENT_TIMEOUT;
1318     def_opts.server.esmtp_name = user;
1319     def_opts.server.badheader = BHREJECT;
1320     def_opts.warnings = WARNING_INTERVAL;
1321     def_opts.remotename = user;
1322     def_opts.listener = SMTP_MODE;
1323     def_opts.fetchsizelimit = 100;
1324     def_opts.fastuidl = 4;
1325
1326     /* get the location of rcfile */
1327     rcfiledir[0] = 0;
1328     p = strrchr (rcfile, '/');
1329     if (p && (size_t)(p - rcfile) < sizeof (rcfiledir)) {
1330         *p = 0;                 /* replace '/' by '0' */
1331         strlcpy (rcfiledir, rcfile, sizeof(rcfiledir));
1332         *p = '/';               /* restore '/' */
1333         if (!rcfiledir[0])      /* "/.fetchmailrc" case */
1334             strcpy (rcfiledir, "/");
1335     }
1336
1337     /* note the parse time, so we can pick up on modifications */
1338     if (strcmp(rcfile, "-") == 0)
1339         parsetime = time(NULL);
1340     else {
1341         if (stat(rcfile, &rcstat) != -1)
1342             parsetime = rcstat.st_mtime;
1343         else if (errno != ENOENT)
1344             report(stderr, GT_("couldn't time-check the run-control file\n"));
1345     }
1346
1347     /* this builds the host list */
1348     if ((st = prc_parse_file(rcfile, !versioninfo)) != 0)
1349         /*
1350          * FIXME: someday, send notification mail here if backgrounded.
1351          * Right now, that can happen if the user changes the rcfile
1352          * while the fetchmail is running in background.  Do similarly
1353          * for the other exit() calls in this function.
1354          */
1355         exit(st);
1356
1357     if ((implicitmode = (optind >= argc)))
1358     {
1359 #ifdef HAVE_LIBPWMD
1360         for (ctl = querylist; ctl; ctl = ctl->next) {
1361             ctl->active = !ctl->server.skip;
1362
1363             if (ctl->pwmd_file) {
1364                 /*
1365                  * Cannot get an element path without a service.
1366                  */
1367                 if (ctl->server.protocol <= 1) {
1368                     report(stderr, GT_("fetchmail: %s configuration invalid, pwmd_file requires a protocol specification\n"),
1369                             ctl->server.pollname);
1370                     pwmd_close(pwm);
1371                     exit(PS_SYNTAX);
1372                 }
1373
1374                 if (do_pwmd_connect(ctl->pwmd_socket, ctl->pwmd_file))
1375                     continue;
1376
1377                 if (get_pwmd_details(ctl->server.pollname, ctl->server.protocol,
1378                             ctl))
1379                     continue;
1380
1381                 time(&rcstat.st_mtime);
1382             }
1383         }
1384
1385 #else
1386         for (ctl = querylist; ctl; ctl = ctl->next)
1387             ctl->active = !ctl->server.skip;
1388 #endif
1389     }
1390     else
1391         for (; optind < argc; optind++) 
1392         {
1393             flag        predeclared =  FALSE;
1394
1395             /*
1396              * If hostname corresponds to a host known from the rc file,
1397              * simply declare it active.  Otherwise synthesize a host
1398              * record from command line and defaults
1399              */
1400             for (ctl = querylist; ctl; ctl = ctl->next)
1401                 if (!strcmp(ctl->server.pollname, argv[optind])
1402                         || str_in_list(&ctl->server.akalist, argv[optind], TRUE))
1403                 {
1404                     /* Is this correct? */
1405                     if (predeclared && outlevel >= O_VERBOSE)
1406                         fprintf(stderr,GT_("Warning: multiple mentions of host %s in config file\n"),argv[optind]);
1407                     ctl->active = TRUE;
1408                     predeclared = TRUE;
1409
1410 #ifdef HAVE_LIBPWMD
1411                     if (ctl->pwmd_file) {
1412                         /*
1413                          * Cannot get an element path without a service.
1414                          */
1415                         if (ctl->server.protocol <= 1) {
1416                             report(stderr, GT_("%s configuration invalid, pwmd_file requires a protocol specification\n"),
1417                                    ctl->server.pollname);
1418                             exit(PS_SYNTAX);
1419                         }
1420
1421                         fprintf(stderr, "%s(%i): %s\n", __FILE__, __LINE__, __FUNCTION__);
1422                         if (do_pwmd_connect(ctl->pwmd_socket, ctl->pwmd_file))
1423                             continue;
1424
1425                         if (get_pwmd_details(ctl->server.pollname,
1426                                     ctl->server.protocol, ctl))
1427                             continue;
1428                     }
1429 #endif
1430                 }
1431
1432             if (!predeclared)
1433             {
1434                 /*
1435                  * Allocate and link record without copying in
1436                  * command-line args; we'll do that with the optmerge
1437                  * call later on.
1438                  */
1439                 ctl = hostalloc((struct query *)NULL);
1440
1441 #ifdef HAVE_LIBPWMD
1442                 if (cmd_opts.pwmd_file) {
1443                     /*
1444                      * Cannot get an element path without a service.
1445                      */
1446                     if (cmd_opts.server.protocol == 0 || cmd_opts.server.protocol == 1) {
1447                         report(stderr, GT_("Option --pwmd-file needs a service (-p) parameter.\n"));
1448                         exit(PS_SYNTAX);
1449                     }
1450
1451                         fprintf(stderr, "%s(%i): %s\n", __FILE__, __LINE__, __FUNCTION__);
1452                     if (do_pwmd_connect(cmd_opts.pwmd_socket, cmd_opts.pwmd_file))
1453                         continue;
1454
1455                     if (get_pwmd_details(argv[optind], cmd_opts.server.protocol,
1456                             ctl))
1457                         continue;
1458                 }
1459                 else
1460                     ctl->server.via =
1461                         ctl->server.pollname = xstrdup(argv[optind]);
1462 #else
1463                 ctl->server.via =
1464                     ctl->server.pollname = xstrdup(argv[optind]);
1465 #endif
1466                 ctl->active = TRUE;
1467                 ctl->server.lead_server = (struct hostdata *)NULL;
1468             }
1469         }
1470
1471     /*
1472      * If there's a defaults record, merge it and lose it.
1473      * FIXME: we don't currently free all entries that might be in struct query.
1474      */ 
1475     if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
1476     {
1477         struct query *tmpq;
1478
1479         for (ctl = querylist->next; ctl; ctl = ctl->next)
1480             optmerge(ctl, querylist, FALSE);
1481         tmpq = querylist;
1482         querylist = querylist->next;
1483         free(tmpq->server.pollname);
1484         free(tmpq);
1485     }
1486
1487     /* don't allow a defaults record after the first */
1488     for (ctl = querylist; ctl; ctl = ctl->next) {
1489         if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0) {
1490             fprintf(stderr, GT_("fetchmail: Error: multiple \"defaults\" records in config file.\n"));
1491             exit(PS_SYNTAX);
1492         }
1493     }
1494
1495     /* use localhost if we never fetch the FQDN of this host */
1496     fetchmailhost = "localhost";
1497
1498     /* here's where we override globals */
1499     if (cmd_run.logfile)
1500         run.logfile = cmd_run.logfile;
1501     if (cmd_run.idfile)
1502         run.idfile = cmd_run.idfile;
1503     if (cmd_run.pidfile)
1504         run.pidfile = cmd_run.pidfile;
1505     /* do this before the keep/fetchall test below, otherwise -d0 may fail */
1506     if (cmd_run.poll_interval >= 0)
1507         run.poll_interval = cmd_run.poll_interval;
1508     if (cmd_run.invisible)
1509         run.invisible = (cmd_run.invisible == FLAG_TRUE);
1510     if (cmd_run.showdots)
1511         run.showdots = (cmd_run.showdots == FLAG_TRUE);
1512     if (cmd_run.use_syslog)
1513         run.use_syslog = (cmd_run.use_syslog == FLAG_TRUE);
1514     if (cmd_run.postmaster)
1515         run.postmaster = cmd_run.postmaster;
1516     if (cmd_run.bouncemail)
1517         run.bouncemail = (cmd_run.bouncemail == FLAG_TRUE);
1518     if (cmd_run.softbounce)
1519         run.softbounce = (cmd_run.softbounce == FLAG_TRUE);
1520
1521     /* check and daemon options are not compatible */
1522     if (check_only && run.poll_interval)
1523         run.poll_interval = 0;
1524
1525     /*
1526      * DNS support is required for some protocols.  We used to
1527      * do this unconditionally, but it made fetchmail excessively
1528      * vulnerable to misconfigured DNS setups.
1529      *
1530      * If we're using ETRN or ODMR, the smtp hunt list is the
1531      * list of systems we're polling on behalf of; these have
1532      * to be fully-qualified domain names.  The default for
1533      * this list should be the FQDN of localhost.
1534      *
1535      * If we're using Kerberos for authentication, we need 
1536      * the FQDN in order to generate capability keys.
1537      */
1538     for (ctl = querylist; ctl; ctl = ctl->next)
1539         if (ctl->active && 
1540                 (ctl->server.protocol==P_ETRN || ctl->server.protocol==P_ODMR
1541                  || ctl->server.authenticate == A_KERBEROS_V5))
1542         {
1543             fetchmailhost = host_fqdn(1);
1544             break;
1545         }
1546
1547     if (!ctl) /* list exhausted */
1548         fetchmailhost = host_fqdn(0);
1549
1550     /* this code enables flags to be turned off */
1551 #define DEFAULT(flag, dflt)     if (flag == FLAG_TRUE)\
1552                                         flag = TRUE;\
1553                                 else if (flag == FLAG_FALSE)\
1554                                         flag = FALSE;\
1555                                 else\
1556                                         flag = (dflt)
1557
1558     /* merge in wired defaults, do sanity checks and prepare internal fields */
1559     for (ctl = querylist; ctl; ctl = ctl->next)
1560     {
1561         ctl->wedged = FALSE;
1562
1563         /* merge in defaults */
1564         optmerge(ctl, &def_opts, FALSE);
1565
1566         /* force command-line options */
1567         optmerge(ctl, &cmd_opts, TRUE);
1568
1569         /*
1570          * queryname has to be set up for inactive servers too.  
1571          * Otherwise the UIDL code core-dumps on startup.
1572          */
1573         if (ctl->server.via) 
1574             ctl->server.queryname = xstrdup(ctl->server.via);
1575         else
1576             ctl->server.queryname = xstrdup(ctl->server.pollname);
1577
1578         /*
1579          * We no longer do DNS lookups at startup.
1580          * This is a kluge.  It enables users to edit their
1581          * configurations when DNS isn't available.
1582          */
1583         ctl->server.truename = xstrdup(ctl->server.queryname);
1584
1585         if (configdump || ctl->active )
1586         {
1587             DEFAULT(ctl->keep, FALSE);
1588             DEFAULT(ctl->fetchall, FALSE);
1589             DEFAULT(ctl->flush, FALSE);
1590             DEFAULT(ctl->limitflush, FALSE);
1591             DEFAULT(ctl->rewrite, TRUE);
1592             DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL)); 
1593             DEFAULT(ctl->forcecr, FALSE);
1594             DEFAULT(ctl->pass8bits, FALSE);
1595             DEFAULT(ctl->dropstatus, FALSE);
1596             DEFAULT(ctl->dropdelivered, FALSE);
1597             DEFAULT(ctl->mimedecode, FALSE);
1598             DEFAULT(ctl->idle, FALSE);
1599             DEFAULT(ctl->server.dns, TRUE);
1600             DEFAULT(ctl->use_ssl, FALSE);
1601             DEFAULT(ctl->sslcertck, FALSE);
1602             DEFAULT(ctl->server.checkalias, FALSE);
1603 #ifndef SSL_ENABLE
1604             /*
1605              * XXX FIXME: do we need this check or can we rely on the .y
1606              * parser handling this?
1607              */
1608             if (ctl->use_ssl) 
1609             {
1610                 report(stderr, GT_("SSL support is not compiled in.\n"));
1611                 exit(PS_SYNTAX);
1612             }
1613 #endif /* SSL_ENABLE */
1614 #undef DEFAULT
1615 #ifndef KERBEROS_V5
1616             if (ctl->server.authenticate == A_KERBEROS_V5) {
1617                 report(stderr, GT_("KERBEROS v5 support is configured, but not compiled in.\n"));
1618                 exit(PS_SYNTAX);
1619             }
1620 #endif
1621 #ifndef GSSAPI
1622             if (ctl->server.authenticate == A_GSSAPI) {
1623                 report(stderr, GT_("GSSAPI support is configured, but not compiled in.\n"));
1624                 exit(PS_SYNTAX);
1625             }
1626 #endif
1627
1628             /*
1629              * Make sure we have a nonempty host list to forward to.
1630              */
1631             if (!ctl->smtphunt)
1632                 save_str(&ctl->smtphunt, "localhost", FALSE);
1633
1634             /*
1635              * Make sure we have a nonempty list of domains to fetch from.
1636              */
1637             if ((ctl->server.protocol==P_ETRN || ctl->server.protocol==P_ODMR) && !ctl->domainlist)
1638                 save_str(&ctl->domainlist, fetchmailhost, FALSE);
1639
1640             /* if `user' doesn't name a real local user, try to run as root */
1641             if ((pw = getpwnam(user)) == (struct passwd *)NULL)
1642                 ctl->uid = 0;
1643             else
1644                 ctl->uid = pw->pw_uid;  /* for local delivery via MDA */
1645             if (!ctl->localnames)       /* for local delivery via SMTP */
1646                 save_str_pair(&ctl->localnames, user, NULL);
1647
1648             /*
1649              * can't handle multidrop mailboxes without "envelope"
1650              * option, this causes truckloads full of support complaints
1651              * "all mail forwarded to postmaster"
1652              */
1653             if (MULTIDROP(ctl) && !ctl->server.envelope)
1654             {
1655                 report(stderr, GT_("warning: multidrop for %s requires envelope option!\n"), ctl->server.pollname);
1656                 report(stderr, GT_("warning: Do not ask for support if all mail goes to postmaster!\n"));
1657             }
1658
1659             /* if no folders were specified, set up the null one as default */
1660             if (!ctl->mailboxes)
1661                 save_str(&ctl->mailboxes, (char *)NULL, 0);
1662
1663             /* maybe user overrode timeout on command line? */
1664             if (ctl->server.timeout == -1)
1665                 ctl->server.timeout = CLIENT_TIMEOUT;
1666
1667             /* sanity checks */
1668             if (ctl->server.service) {
1669                 int port = servport(ctl->server.service);
1670                 if (port < 0)
1671                 {
1672                     (void) fprintf(stderr,
1673                                    GT_("fetchmail: %s configuration invalid, specify positive port number for service or port\n"),
1674                                    ctl->server.pollname);
1675                     exit(PS_SYNTAX);
1676                 }
1677             }
1678             if (ctl->listener == LMTP_MODE)
1679             {
1680                 struct idlist   *idp;
1681
1682                 for (idp = ctl->smtphunt; idp; idp = idp->next)
1683                 {
1684                     char        *cp;
1685
1686                     if (!(cp = strrchr(idp->id, '/'))
1687                         || (0 == strcmp(cp + 1, SMTP_PORT))
1688                         || servport(cp + 1) == SMTP_PORT_NUM)
1689                     {
1690                         (void) fprintf(stderr,
1691                                        GT_("%s configuration invalid, LMTP can't use default SMTP port\n"),
1692                                        ctl->server.pollname);
1693                         exit(PS_SYNTAX);
1694                     }
1695                 }
1696             }
1697
1698             /*
1699              * "I beg to you, have mercy on the we[a]k minds like myself."
1700              * wrote Pehr Anderson.  Your petition is granted.
1701              */
1702             if (ctl->fetchall && ctl->keep && (run.poll_interval || ctl->idle) && !nodetach && !configdump)
1703             {
1704                 (void) fprintf(stderr,
1705                                GT_("Both fetchall and keep on in daemon or idle mode is a mistake!\n"));
1706             }
1707         }
1708     }
1709
1710     /*
1711      * If the user didn't set a last-resort user to get misaddressed
1712      * multidrop mail, set an appropriate default here.
1713      */
1714     if (!run.postmaster)
1715     {
1716         if (getuid() != ROOT_UID)               /* ordinary user */
1717             run.postmaster = user;
1718         else                                    /* root */
1719             run.postmaster = "postmaster";
1720     }
1721
1722     return(implicitmode);
1723 }
1724
1725 static void terminate_poll(int sig)
1726 /* to be executed at the end of a poll cycle */
1727 {
1728
1729     if (sig != 0)
1730         report(stdout, GT_("terminated with signal %d\n"), sig);
1731
1732 #ifdef POP3_ENABLE
1733     /*
1734      * Update UID information at end of each poll, rather than at end
1735      * of run, because that way we don't lose all UIDL information since
1736      * the beginning of time if fetchmail crashes.
1737      */
1738     if (!check_only)
1739         write_saved_lists(querylist, run.idfile);
1740 #endif /* POP3_ENABLE */
1741 }
1742
1743 static void terminate_run(int sig)
1744 /* to be executed on normal or signal-induced termination */
1745 {
1746     struct query        *ctl;
1747
1748     terminate_poll(sig);
1749
1750     /* 
1751      * Craig Metz, the RFC1938 one-time-password guy, points out:
1752      * "Remember that most kernels don't zero pages before handing them to the
1753      * next process and many kernels share pages between user and kernel space.
1754      * You'd be very surprised what you can find from a short program to do a
1755      * malloc() and then dump the contents of the pages you got. By zeroing
1756      * the secrets at end of run (earlier if you can), you make sure the next
1757      * guy can't get the password/pass phrase."
1758      *
1759      * Right you are, Craig!
1760      */
1761     for (ctl = querylist; ctl; ctl = ctl->next)
1762         if (ctl->password)
1763           memset(ctl->password, '\0', strlen(ctl->password));
1764
1765     if (activecount == 0)
1766         exit(PS_NOMAIL);
1767     else
1768         exit(successes ? PS_SUCCESS : querystatus);
1769 }
1770
1771 /*
1772  * Sequence of protocols to try when autoprobing, most capable to least.
1773  */
1774 static const int autoprobe[] = 
1775 {
1776 #ifdef IMAP_ENABLE
1777     P_IMAP,
1778 #endif /* IMAP_ENABLE */
1779 #ifdef POP3_ENABLE
1780     P_POP3,
1781 #endif /* POP3_ENABLE */
1782 };
1783
1784 static int query_host(struct query *ctl)
1785 /* perform fetch transaction with single host */
1786 {
1787     size_t i;
1788     int st = 0;
1789
1790     /*
1791      * If we're syslogging the progress messages are automatically timestamped.
1792      * Force timestamping if we're going to a logfile.
1793      */
1794     if (outlevel >= O_VERBOSE)
1795     {
1796         report(stdout, GT_("%s querying %s (protocol %s) at %s: poll started\n"),
1797                VERSION,
1798                ctl->server.pollname,
1799                showproto(ctl->server.protocol),
1800                timestamp());
1801     }
1802
1803     switch (ctl->server.protocol) {
1804     case P_AUTO:
1805         for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
1806         {
1807             ctl->server.protocol = autoprobe[i];
1808             do {
1809                 st = query_host(ctl);
1810             } while 
1811                 (st == PS_REPOLL);
1812             if (st == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP || st == PS_MAXFETCH || st == PS_DNS)
1813                 break;
1814         }
1815         ctl->server.protocol = P_AUTO;
1816         break;
1817     case P_POP3:
1818 #ifdef POP3_ENABLE
1819         do {
1820             st = doPOP3(ctl);
1821         } while (st == PS_REPOLL);
1822 #else
1823         report(stderr, GT_("POP3 support is not configured.\n"));
1824         st = PS_PROTOCOL;
1825 #endif /* POP3_ENABLE */
1826         break;
1827     case P_IMAP:
1828 #ifdef IMAP_ENABLE
1829         do {
1830             st = doIMAP(ctl);
1831         } while (st == PS_REPOLL);
1832 #else
1833         report(stderr, GT_("IMAP support is not configured.\n"));
1834         st = PS_PROTOCOL;
1835 #endif /* IMAP_ENABLE */
1836         break;
1837     case P_ETRN:
1838 #ifndef ETRN_ENABLE
1839         report(stderr, GT_("ETRN support is not configured.\n"));
1840         st = PS_PROTOCOL;
1841 #else
1842         st = doETRN(ctl);
1843         break;
1844 #endif /* ETRN_ENABLE */
1845     case P_ODMR:
1846 #ifndef ODMR_ENABLE
1847         report(stderr, GT_("ODMR support is not configured.\n"));
1848         st = PS_PROTOCOL;
1849 #else
1850         st = doODMR(ctl);
1851 #endif /* ODMR_ENABLE */
1852         break;
1853     default:
1854         report(stderr, GT_("unsupported protocol selected.\n"));
1855         st = PS_PROTOCOL;
1856     }
1857
1858     /*
1859      * If we're syslogging the progress messages are automatically timestamped.
1860      * Force timestamping if we're going to a logfile.
1861      */
1862     if (outlevel >= O_VERBOSE)
1863     {
1864         report(stdout, GT_("%s querying %s (protocol %s) at %s: poll completed\n"),
1865                VERSION,
1866                ctl->server.pollname,
1867                showproto(ctl->server.protocol),
1868                timestamp());
1869     }
1870
1871     return(st);
1872 }
1873
1874 static int print_id_of(struct uid_db_record *rec, void *unused)
1875 {
1876     (void)unused;
1877
1878     printf("\t%s\n", rec->id);
1879     return 0;
1880 }
1881
1882 static void dump_params (struct runctl *runp,
1883                          struct query *querylist, flag implicit)
1884 /* display query parameters in English */
1885 {
1886     struct query *ctl;
1887
1888     if (runp->poll_interval)
1889         printf(GT_("Poll interval is %d seconds\n"), runp->poll_interval);
1890     if (runp->logfile)
1891         printf(GT_("Logfile is %s\n"), runp->logfile);
1892     if (strcmp(runp->idfile, IDFILE_NAME))
1893         printf(GT_("Idfile is %s\n"), runp->idfile);
1894     if (runp->use_syslog)
1895         printf(GT_("Progress messages will be logged via syslog\n"));
1896     if (runp->invisible)
1897         printf(GT_("Fetchmail will masquerade and will not generate Received\n"));
1898     if (runp->showdots)
1899         printf(GT_("Fetchmail will show progress dots even in logfiles.\n"));
1900     if (runp->postmaster)
1901         printf(GT_("Fetchmail will forward misaddressed multidrop messages to %s.\n"),
1902                runp->postmaster);
1903
1904     if (!runp->bouncemail)
1905         printf(GT_("Fetchmail will direct error mail to the postmaster.\n"));
1906     else if (outlevel >= O_VERBOSE)
1907         printf(GT_("Fetchmail will direct error mail to the sender.\n"));
1908
1909     if (!runp->softbounce)
1910         printf(GT_("Fetchmail will treat permanent errors as permanent (drop messages).\n"));
1911     else if (outlevel >= O_VERBOSE)
1912         printf(GT_("Fetchmail will treat permanent errors as temporary (keep messages).\n"));
1913
1914     for (ctl = querylist; ctl; ctl = ctl->next)
1915     {
1916         if (!ctl->active || (implicit && ctl->server.skip))
1917             continue;
1918
1919         printf(GT_("Options for retrieving from %s@%s:\n"),
1920                ctl->remotename, visbuf(ctl->server.pollname));
1921
1922         if (ctl->server.via && MAILBOX_PROTOCOL(ctl))
1923             printf(GT_("  Mail will be retrieved via %s\n"), ctl->server.via);
1924
1925         if (ctl->server.interval)
1926             printf(ngettext("  Poll of this server will occur every %d interval.\n",
1927                             "  Poll of this server will occur every %d intervals.\n",
1928                             ctl->server.interval), ctl->server.interval);
1929         if (ctl->server.truename)
1930             printf(GT_("  True name of server is %s.\n"), ctl->server.truename);
1931         if (ctl->server.skip || outlevel >= O_VERBOSE)
1932             printf(ctl->server.skip
1933                    ? GT_("  This host will not be queried when no host is specified.\n")
1934                    : GT_("  This host will be queried when no host is specified.\n"));
1935         if (!NO_PASSWORD(ctl))
1936         {
1937             if (!ctl->password)
1938                 printf(GT_("  Password will be prompted for.\n"));
1939             else if (outlevel >= O_VERBOSE)
1940             {
1941                 printf(GT_("  Password = \"%s\".\n"),
1942                                     visbuf(ctl->password));
1943             }
1944         }
1945
1946         if (ctl->server.protocol == P_POP3 
1947             && ctl->server.service && !strcmp(ctl->server.service, KPOP_PORT)
1948             && (ctl->server.authenticate == A_KERBEROS_V5))
1949             printf(GT_("  Protocol is KPOP with Kerberos %s authentication"),
1950                    ctl->server.authenticate == A_KERBEROS_V5 ? "V" : "IV");
1951         else
1952             printf(GT_("  Protocol is %s"), showproto(ctl->server.protocol));
1953         if (ctl->server.service)
1954             printf(GT_(" (using service %s)"), ctl->server.service);
1955         else if (outlevel >= O_VERBOSE)
1956             printf(GT_(" (using default port)"));
1957         putchar('.');
1958         putchar('\n');
1959         switch (ctl->server.authenticate)
1960         {
1961         case A_ANY:
1962             printf(GT_("  All available authentication methods will be tried.\n"));
1963             break;
1964         case A_PASSWORD:
1965             printf(GT_("  Password authentication will be forced.\n"));
1966             break;
1967         case A_MSN:
1968             printf(GT_("  MSN authentication will be forced.\n"));
1969             break;
1970         case A_NTLM:
1971             printf(GT_("  NTLM authentication will be forced.\n"));
1972             break;
1973         case A_OTP:
1974             printf(GT_("  OTP authentication will be forced.\n"));
1975             break;
1976         case A_CRAM_MD5:
1977             printf(GT_("  CRAM-MD5 authentication will be forced.\n"));
1978             break;
1979         case A_GSSAPI:
1980             printf(GT_("  GSSAPI authentication will be forced.\n"));
1981             break;
1982         case A_KERBEROS_V5:
1983             printf(GT_("  Kerberos V5 authentication will be forced.\n"));
1984             break;
1985         case A_SSH:
1986             printf(GT_("  End-to-end encryption assumed.\n"));
1987             break;
1988         case A_APOP:
1989             printf(GT_("  APOP authentication will be forced.\n"));
1990             break;
1991         default:
1992             abort();
1993         }
1994         if (ctl->server.principal != (char *) NULL)
1995             printf(GT_("  Mail service principal is: %s\n"), ctl->server.principal);
1996 #ifdef  SSL_ENABLE
1997         if (ctl->use_ssl)
1998             printf(GT_("  SSL encrypted sessions enabled.\n"));
1999         if (ctl->sslproto)
2000             printf(GT_("  SSL protocol: %s.\n"), ctl->sslproto);
2001         if (ctl->sslcertck) {
2002             printf(GT_("  SSL server certificate checking enabled.\n"));
2003         }
2004         if (ctl->sslcertfile != NULL)
2005                 printf(GT_("  SSL trusted certificate file: %s\n"), ctl->sslcertfile);
2006         if (ctl->sslcertpath != NULL)
2007                 printf(GT_("  SSL trusted certificate directory: %s\n"), ctl->sslcertpath);
2008         if (ctl->sslcommonname != NULL)
2009                 printf(GT_("  SSL server CommonName: %s\n"), ctl->sslcommonname);
2010         if (ctl->sslfingerprint != NULL)
2011                 printf(GT_("  SSL key fingerprint (checked against the server key): %s\n"), ctl->sslfingerprint);
2012 #endif
2013         if (ctl->server.timeout > 0)
2014             printf(GT_("  Server nonresponse timeout is %d seconds"), ctl->server.timeout);
2015         if (ctl->server.timeout ==  CLIENT_TIMEOUT)
2016             printf(GT_(" (default).\n"));
2017         else
2018             printf(".\n");
2019
2020         if (MAILBOX_PROTOCOL(ctl)) 
2021         {
2022             if (!ctl->mailboxes->id)
2023                 printf(GT_("  Default mailbox selected.\n"));
2024             else
2025             {
2026                 struct idlist *idp;
2027
2028                 printf(GT_("  Selected mailboxes are:"));
2029                 for (idp = ctl->mailboxes; idp; idp = idp->next)
2030                     printf(" %s", idp->id);
2031                 printf("\n");
2032             }
2033             printf(ctl->fetchall
2034                    ? GT_("  All messages will be retrieved (--all on).\n")
2035                    : GT_("  Only new messages will be retrieved (--all off).\n"));
2036             printf(ctl->keep
2037                    ? GT_("  Fetched messages will be kept on the server (--keep on).\n")
2038                    : GT_("  Fetched messages will not be kept on the server (--keep off).\n"));
2039             printf(ctl->flush
2040                    ? GT_("  Old messages will be flushed before message retrieval (--flush on).\n")
2041                    : GT_("  Old messages will not be flushed before message retrieval (--flush off).\n"));
2042             printf(ctl->limitflush
2043                    ? GT_("  Oversized messages will be flushed before message retrieval (--limitflush on).\n")
2044                    : GT_("  Oversized messages will not be flushed before message retrieval (--limitflush off).\n"));
2045             printf(ctl->rewrite
2046                    ? GT_("  Rewrite of server-local addresses is enabled (--norewrite off).\n")
2047                    : GT_("  Rewrite of server-local addresses is disabled (--norewrite on).\n"));
2048             printf(ctl->stripcr
2049                    ? GT_("  Carriage-return stripping is enabled (stripcr on).\n")
2050                    : GT_("  Carriage-return stripping is disabled (stripcr off).\n"));
2051             printf(ctl->forcecr
2052                    ? GT_("  Carriage-return forcing is enabled (forcecr on).\n")
2053                    : GT_("  Carriage-return forcing is disabled (forcecr off).\n"));
2054             printf(ctl->pass8bits
2055                    ? GT_("  Interpretation of Content-Transfer-Encoding is disabled (pass8bits on).\n")
2056                    : GT_("  Interpretation of Content-Transfer-Encoding is enabled (pass8bits off).\n"));
2057             printf(ctl->mimedecode
2058                    ? GT_("  MIME decoding is enabled (mimedecode on).\n")
2059                    : GT_("  MIME decoding is disabled (mimedecode off).\n"));
2060             printf(ctl->idle
2061                    ? GT_("  Idle after poll is enabled (idle on).\n")
2062                    : GT_("  Idle after poll is disabled (idle off).\n"));
2063             printf(ctl->dropstatus
2064                    ? GT_("  Nonempty Status lines will be discarded (dropstatus on)\n")
2065                    : GT_("  Nonempty Status lines will be kept (dropstatus off)\n"));
2066             printf(ctl->dropdelivered
2067                    ? GT_("  Delivered-To lines will be discarded (dropdelivered on)\n")
2068                    : GT_("  Delivered-To lines will be kept (dropdelivered off)\n"));
2069             if (NUM_NONZERO(ctl->limit))
2070             {
2071                 if (NUM_NONZERO(ctl->limit))
2072                     printf(GT_("  Message size limit is %d octets (--limit %d).\n"), 
2073                            ctl->limit, ctl->limit);
2074                 else if (outlevel >= O_VERBOSE)
2075                     printf(GT_("  No message size limit (--limit 0).\n"));
2076                 if (run.poll_interval > 0)
2077                     printf(GT_("  Message size warning interval is %d seconds (--warnings %d).\n"), 
2078                            ctl->warnings, ctl->warnings);
2079                 else if (outlevel >= O_VERBOSE)
2080                     printf(GT_("  Size warnings on every poll (--warnings 0).\n"));
2081             }
2082             if (NUM_NONZERO(ctl->fetchlimit))
2083                 printf(GT_("  Received-message limit is %d (--fetchlimit %d).\n"),
2084                        ctl->fetchlimit, ctl->fetchlimit);
2085             else if (outlevel >= O_VERBOSE)
2086                 printf(GT_("  No received-message limit (--fetchlimit 0).\n"));
2087             if (NUM_NONZERO(ctl->fetchsizelimit))
2088                 printf(GT_("  Fetch message size limit is %d (--fetchsizelimit %d).\n"),
2089                        ctl->fetchsizelimit, ctl->fetchsizelimit);
2090             else if (outlevel >= O_VERBOSE)
2091                 printf(GT_("  No fetch message size limit (--fetchsizelimit 0).\n"));
2092             if (NUM_NONZERO(ctl->fastuidl) && MAILBOX_PROTOCOL(ctl))
2093             {
2094                 if (ctl->fastuidl == 1)
2095                     printf(GT_("  Do binary search of UIDs during each poll (--fastuidl 1).\n"));
2096                 else
2097                     printf(GT_("  Do binary search of UIDs during %d out of %d polls (--fastuidl %d).\n"), ctl->fastuidl - 1, ctl->fastuidl, ctl->fastuidl);
2098             }
2099             else if (outlevel >= O_VERBOSE)
2100                 printf(GT_("   Do linear search of UIDs during each poll (--fastuidl 0).\n"));
2101             if (NUM_NONZERO(ctl->batchlimit))
2102                 printf(GT_("  SMTP message batch limit is %d.\n"), ctl->batchlimit);
2103             else if (outlevel >= O_VERBOSE)
2104                 printf(GT_("  No SMTP message batch limit (--batchlimit 0).\n"));
2105             if (MAILBOX_PROTOCOL(ctl))
2106             {
2107                 if (NUM_NONZERO(ctl->expunge))
2108                     printf(GT_("  Deletion interval between expunges forced to %d (--expunge %d).\n"), ctl->expunge, ctl->expunge);
2109                 else if (outlevel >= O_VERBOSE)
2110                     printf(GT_("  No forced expunges (--expunge 0).\n"));
2111             }
2112         }
2113         else    /* ODMR or ETRN */
2114         {
2115             struct idlist *idp;
2116
2117             printf(GT_("  Domains for which mail will be fetched are:"));
2118             for (idp = ctl->domainlist; idp; idp = idp->next)
2119             {
2120                 printf(" %s", idp->id);
2121                 if (!idp->val.status.mark)
2122                     printf(GT_(" (default)"));
2123             }
2124             printf("\n");
2125         }
2126         if (ctl->bsmtp)
2127             printf(GT_("  Messages will be appended to %s as BSMTP\n"), visbuf(ctl->bsmtp));
2128         else if (ctl->mda && MAILBOX_PROTOCOL(ctl))
2129             printf(GT_("  Messages will be delivered with \"%s\".\n"), visbuf(ctl->mda));
2130         else
2131         {
2132             struct idlist *idp;
2133
2134             if (ctl->smtphunt)
2135             {
2136                 printf(GT_("  Messages will be %cMTP-forwarded to:"), 
2137                        ctl->listener);
2138                 for (idp = ctl->smtphunt; idp; idp = idp->next)
2139                 {
2140                     printf(" %s", idp->id);
2141                     if (!idp->val.status.mark)
2142                         printf(GT_(" (default)"));
2143                 }
2144                 printf("\n");
2145             }
2146             if (ctl->smtpaddress)
2147                 printf(GT_("  Host part of MAIL FROM line will be %s\n"),
2148                        ctl->smtpaddress);
2149             if (ctl->smtpname)
2150                 printf(GT_("  Address to be put in RCPT TO lines shipped to SMTP will be %s\n"),
2151                        ctl->smtpname);
2152         }
2153         if (MAILBOX_PROTOCOL(ctl))
2154         {
2155                 if (ctl->antispam != (struct idlist *)NULL)
2156                 {
2157                     struct idlist *idp;
2158
2159                     printf(GT_("  Recognized listener spam block responses are:"));
2160                     for (idp = ctl->antispam; idp; idp = idp->next)
2161                         printf(" %d", idp->val.status.num);
2162                     printf("\n");
2163                 }
2164                 else if (outlevel >= O_VERBOSE)
2165                     printf(GT_("  Spam-blocking disabled\n"));
2166         }
2167         if (ctl->preconnect)
2168             printf(GT_("  Server connection will be brought up with \"%s\".\n"),
2169                    visbuf(ctl->preconnect));
2170         else if (outlevel >= O_VERBOSE)
2171             printf(GT_("  No pre-connection command.\n"));
2172         if (ctl->postconnect)
2173             printf(GT_("  Server connection will be taken down with \"%s\".\n"),
2174                    visbuf(ctl->postconnect));
2175         else if (outlevel >= O_VERBOSE)
2176             printf(GT_("  No post-connection command.\n"));
2177         if (MAILBOX_PROTOCOL(ctl)) {
2178                 if (!ctl->localnames)
2179                     printf(GT_("  No localnames declared for this host.\n"));
2180                 else
2181                 {
2182                     struct idlist *idp;
2183                     int count = 0;
2184
2185                     for (idp = ctl->localnames; idp; idp = idp->next)
2186                         ++count;
2187
2188                     if (count > 1 || ctl->wildcard)
2189                         printf(GT_("  Multi-drop mode: "));
2190                     else
2191                         printf(GT_("  Single-drop mode: "));
2192
2193                     printf(ngettext("%d local name recognized.\n", "%d local names recognized.\n", count), count);
2194                     if (outlevel >= O_VERBOSE)
2195                     {
2196                         for (idp = ctl->localnames; idp; idp = idp->next)
2197                             if (idp->val.id2)
2198                                 printf("\t%s -> %s\n", idp->id, idp->val.id2);
2199                             else
2200                                 printf("\t%s\n", idp->id);
2201                         if (ctl->wildcard)
2202                             fputs("\t*\n", stdout);
2203                     }
2204
2205                     if (count > 1 || ctl->wildcard)
2206                     {
2207                         printf(ctl->server.dns
2208                                ? GT_("  DNS lookup for multidrop addresses is enabled.\n")
2209                                : GT_("  DNS lookup for multidrop addresses is disabled.\n"));
2210                         if (ctl->server.dns)
2211                         {
2212                             if (ctl->server.checkalias)
2213                                 printf(GT_("  Server aliases will be compared with multidrop addresses by IP address.\n"));
2214                             else
2215                                 printf(GT_("  Server aliases will be compared with multidrop addresses by name.\n"));
2216                         }
2217                         if (ctl->server.envelope == STRING_DISABLED)
2218                             printf(GT_("  Envelope-address routing is disabled\n"));
2219                         else
2220                         {
2221                             printf(GT_("  Envelope header is assumed to be: %s\n"),
2222                                    ctl->server.envelope ? ctl->server.envelope : "Received");
2223                             if (ctl->server.envskip || outlevel >= O_VERBOSE)
2224                                 printf(GT_("  Number of envelope headers to be skipped over: %d\n"),
2225                                        ctl->server.envskip);
2226                             if (ctl->server.qvirtual)
2227                                 printf(GT_("  Prefix %s will be removed from user id\n"),
2228                                        ctl->server.qvirtual);
2229                             else if (outlevel >= O_VERBOSE) 
2230                                 printf(GT_("  No prefix stripping\n"));
2231                         }
2232
2233                         if (ctl->server.akalist)
2234                         {
2235                             printf(GT_("  Predeclared mailserver aliases:"));
2236                             for (idp = ctl->server.akalist; idp; idp = idp->next)
2237                                 printf(" %s", idp->id);
2238                             putchar('\n');
2239                         }
2240
2241                         if (ctl->server.localdomains)
2242                         {
2243                             printf(GT_("  Local domains:"));
2244                             for (idp = ctl->server.localdomains; idp; idp = idp->next)
2245                                 printf(" %s", idp->id);
2246                             putchar('\n');
2247                         }
2248                     }
2249                 }
2250         }
2251 #ifdef CAN_MONITOR
2252         if (ctl->server.interface)
2253             printf(GT_("  Connection must be through interface %s.\n"), ctl->server.interface);
2254         else if (outlevel >= O_VERBOSE)
2255             printf(GT_("  No interface requirement specified.\n"));
2256         if (ctl->server.monitor)
2257             printf(GT_("  Polling loop will monitor %s.\n"), ctl->server.monitor);
2258         else if (outlevel >= O_VERBOSE)
2259             printf(GT_("  No monitor interface specified.\n"));
2260 #endif
2261
2262         if (ctl->server.plugin)
2263             printf(GT_("  Server connections will be made via plugin %s (--plugin %s).\n"), ctl->server.plugin, ctl->server.plugin);
2264         else if (outlevel >= O_VERBOSE)
2265             printf(GT_("  No plugin command specified.\n"));
2266         if (ctl->server.plugout)
2267             printf(GT_("  Listener connections will be made via plugout %s (--plugout %s).\n"), ctl->server.plugout, ctl->server.plugout);
2268         else if (outlevel >= O_VERBOSE)
2269             printf(GT_("  No plugout command specified.\n"));
2270
2271         if (MAILBOX_PROTOCOL(ctl))
2272         {
2273             int count;
2274
2275             if (!(count = uid_db_n_records(&ctl->oldsaved)))
2276                 printf(GT_("  No UIDs saved from this host.\n"));
2277             else
2278             {
2279                 printf(GT_("  %d UIDs saved.\n"), count);
2280                 traverse_uid_db(&ctl->oldsaved, print_id_of, NULL);
2281             }
2282         }
2283
2284         if (ctl->server.tracepolls)
2285             printf(GT_("  Poll trace information will be added to the Received header.\n"));
2286         else if (outlevel >= O_VERBOSE)
2287             printf(GT_("  No poll trace information will be added to the Received header.\n"));
2288
2289         switch (ctl->server.badheader) {
2290             case BHREJECT:
2291                 if (outlevel >= O_VERBOSE)
2292                     printf(GT_("  Messages with bad headers will be rejected.\n"));
2293                 break;
2294             case BHACCEPT:
2295                 printf(GT_("  Messages with bad headers will be passed on.\n"));
2296                 break;
2297         }
2298
2299         switch (ctl->server.retrieveerror) {
2300             case RE_ABORT:
2301                 if (outlevel >= O_VERBOSE)
2302                     printf(GT_("  Messages with fetch body errors will cause the session to abort.\n"));
2303                 break;
2304             case RE_CONTINUE:
2305                 printf(GT_("  Messages with fetch body errors will be skipped, the session will continue.\n"));
2306                 break;
2307             case RE_MARKSEEN:
2308                 printf(GT_("  Messages with fetch body errors will be marked seen, the session will continue.\n"));
2309                 break;
2310         }
2311
2312         if (ctl->properties)
2313             printf(GT_("  Pass-through properties \"%s\".\n"),
2314                    visbuf(ctl->properties));
2315     }
2316 }
2317
2318 /* fetchmail.c ends here */