]> Pileus Git - ~andy/fetchmail/blob - fetchmail.c
Better behavior in absence of bind library.
[~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
7 #include "config.h"
8
9 #include <stdio.h>
10 #include <ctype.h>
11 #if defined(STDC_HEADERS)
12 #include <stdlib.h>
13 #endif
14 #if defined(HAVE_UNISTD_H)
15 #include <unistd.h>
16 #endif
17 #if defined(HAVE_ALLOCA_H)
18 #include <alloca.h>
19 #else
20 #ifdef _AIX
21  #pragma alloca
22 #endif
23 #endif
24 #include <string.h>
25 #include <signal.h>
26 #if defined(HAVE_SYSLOG)
27 #include <syslog.h>
28 #endif
29 #include <pwd.h>
30 #include <errno.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35
36 #ifdef HAVE_GETHOSTBYNAME
37 #include <netdb.h>
38 #endif /* HAVE_GETHOSTBYNAME */
39
40 #include "fetchmail.h"
41 #include "tunable.h"
42 #include "smtp.h"
43 #include "getopt.h"
44 #include "netrc.h"
45
46 #ifndef ENETUNREACH
47 #define ENETUNREACH   128       /* Interactive doesn't know this */
48 #endif /* ENETUNREACH */
49
50 /* prototypes for internal functions */
51 static int load_params(int, char **, int);
52 static void dump_params (struct query *);
53 static int query_host(struct query *);
54
55 /* controls the detail level of status/progress messages written to stderr */
56 int outlevel;           /* see the O_.* constants above */
57
58 /* daemon mode control */
59 flag nodetach;          /* if TRUE, don't detach daemon process */
60 flag quitmode;          /* if --quit was set */
61 flag check_only;        /* if --probe was set */
62 char *cmd_logfile;      /* if --logfile was set */
63 int cmd_daemon;         /* if --daemon was set */
64
65 /* miscellaneous global controls */
66 char *idfile;           /* UID list file */
67 flag versioninfo;       /* emit only version info */
68 char *user;             /* the name of the invoking user */
69 char *home;
70 char *fetchmailhost;    /* the name of the host running fetchmail */
71 char *program_name;     /* the name to prefix error messages with */
72
73 static char *lockfile;          /* name of lockfile */
74 static int querystatus;         /* status of query */
75 static int successes;           /* count number of successful polls */
76 static int lastsig;             /* last signal received */
77
78 static void termhook();         /* forward declaration of exit hook */
79
80 RETSIGTYPE donothing(sig) int sig; {signal(sig, donothing); lastsig = sig;}
81
82 #ifdef HAVE_ON_EXIT
83 static void unlockit(int n, void *p)
84 #else
85 static void unlockit(void)
86 #endif
87 /* must-do actions for exit (but we can't count on being able to do malloc) */
88 {
89     unlink(lockfile);
90 }
91
92 int main (int argc, char **argv)
93 {
94     int st, bkgd = FALSE;
95     int parsestatus, implicitmode = FALSE;
96     struct query *ctl;
97     FILE        *lockfp;
98     netrc_entry *netrc_list;
99     char *netrc_file, tmpbuf[BUFSIZ];
100     pid_t pid;
101
102     envquery(argc, argv);
103
104 #define IDFILE_NAME     ".fetchids"
105     idfile = (char *) xmalloc(strlen(home)+strlen(IDFILE_NAME)+2);
106     strcpy(idfile, home);
107     strcat(idfile, "/");
108     strcat(idfile, IDFILE_NAME);
109   
110     outlevel = O_NORMAL;
111
112     if ((parsestatus = parsecmdline(argc,argv,&cmd_opts)) < 0)
113         exit(PS_SYNTAX);
114
115     /* this hint to stdio should help messages come out in the right order */
116     setvbuf(stdout, NULL, _IOLBF, POPBUFSIZE);
117
118     if (versioninfo)
119     {
120         printf("This is fetchmail release %s", RELEASE_ID);
121 #ifdef POP2_ENABLE
122         printf("+POP2");
123 #endif /* POP2_ENABLE */
124 #ifndef POP3_ENABLE
125         printf("-POP3");
126 #endif /* POP3_ENABLE */
127 #ifndef IMAP_ENABLE
128         printf("-IMAP");
129 #endif /* IMAP_ENABLE */
130 #ifdef RPA_ENABLE
131         printf("+RPA");
132 #endif /* RPA_ENABLE */
133 #ifndef ETRN_ENABLE
134         printf("-ETRN");
135 #endif /* ETRN_ENABLE */
136         putchar('\n');
137
138         /* this is an attempt to help remote debugging */
139         system("uname -a");
140     }
141
142     /* avoid parsing the config file if all we're doing is killing a daemon */ 
143     if (!(quitmode && argc == 2))
144         implicitmode = load_params(argc, argv, optind);
145
146     /* set up to do lock protocol */
147     if (!getuid())
148         sprintf(tmpbuf, "%s/fetchmail.pid", PID_DIR);
149     else {
150         strcpy(tmpbuf, home);
151         strcat(tmpbuf, "/.fetchmail");
152     }
153
154     /* perhaps we just want to check options? */
155     if (versioninfo) {
156         printf("Taking options from command line");
157         if (access(rcfile, 0))
158             printf("\n");
159         else
160             printf(" and %s\n", rcfile);
161         if (poll_interval)
162             printf("Poll interval is %d seconds\n", poll_interval);
163         if (outlevel == O_VERBOSE)
164             printf("Lockfile at %s\n", tmpbuf);
165         if (logfile)
166             printf("Logfile is %s\n", logfile);
167 #if defined(HAVE_SYSLOG)
168         if (errors_to_syslog)
169             printf("Progress messages will be logged via syslog\n");
170 #endif
171         if (use_invisible)
172             printf("Fetchmail will masquerade and will not generate Received\n");
173         for (ctl = querylist; ctl; ctl = ctl->next) {
174             if (ctl->active && !(implicitmode && ctl->server.skip))
175                 dump_params(ctl);
176         }
177         if (querylist == NULL)
178             (void) fprintf(stderr,
179                 "No mailservers set up -- perhaps %s is missing?\n", rcfile);
180         exit(0);
181     }
182
183     /* check for another fetchmail running concurrently */
184     pid = -1;
185     if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
186     {
187         fprintf(stderr,"fetchmail: cannot allocate memory for lock name.\n");
188         exit(PS_EXCLUDE);
189     }
190     else
191         (void) strcpy(lockfile, tmpbuf);
192     if ((lockfp = fopen(lockfile, "r")) != NULL )
193     {
194         bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
195
196         if (kill(pid, 0) == -1) {
197             fprintf(stderr,"fetchmail: removing stale lockfile\n");
198             pid = -1;
199             bkgd = FALSE;
200             unlink(lockfile);
201         }
202         fclose(lockfp);
203     }
204
205     /* if no mail servers listed and nothing in background, we're done */
206     if (!(quitmode && argc == 2) && pid == -1 && querylist == NULL) {
207         (void)fputs("fetchmail: no mailservers have been specified.\n",stderr);
208         exit(PS_SYNTAX);
209     }
210
211     /* perhaps user asked us to kill the other fetchmail */
212     if (quitmode)
213     {
214         if (pid == -1) 
215         {
216             fprintf(stderr,"fetchmail: no other fetchmail is running\n");
217             if (argc == 2)
218                 exit(PS_EXCLUDE);
219         }
220         else if (kill(pid, SIGTERM) < 0)
221         {
222             fprintf(stderr,"fetchmail: error killing %s fetchmail at %d; bailing out.\n",
223                     bkgd ? "background" : "foreground", pid);
224             exit(PS_EXCLUDE);
225         }
226         else
227         {
228             fprintf(stderr,"fetchmail: %s fetchmail at %d killed.\n",
229                     bkgd ? "background" : "foreground", pid);
230             unlink(lockfile);
231             if (argc == 2)
232                 exit(0);
233             else
234                 pid = -1; 
235         }
236     }
237
238     /* another fetchmail is running -- wake it up or die */
239     if (pid != -1)
240     {
241         if (check_only)
242         {
243             fprintf(stderr,
244                  "fetchmail: can't check mail while another fetchmail to same host is running.\n");
245             return(PS_EXCLUDE);
246         }
247         else if (!implicitmode)
248         {
249             fprintf(stderr,
250                  "fetchmail: can't poll specified hosts with another fetchmail running at %d.\n",
251                  pid);
252                 return(PS_EXCLUDE);
253         }
254         else if (!bkgd)
255         {
256             fprintf(stderr,
257                  "fetchmail: another foreground fetchmail is running at %d.\n",
258                  pid);
259                 return(PS_EXCLUDE);
260         }
261         else if (argc > 1)
262         {
263             fprintf(stderr,
264                     "fetchmail: can't accept options while a background fetchmail is running.\n");
265             return(PS_EXCLUDE);
266         }
267         else if (kill(pid, SIGUSR1) == 0)
268         {
269             fprintf(stderr,
270                     "fetchmail: background fetchmail at %d awakened.\n",
271                     pid);
272             return(0);
273         }
274         else
275         {
276             /*
277              * Should never happen -- possible only if a background fetchmail
278              * croaks after the first kill probe above but before the
279              * SIGUSR1/SIGHUP transmission.
280              */
281             fprintf(stderr,
282                     "fetchmail: elder sibling at %d died mysteriously.\n",
283                     pid);
284             return(PS_UNDEFINED);
285         }
286     }
287
288     /* parse the ~/.netrc file (if present) for future password lookups. */
289     netrc_file = (char *) xmalloc (strlen (home) + 8);
290     strcpy (netrc_file, home);
291     strcat (netrc_file, "/.netrc");
292     netrc_list = parse_netrc(netrc_file);
293
294     /* pick up interactively any passwords we need but don't have */ 
295     for (ctl = querylist; ctl; ctl = ctl->next)
296         if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
297         {
298             if (ctl->server.preauthenticate == A_KERBEROS_V4 || ctl->server.protocol == P_IMAP_K4 || ctl->server.protocol == P_IMAP_GSS)
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                 /* look up the host and account in the .netrc file. */
305                 netrc_entry *p = search_netrc(netrc_list,ctl->server.pollname);
306                 while (p && strcmp(p->account, ctl->remotename))
307                     p = search_netrc(p->next, ctl->remotename);
308
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
314             if (ctl->server.protocol != P_ETRN && ctl->server.protocol != P_IMAP_K4 && ctl->server.protocol != P_IMAP_GSS && !ctl->password)
315             {
316                 (void) sprintf(tmpbuf, "Enter password for %s@%s: ",
317                                ctl->remotename, ctl->server.pollname);
318                 ctl->password = xstrdup((char *)getpassword(tmpbuf));
319             }
320         }
321
322     /*
323      * Maybe time to go to demon mode...
324      */
325 #if defined(HAVE_SYSLOG)
326     if (errors_to_syslog)
327     {
328         openlog(program_name, LOG_PID, LOG_MAIL);
329         error_init(-1);
330     }
331     else
332 #endif
333         error_init(poll_interval == 0 && !logfile);
334
335     if (poll_interval)
336     {
337         if (!nodetach)
338             daemonize(logfile, termhook);
339         error( 0, 0, "starting fetchmail %s daemon ", RELEASE_ID);
340
341         /*
342          * We'll set up a handler for these when we're sleeping,
343          * but ignore them otherwise so as not to interrupt a poll.
344          */
345         signal(SIGUSR1, SIG_IGN);
346         if (poll_interval && !getuid())
347             signal(SIGHUP, SIG_IGN);
348     }
349
350     /* beyond here we don't want more than one fetchmail running per user */
351     umask(0077);
352     signal(SIGABRT, termhook);
353     signal(SIGINT, termhook);
354     signal(SIGTERM, termhook);
355     signal(SIGALRM, termhook);
356     signal(SIGPIPE, termhook);
357     signal(SIGQUIT, termhook);
358
359     /* here's the exclusion lock */
360     if ((lockfp = fopen(lockfile,"w")) != NULL) {
361         fprintf(lockfp,"%d",getpid());
362         if (poll_interval)
363             fprintf(lockfp," %d", poll_interval);
364         fclose(lockfp);
365
366 #ifdef HAVE_ATEXIT
367         atexit(unlockit);
368 #endif
369 #ifdef HAVE_ON_EXIT
370         on_exit(unlockit, (char *)NULL);
371 #endif
372     }
373
374     /*
375      * Query all hosts. If there's only one, the error return will
376      * reflect the status of that transaction.
377      */
378     do {
379 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
380         /*
381          * This was an efficiency hack that backfired.  The theory
382          * was that using TCP/IP for DNS queries would get us better
383          * reliability and shave off some per-UDP-packet costs.
384          * Unfortunately it interacted badly with diald, which effectively 
385          * filters out DNS queries over TCP/IP for reasons having to do
386          * with some obscure kernel problem involving bootstrapping of
387          * dynamically-addressed links.  I don't understand this mess
388          * and don't want to, so it's "See ya!" to this hack.
389          */
390         sethostent(TRUE);       /* use TCP/IP for mailserver queries */
391 #endif /* HAVE_RES_SEARCH */
392
393         batchcount = 0;
394         for (ctl = querylist; ctl; ctl = ctl->next)
395         {
396             if (ctl->active && !(implicitmode && ctl->server.skip))
397             {
398                 /* check skip interval first so that it counts all polls */
399                 if (poll_interval && ctl->server.interval) 
400                 {
401                     if (ctl->server.poll_count++ % ctl->server.interval) 
402                     {
403                         if (outlevel == O_VERBOSE)
404                             fprintf(stderr,
405                                     "fetchmail: interval not reached, not querying %s\n",
406                                     ctl->server.pollname);
407                         continue;
408                     }
409                 }
410
411 #ifdef linux
412                 /* interface_approve() does its own error logging */
413                 if (!interface_approve(&ctl->server))
414                     continue;
415 #endif /* linux */
416
417 #ifdef HAVE_GETHOSTBYNAME
418                 /*
419                  * This functions partly as a probe to make sure our
420                  * nameserver is still up.  The multidrop case
421                  * (especially) needs it.
422                  */
423                 if (ctl->server.preauthenticate==A_KERBEROS_V4 || MULTIDROP(ctl))
424                 {
425                     struct hostent      *namerec;
426
427                     /* compute the canonical name of the host */
428                     errno = 0;
429                     namerec = gethostbyname(ctl->server.queryname);
430                     if (namerec == (struct hostent *)NULL)
431                     {
432                         error(0, errno,
433                                 "skipping %s poll, ",
434                                 ctl->server.pollname);
435                         if (errno)
436                         {
437                             if (errno == ENETUNREACH)
438                                 break;  /* go to sleep */
439                         }
440 #ifdef HAVE_HERROR              /* NEXTSTEP doesn't */
441                         else
442                             herror("DNS error");
443 #endif /* HAVE_HERROR */
444                         continue;
445                     }
446                     else
447                     {
448                         free(ctl->server.truename);
449                         ctl->server.truename=xstrdup((char *)namerec->h_name);
450                     }
451                 }
452 #endif /* HAVE_GETHOSTBYNAME */
453
454                 querystatus = query_host(ctl);
455
456                 if (querystatus == PS_SUCCESS) {
457                     successes++;
458 #ifdef POP3_ENABLE
459                     if (!check_only)
460                       update_str_lists(ctl);
461 #endif  /* POP3_ENABLE */
462                 }
463 #ifdef  linux
464                 if (ctl->server.monitor)
465                     {
466                         /* Allow some time for the link to quiesce.  One
467                          * second is usually sufficient, three is safe.
468                          * Note:  this delay is important - don't remove!
469                          */
470                         sleep(3);
471                         interface_note_activity(&ctl->server);
472                     }
473 #endif
474             }
475         }
476
477 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
478         endhostent();           /* release TCP/IP connection to nameserver */
479 #endif /* HAVE_RES_SEARCH */
480
481         /*
482          * Close all SMTP delivery sockets.  For optimum performance
483          * we'd like to hold them open til end of run, but (1) this
484          * loses if our poll interval is longer than the MTA's inactivity
485          * timeout, and (2) some MTAs (like smail) don't deliver after
486          * each message, but rather queue up mail and wait to actually
487          * deliver it until the input socket is closed. 
488          */
489         for (ctl = querylist; ctl; ctl = ctl->next)
490             if (ctl->smtp_socket != -1)
491             {
492                 SMTP_quit(ctl->smtp_socket);
493                 close(ctl->smtp_socket);
494                 ctl->smtp_socket = -1;
495             }
496
497         /*
498          * OK, we've polled.  Now sleep.
499          */
500         if (poll_interval)
501         {
502             if (outlevel == O_VERBOSE)
503             {
504                 time_t  now;
505
506                 time(&now);
507                 fprintf(stderr, "fetchmail: sleeping at %s", ctime(&now));
508             }
509
510             /*
511              * With this simple hack, we make it possible for a foreground 
512              * fetchmail to wake up one in daemon mode.  What we want is the
513              * side effect of interrupting any sleep that may be going on,
514              * forcing fetchmail to re-poll its hosts.  The second line is
515              * for people who think all system daemons wake up on SIGHUP.
516              */
517             signal(SIGUSR1, donothing);
518             if (!getuid())
519                 signal(SIGHUP, donothing);
520
521             /*
522              * We can't use sleep(3) here because we need an alarm(3)
523              * equivalent in order to implement server nonresponse timeout.
524              * We'll just assume setitimer(2) is available since fetchmail
525              * has to have a BSDoid socket layer to work at all.
526              */
527             {
528                 struct itimerval ntimeout;
529
530                 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
531                 ntimeout.it_value.tv_sec  = poll_interval;
532                 ntimeout.it_value.tv_usec = 0;
533
534                 setitimer(ITIMER_REAL,&ntimeout,NULL);
535                 signal(SIGALRM, donothing);
536                 pause();
537                 signal(SIGALRM, SIG_IGN);
538                 if (lastsig == SIGUSR1
539                         || ((poll_interval && !getuid()) && lastsig == SIGHUP))
540                 {
541 #ifdef SYS_SIGLIST_DECLARED
542                     error(0, 0, "awakened by %s", sys_siglist[lastsig]);
543 #else
544                     error(0, 0, "awakened by signal %d", lastsig);
545 #endif
546                 }
547             }
548
549             /* now lock out interrupts again */
550             signal(SIGUSR1, SIG_IGN);
551             if (!getuid())
552                 signal(SIGHUP, SIG_IGN);
553
554             if (outlevel == O_VERBOSE)
555             {
556                 time_t  now;
557
558                 time(&now);
559                 fprintf(stderr, "fetchmail: awakened at %s", ctime(&now));
560             }
561         }
562     } while
563         (poll_interval);
564
565     if (outlevel == O_VERBOSE)
566         fprintf(stderr,"fetchmail: normal termination, status %d\n",
567                 successes ? PS_SUCCESS : querystatus);
568
569     termhook(0);
570     exit(successes ? PS_SUCCESS : querystatus);
571 }
572
573 static int load_params(int argc, char **argv, int optind)
574 {
575     int implicitmode, st;
576     struct passwd *pw;
577     struct query def_opts, *ctl;
578
579     memset(&def_opts, '\0', sizeof(struct query));
580     def_opts.smtp_socket = -1;
581     def_opts.smtpaddress = (char *)0;
582
583     def_opts.server.protocol = P_AUTO;
584     def_opts.server.timeout = CLIENT_TIMEOUT;
585     def_opts.remotename = user;
586     def_opts.expunge = 1;
587
588     /* this builds the host list */
589     if (prc_parse_file(rcfile, !versioninfo) != 0)
590         exit(PS_SYNTAX);
591
592     if ((implicitmode = (optind >= argc)))
593     {
594         for (ctl = querylist; ctl; ctl = ctl->next)
595             ctl->active = TRUE;
596     }
597     else
598         for (; optind < argc; optind++) 
599         {
600             /*
601              * If hostname corresponds to a host known from the rc file,
602              * simply declare it active.  Otherwise synthesize a host
603              * record from command line and defaults
604              */
605             for (ctl = querylist; ctl; ctl = ctl->next)
606                 if (!strcmp(ctl->server.pollname, argv[optind])
607                         || str_in_list(&ctl->server.akalist, argv[optind]))
608                     goto foundit;
609
610             ctl = hostalloc(&cmd_opts);
611             ctl->server.pollname = xstrdup(argv[optind]);
612
613         foundit:
614             ctl->active = TRUE;
615         }
616
617     /* if there's a defaults record, merge it and lose it */ 
618     if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
619     {
620         for (ctl = querylist->next; ctl; ctl = ctl->next)
621             optmerge(ctl, querylist);
622         querylist = querylist->next;
623     }
624
625     /* don't allow a defaults record after the first */
626     for (ctl = querylist; ctl; ctl = ctl->next)
627         if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
628             exit(PS_SYNTAX);
629
630     /* merge in wired defaults, do sanity checks and prepare internal fields */
631     for (ctl = querylist; ctl; ctl = ctl->next)
632     {
633         if (ctl->active && !(implicitmode && ctl->server.skip))
634         {
635             /* merge in defaults */
636             optmerge(ctl, &def_opts);
637
638             /* make sure we have a nonempty host list to forward to */
639             if (!ctl->smtphunt)
640                 save_str(&ctl->smtphunt, FALSE, fetchmailhost);
641
642             /* keep lusers from shooting themselves in the foot :-) */
643             if (poll_interval && ctl->limit)
644             {
645                 fprintf(stderr,"fetchmail: you'd never see large messages!\n");
646                 exit(PS_SYNTAX);
647             }
648
649             /* if `user' doesn't name a real local user, try to run as root */
650             if ((pw = getpwnam(user)) == (struct passwd *)NULL)
651                 ctl->uid = 0;
652             else
653                 ctl->uid = pw->pw_uid;  /* for local delivery via MDA */
654             if (!ctl->localnames)       /* for local delivery via SMTP */
655                 save_str_pair(&ctl->localnames, user, NULL);
656
657             /* this code enables flags to be turned off */
658 #define DEFAULT(flag, dflt)     if (flag == FLAG_TRUE)\
659                                         flag = TRUE;\
660                                 else if (flag == FLAG_FALSE)\
661                                         flag = FALSE;\
662                                 else\
663                                         flag = (dflt)
664             DEFAULT(ctl->keep, FALSE);
665             DEFAULT(ctl->fetchall, FALSE);
666             DEFAULT(ctl->flush, FALSE);
667             DEFAULT(ctl->rewrite, TRUE);
668             DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL)); 
669             DEFAULT(ctl->forcecr, FALSE);
670             DEFAULT(ctl->pass8bits, FALSE);
671             DEFAULT(ctl->dropstatus, FALSE);
672             DEFAULT(ctl->server.dns, TRUE);
673             DEFAULT(ctl->server.uidl, FALSE);
674 #undef DEFAULT
675
676 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
677             /* can't handle multidrop mailboxes unless we can do DNS lookups */
678             if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
679             {
680                 ctl->server.dns = FALSE;
681                 fprintf(stderr, "fetchmail: warning: no DNS available to check multidrop fetches from %s\n", ctl->server.pollname);
682             }
683 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
684
685             /*
686              *
687              * Compute the true name of the mailserver host.  
688              * There are two clashing cases here:
689              *
690              * (1) The poll name is a label, possibly on one of several
691              *     poll configurations for the same host.  In this case 
692              *     the `via' option will be present and give the true name.
693              *
694              * (2) The poll name is the true one, the via name is 
695              *     localhost.   This is going to be typical for ssh-using
696              *     configurations.
697              *
698              * We're going to assume the via name is true unless it's
699              * localhost.
700              *
701              * Each poll cycle, if we've got DNS, we'll try to canonicalize
702              * the name.  This will function as a probe to ensure the
703              * host's nameserver is up.
704              */
705             if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
706                 ctl->server.queryname = xstrdup(ctl->server.via);
707             else
708                 ctl->server.queryname = xstrdup(ctl->server.pollname);
709             ctl->server.truename = xstrdup(ctl->server.queryname);
710
711             /* if no folders were specified, set up the null one as default */
712             if (!ctl->mailboxes)
713                 save_str(&ctl->mailboxes, -1, (char *)NULL);
714
715             /* maybe user overrode timeout on command line? */
716             if (ctl->server.timeout == -1)      
717                 ctl->server.timeout = CLIENT_TIMEOUT;
718
719             /* sanity checks */
720             if (ctl->server.port < 0)
721             {
722                 (void) fprintf(stderr,
723                                "%s configuration invalid, port number cannot be negative",
724                                ctl->server.pollname);
725                 exit(PS_SYNTAX);
726             }
727             if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
728             {
729                 (void) fprintf(stderr,
730                                "%s configuration invalid, RPOP requires a privileged port",
731                                ctl->server.pollname);
732                 exit(PS_SYNTAX);
733             }
734         }
735     }
736
737     /* initialize UID handling */
738     if (!versioninfo && (st = prc_filecheck(idfile)) != 0)
739         exit(st);
740 #ifdef POP3_ENABLE
741     else
742         initialize_saved_lists(querylist, idfile);
743 #endif /* POP3_ENABLE */
744
745     /* if cmd_logfile was explicitly set, use it to override logfile */
746     if (cmd_logfile)
747         logfile = cmd_logfile;
748
749     /* likewise for poll_interval */
750     if (cmd_daemon >= 0)
751         poll_interval = cmd_daemon;
752
753     /* check and daemon options are not compatible */
754     if (check_only && poll_interval)
755         poll_interval = 0;
756
757     return(implicitmode);
758 }
759
760 void termhook(int sig)
761 /* to be executed on normal or signal-induced termination */
762 {
763     struct query        *ctl;
764
765     /*
766      * Sending SMTP QUIT on signal is theoretically nice, but led to a 
767      * subtle bug.  If fetchmail was terminated by signal while it was 
768      * shipping message text, it would hang forever waiting for a
769      * command acknowledge.  In theory we could enable the QUIT
770      * only outside of the message send.  In practice, we don't
771      * care.  All mailservers hang up on a dropped TCP/IP connection
772      * anyway.
773      */
774
775     if (sig != 0)
776         error(0, 0, "terminated with signal %d", sig);
777     else
778         /* terminate all SMTP connections cleanly */
779         for (ctl = querylist; ctl; ctl = ctl->next)
780             if (ctl->smtp_socket != -1)
781                 SMTP_quit(ctl->smtp_socket);
782
783 #ifdef POP3_ENABLE
784     if (!check_only)
785         write_saved_lists(querylist, idfile);
786 #endif /* POP3_ENABLE */
787
788     /* 
789      * Craig Metz, the RFC1938 one-time-password guy, points out:
790      * "Remember that most kernels don't zero pages before handing them to the
791      * next process and many kernels share pages between user and kernel space.
792      * You'd be very surprised what you can find from a short program to do a
793      * malloc() and then dump the contents of the pages you got. By zeroing
794      * the secrets at end of run (earlier if you can), you make sure the next
795      * guy can't get the password/pass phrase."
796      *
797      * Right you are, Craig!
798      */
799     for (ctl = querylist; ctl; ctl = ctl->next)
800         if (ctl->password)
801           memset(ctl->password, '\0', strlen(ctl->password));
802
803 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
804     unlockit();
805 #endif
806
807     exit(successes ? PS_SUCCESS : querystatus);
808 }
809
810 /*
811  * Sequence of protocols to try when autoprobing, most capable to least.
812  */
813 static const int autoprobe[] = 
814 {
815 #ifdef IMAP_ENABLE
816     P_IMAP,
817 #endif /* IMAP_ENABLE */
818 #ifdef POP3_ENABLE
819     P_POP3,
820 #endif /* POP3_ENABLE */
821 #ifdef POP2_ENABLE
822     P_POP2
823 #endif /* POP2_ENABLE */
824 };
825
826 static int query_host(struct query *ctl)
827 /* perform fetch transaction with single host */
828 {
829     int i, st;
830
831     if (outlevel == O_VERBOSE)
832     {
833         time_t now;
834
835         time(&now);
836         fprintf(stderr, "fetchmail: %s querying %s (protocol %s) at %s",
837             RELEASE_ID,
838             ctl->server.pollname, showproto(ctl->server.protocol), ctime(&now));
839     }
840     switch (ctl->server.protocol) {
841     case P_AUTO:
842         for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
843         {
844             ctl->server.protocol = autoprobe[i];
845             if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
846                 break;
847         }
848         ctl->server.protocol = P_AUTO;
849         return(st);
850         break;
851     case P_POP2:
852 #ifdef POP2_ENABLE
853         return(doPOP2(ctl));
854 #else
855         fprintf(stderr, "POP2 support is not configured.\n");
856         return(PS_PROTOCOL);
857 #endif /* POP2_ENABLE */
858         break;
859     case P_POP3:
860     case P_APOP:
861     case P_RPOP:
862 #ifdef POP3_ENABLE
863         return(doPOP3(ctl));
864 #else
865         fprintf(stderr, "POP3 support is not configured.\n");
866         return(PS_PROTOCOL);
867 #endif /* POP3_ENABLE */
868         break;
869     case P_IMAP:
870     case P_IMAP_K4:
871     case P_IMAP_GSS:
872 #ifdef IMAP_ENABLE
873         return(doIMAP(ctl));
874 #else
875         fprintf(stderr, "IMAP support is not configured.\n");
876         return(PS_PROTOCOL);
877 #endif /* IMAP_ENABLE */
878         break;
879     case P_ETRN:
880 #ifndef ETRN_ENABLE
881         fprintf(stderr, "ETRN support is not configured.\n");
882         return(PS_PROTOCOL);
883 #else
884 #ifdef HAVE_GETHOSTBYNAME
885         return(doETRN(ctl));
886 #else
887         fprintf(stderr, "Cannot support ETRN without gethostbyname(2).\n");
888         return(PS_PROTOCOL);
889 #endif /* HAVE_GETHOSTBYNAME */
890 #endif /* ETRN_ENABLE */
891     default:
892         error(0, 0, "unsupported protocol selected.");
893         return(PS_PROTOCOL);
894     }
895 }
896
897 void dump_params (struct query *ctl)
898 /* display query parameters in English */
899 {
900     printf("Options for retrieving from %s@%s:\n",
901            ctl->remotename, visbuf(ctl->server.pollname));
902
903     if (ctl->server.via)
904         printf("  Mail will be retrieved via %s\n", ctl->server.via);
905
906     if (ctl->server.interval)
907         printf("  Poll of this server will occur every %d intervals.\n",
908                ctl->server.interval);
909     if (ctl->server.truename)
910         printf("  True name of server is %s.\n", ctl->server.truename);
911     if (ctl->server.skip || outlevel == O_VERBOSE)
912         printf("  This host will%s be queried when no host is specified.\n",
913                ctl->server.skip ? " not" : "");
914     if (!ctl->password)
915         printf("  Password will be prompted for.\n");
916     else if (outlevel == O_VERBOSE)
917         if (ctl->server.protocol == P_APOP)
918             printf("  APOP secret = '%s'.\n", visbuf(ctl->password));
919         else if (ctl->server.protocol == P_RPOP)
920             printf("  RPOP id = '%s'.\n", visbuf(ctl->password));
921         else
922             printf("  Password = '%s'.\n", visbuf(ctl->password));
923     if (ctl->server.protocol == P_POP3 
924                 && ctl->server.port == KPOP_PORT
925                 && ctl->server.preauthenticate == A_KERBEROS_V4)
926         printf("  Protocol is KPOP");
927     else
928         printf("  Protocol is %s", showproto(ctl->server.protocol));
929     if (ctl->server.port)
930         printf(" (using port %d)", ctl->server.port);
931     else if (outlevel == O_VERBOSE)
932         printf(" (using default port)");
933     if (ctl->server.uidl)
934         printf(" (forcing UIDL use)");
935     putchar('.');
936     putchar('\n');
937     if (ctl->server.preauthenticate == A_KERBEROS_V4)
938             printf("  Kerberos V4 preauthentication enabled.\n");
939     if (ctl->server.timeout > 0)
940         printf("  Server nonresponse timeout is %d seconds", ctl->server.timeout);
941     if (ctl->server.timeout ==  CLIENT_TIMEOUT)
942         printf(" (default).\n");
943     else
944         printf(".\n");
945
946     if (!ctl->mailboxes->id)
947         printf("  Default mailbox selected.\n");
948     else
949     {
950         struct idlist *idp;
951
952         printf("  Selected mailboxes are:");
953         for (idp = ctl->mailboxes; idp; idp = idp->next)
954             printf(" %s", idp->id);
955         printf("\n");
956     }
957     printf("  %s messages will be retrieved (--all %s).\n",
958            ctl->fetchall ? "All" : "Only new",
959            ctl->fetchall ? "on" : "off");
960     printf("  Fetched messages will%s be kept on the server (--keep %s).\n",
961            ctl->keep ? "" : " not",
962            ctl->keep ? "on" : "off");
963     printf("  Old messages will%s be flushed before message retrieval (--flush %s).\n",
964            ctl->flush ? "" : " not",
965            ctl->flush ? "on" : "off");
966     printf("  Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
967            ctl->rewrite ? "en" : "dis",
968            ctl->rewrite ? "off" : "on");
969     printf("  Carriage-return stripping is %sabled (stripcr %s).\n",
970            ctl->stripcr ? "en" : "dis",
971            ctl->stripcr ? "on" : "off");
972     printf("  Carriage-return forcing is %sabled (forcecr %s).\n",
973            ctl->forcecr ? "en" : "dis",
974            ctl->forcecr ? "on" : "off");
975     printf("  Interpretation of Content-Transfer-Encoding is %sabled (pass8bits %s).\n",
976            ctl->pass8bits ? "dis" : "en",
977            ctl->pass8bits ? "on" : "off");
978     printf("  Nonempty Status lines will be %s (dropstatus %s)\n",
979            ctl->dropstatus ? "discarded" : "kept",
980            ctl->dropstatus ? "on" : "off");
981     if (NUM_NONZERO(ctl->limit))
982         printf("  Message size limit is %d bytes (--limit %d).\n", 
983                ctl->limit, ctl->limit);
984     else if (outlevel == O_VERBOSE)
985         printf("  No message size limit (--limit 0).\n");
986     if (NUM_NONZERO(ctl->fetchlimit))
987         printf("  Received-message limit is %d (--fetchlimit %d).\n",
988                ctl->fetchlimit, ctl->fetchlimit);
989     else if (outlevel == O_VERBOSE)
990         printf("  No received-message limit (--fetchlimit 0).\n");
991     if (NUM_NONZERO(ctl->batchlimit))
992         printf("  SMTP message batch limit is %d.\n", ctl->batchlimit);
993     else if (outlevel == O_VERBOSE)
994         printf("  No SMTP message batch limit (--batchlimit 0).\n");
995     if (ctl->server.protocol == P_IMAP)
996         if (NUM_NONZERO(ctl->expunge))
997             printf("  Deletion interval between expunges is %d (--expunge %d).\n", ctl->expunge, ctl->expunge);
998         else if (outlevel == O_VERBOSE)
999             printf("  No expunges (--expunge 0).\n");
1000     if (ctl->mda)
1001         printf("  Messages will be delivered with '%s.'\n", visbuf(ctl->mda));
1002     else
1003     {
1004         struct idlist *idp;
1005
1006         printf("  Messages will be SMTP-forwarded to:");
1007         for (idp = ctl->smtphunt; idp; idp = idp->next)
1008             if (ctl->server.protocol != P_ETRN || idp->val.num)
1009             {
1010                 printf(" %s", idp->id);
1011                 if (!idp->val.num)
1012                     printf(" (default)");
1013             }
1014         printf("\n");
1015         if (ctl->smtpaddress)
1016             printf("  Host part of MAIL FROM line will be %s\n",
1017                    ctl->smtpaddress);
1018     }
1019     if (ctl->preconnect)
1020         printf("  Server connection will be brought up with '%s.'\n",
1021                visbuf(ctl->preconnect));
1022     else if (outlevel == O_VERBOSE)
1023         printf("  No pre-connection command.\n");
1024     if (ctl->postconnect)
1025         printf("  Server connection will be taken down with '%s.'\n",
1026                visbuf(ctl->postconnect));
1027     else if (outlevel == O_VERBOSE)
1028         printf("  No post-connection command.\n");
1029     if (!ctl->localnames)
1030         printf("  No localnames declared for this host.\n");
1031     else
1032     {
1033         struct idlist *idp;
1034         int count = 0;
1035
1036         for (idp = ctl->localnames; idp; idp = idp->next)
1037             ++count;
1038
1039         if (count > 1 || ctl->wildcard)
1040             printf("  Multi-drop mode: ");
1041         else
1042             printf("  Single-drop mode: ");
1043
1044         printf("%d local name(s) recognized.\n", count);
1045         if (outlevel == O_VERBOSE)
1046         {
1047             for (idp = ctl->localnames; idp; idp = idp->next)
1048                 if (idp->val.id2)
1049                     printf("\t%s -> %s\n", idp->id, idp->val.id2);
1050                 else
1051                     printf("\t%s\n", idp->id);
1052             if (ctl->wildcard)
1053                 fputs("*\n", stdout);
1054         }
1055
1056         if (count > 1 || ctl->wildcard)
1057         {
1058             printf("  DNS lookup for multidrop addresses is %sabled.\n",
1059                    ctl->server.dns ? "en" : "dis");
1060
1061             if (ctl->server.envelope == STRING_DISABLED)
1062                 printf("  Envelope-address routing is disabled\n");
1063             else
1064             {
1065                 printf("  Envelope header is assumed to be: %s\n",
1066                        ctl->server.envelope ? ctl->server.envelope:"Received");
1067                 if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1068                     printf("  Number of envelope header to be parsed: %d\n",
1069                            ctl->server.envskip);
1070                 if (ctl->server.qvirtual)
1071                     printf("  Prefix %s will be removed from user id\n",
1072                            ctl->server.qvirtual);
1073                 else if (outlevel >= O_VERBOSE) 
1074                     printf("  No prefix stripping\n");
1075             }
1076
1077             if (ctl->server.akalist)
1078             {
1079                 struct idlist *idp;
1080
1081                 printf("  Predeclared mailserver aliases:");
1082                 for (idp = ctl->server.akalist; idp; idp = idp->next)
1083                     printf(" %s", idp->id);
1084                 putchar('\n');
1085             }
1086             if (ctl->server.localdomains)
1087             {
1088                 struct idlist *idp;
1089
1090                 printf("  Local domains:");
1091                 for (idp = ctl->server.localdomains; idp; idp = idp->next)
1092                     printf(" %s", idp->id);
1093                 putchar('\n');
1094             }
1095         }
1096     }
1097 #ifdef  linux
1098     if (ctl->server.interface)
1099         printf("  Connection must be through interface %s.\n", ctl->server.interface);
1100     else if (outlevel == O_VERBOSE)
1101         printf("  No interface requirement specified.\n");
1102     if (ctl->server.monitor)
1103         printf("  Polling loop will monitor %s.\n", ctl->server.monitor);
1104     else if (outlevel == O_VERBOSE)
1105         printf("  No monitor interface specified.\n");
1106 #endif
1107
1108     if (ctl->server.protocol > P_POP2)
1109         if (!ctl->oldsaved)
1110             printf("  No UIDs saved from this host.\n");
1111         else
1112         {
1113             struct idlist *idp;
1114             int count = 0;
1115
1116             for (idp = ctl->oldsaved; idp; idp = idp->next)
1117                 ++count;
1118
1119             printf("  %d UIDs saved.\n", count);
1120             if (outlevel == O_VERBOSE)
1121                 for (idp = ctl->oldsaved; idp; idp = idp->next)
1122                     fprintf(stderr, "\t%s\n", idp->id);
1123         }
1124 }
1125
1126 /* fetchmail.c ends here */