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