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