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