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