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