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