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