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