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