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