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