]> Pileus Git - ~andy/fetchmail/blob - fetchmail.c
SIGALRM flakiness fix.
[~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 || ctl->server.protocol == P_IMAP_K4 || ctl->server.protocol == P_IMAP_GSS)
329                 /* Server won't care what the password is, but there
330                    must be some non-null string here.  */
331                 ctl->password = ctl->remotename;
332             else
333             {
334                 /* look up the host and account in the .netrc file. */
335                 netrc_entry *p = search_netrc(netrc_list,ctl->server.pollname);
336                 while (p && strcmp(p->account, ctl->remotename))
337                     p = search_netrc(p->next, ctl->remotename);
338
339                 /* if we find a matching entry with a password, use it */
340                 if (p && p->password)
341                     ctl->password = xstrdup(p->password);
342             }
343
344             if (ctl->server.protocol != P_ETRN && ctl->server.protocol != P_IMAP_K4 && ctl->server.protocol != P_IMAP_GSS && !ctl->password)
345             {
346                 (void) sprintf(tmpbuf, "Enter password for %s@%s: ",
347                                ctl->remotename, ctl->server.pollname);
348                 ctl->password = xstrdup((char *)getpassword(tmpbuf));
349             }
350         }
351
352     /*
353      * Maybe time to go to demon mode...
354      */
355 #if defined(HAVE_SYSLOG)
356     if (errors_to_syslog)
357     {
358         openlog(program_name, LOG_PID, LOG_MAIL);
359         error_init(-1);
360     }
361     else
362 #endif
363         error_init(poll_interval == 0 && !logfile);
364
365     if (poll_interval)
366     {
367         if (!nodetach)
368             daemonize(logfile, termhook);
369         error( 0, 0, "starting fetchmail %s daemon ", RELEASE_ID);
370
371         /*
372          * We'll set up a handler for these when we're sleeping,
373          * but ignore them otherwise so as not to interrupt a poll.
374          */
375         signal(SIGUSR1, SIG_IGN);
376         if (poll_interval && !getuid())
377             signal(SIGHUP, SIG_IGN);
378     }
379
380     /* beyond here we don't want more than one fetchmail running per user */
381     umask(0077);
382     signal(SIGABRT, termhook);
383     signal(SIGINT, termhook);
384     signal(SIGTERM, termhook);
385     signal(SIGALRM, termhook);
386     signal(SIGPIPE, termhook);
387     signal(SIGQUIT, termhook);
388
389     /* here's the exclusion lock */
390     if ((lockfp = fopen(lockfile,"w")) != NULL) {
391         fprintf(lockfp,"%d",getpid());
392         if (poll_interval)
393             fprintf(lockfp," %d", poll_interval);
394         fclose(lockfp);
395
396 #ifdef HAVE_ATEXIT
397         atexit(unlockit);
398 #endif
399 #ifdef HAVE_ON_EXIT
400         on_exit(unlockit, (char *)NULL);
401 #endif
402     }
403
404     /*
405      * Query all hosts. If there's only one, the error return will
406      * reflect the status of that transaction.
407      */
408     do {
409 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
410         /*
411          * This was an efficiency hack that backfired.  The theory
412          * was that using TCP/IP for DNS queries would get us better
413          * reliability and shave off some per-UDP-packet costs.
414          * Unfortunately it interacted badly with diald, which effectively 
415          * filters out DNS queries over TCP/IP for reasons having to do
416          * with some obscure kernel problem involving bootstrapping of
417          * dynamically-addressed links.  I don't understand this mess
418          * and don't want to, so it's "See ya!" to this hack.
419          */
420         sethostent(TRUE);       /* use TCP/IP for mailserver queries */
421 #endif /* HAVE_RES_SEARCH */
422
423         batchcount = 0;
424         for (ctl = querylist; ctl; ctl = ctl->next)
425         {
426             if (ctl->active && !(implicitmode && ctl->server.skip))
427             {
428                 /* check skip interval first so that it counts all polls */
429                 if (poll_interval && ctl->server.interval) 
430                 {
431                     if (ctl->server.poll_count++ % ctl->server.interval) 
432                     {
433                         if (outlevel == O_VERBOSE)
434                             fprintf(stderr,
435                                     "fetchmail: interval not reached, not querying %s\n",
436                                     ctl->server.pollname);
437                         continue;
438                     }
439                 }
440
441 #if defined(linux) && !INET6
442                 /* interface_approve() does its own error logging */
443                 if (!interface_approve(&ctl->server))
444                     continue;
445 #endif /* defined(linux) && !INET6 */
446
447 #ifdef HAVE_GETHOSTBYNAME
448                 /*
449                  * This functions partly as a probe to make sure our
450                  * nameserver is still up.  The multidrop case
451                  * (especially) needs it.
452                  */
453                 if (ctl->server.preauthenticate==A_KERBEROS_V4 || MULTIDROP(ctl))
454                 {
455                     struct hostent      *namerec;
456
457                     /* compute the canonical name of the host */
458                     errno = 0;
459                     namerec = gethostbyname(ctl->server.queryname);
460                     if (namerec == (struct hostent *)NULL)
461                     {
462                         error(0, errno,
463                                 "skipping %s poll, ",
464                                 ctl->server.pollname);
465                         if (errno)
466                         {
467                             if (errno == ENETUNREACH)
468                                 break;  /* go to sleep */
469                         }
470 #ifdef HAVE_HERROR              /* NEXTSTEP doesn't */
471                         else
472                             herror("DNS error");
473 #endif /* HAVE_HERROR */
474                         continue;
475                     }
476                     else
477                     {
478                         free(ctl->server.truename);
479                         ctl->server.truename=xstrdup((char *)namerec->h_name);
480                     }
481                 }
482 #endif /* HAVE_GETHOSTBYNAME */
483
484                 querystatus = query_host(ctl);
485
486                 if (querystatus == PS_SUCCESS) {
487                     successes++;
488 #ifdef POP3_ENABLE
489                     if (!check_only)
490                       update_str_lists(ctl);
491 #endif  /* POP3_ENABLE */
492                 }
493 #if defined(linux) && !INET6
494                 if (ctl->server.monitor)
495                     {
496                         /* Allow some time for the link to quiesce.  One
497                          * second is usually sufficient, three is safe.
498                          * Note:  this delay is important - don't remove!
499                          */
500                         sleep(3);
501                         interface_note_activity(&ctl->server);
502                     }
503 #endif /* defined(linux) && !INET6 */
504             }
505         }
506
507 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
508         endhostent();           /* release TCP/IP connection to nameserver */
509 #endif /* HAVE_RES_SEARCH */
510
511         /*
512          * Close all SMTP delivery sockets.  For optimum performance
513          * we'd like to hold them open til end of run, but (1) this
514          * loses if our poll interval is longer than the MTA's inactivity
515          * timeout, and (2) some MTAs (like smail) don't deliver after
516          * each message, but rather queue up mail and wait to actually
517          * deliver it until the input socket is closed. 
518          */
519         for (ctl = querylist; ctl; ctl = ctl->next)
520             if (ctl->smtp_socket != -1)
521             {
522                 SMTP_quit(ctl->smtp_socket);
523                 close(ctl->smtp_socket);
524                 ctl->smtp_socket = -1;
525             }
526
527         /*
528          * OK, we've polled.  Now sleep.
529          */
530         if (poll_interval)
531         {
532             if (outlevel == O_VERBOSE)
533             {
534                 time_t  now;
535
536                 time(&now);
537                 fprintf(stderr, "fetchmail: sleeping at %s", ctime(&now));
538             }
539
540             /*
541              * With this simple hack, we make it possible for a foreground 
542              * fetchmail to wake up one in daemon mode.  What we want is the
543              * side effect of interrupting any sleep that may be going on,
544              * forcing fetchmail to re-poll its hosts.  The second line is
545              * for people who think all system daemons wake up on SIGHUP.
546              */
547             signal(SIGUSR1, donothing);
548             if (!getuid())
549                 signal(SIGHUP, donothing);
550
551             /*
552              * We can't use sleep(3) here because we need an alarm(3)
553              * equivalent in order to implement server nonresponse timeout.
554              * We'll just assume setitimer(2) is available since fetchmail
555              * has to have a BSDoid socket layer to work at all.
556              */
557             {
558 #ifndef __EMX__
559 #ifndef SLEEP_WITH_ALARM        /* not normally on */
560                 struct timeval timeout;
561
562                 timeout.tv_sec = poll_interval;
563                 timeout.tv_usec = 0;
564                 select(0,0,0,0, &timeout);
565 #else
566                 /* 
567                  * This code is flaky under Red Hat Linux 5.0, and possibly
568                  * elsewhere.  John Stracke <francis@netscape.com> writes:
569                  *
570                  * The problem seems to be that, after hitting the interval
571                  * timer while talking to the server, the process no longer
572                  * responds to SIGALRM.  I put in printf()s to see when it
573                  * reached the pause() for the poll interval, and I checked
574                  * the return from setitimer(), and everything seemed to be
575                  * working fine, except that the pause() just ignored SIGALRM.
576                  * I thought maybe the itimer wasn't being fired, so I hit
577                  * it with a SIGALRM from the command line, and it ignored
578                  * that, too.  SIGUSR1 woke it up just fine, and it proceeded
579                  * to repoll--but, when the dummy server didn't respond, it
580                  * never timed out, and SIGALRM wouldn't make it.
581                  *
582                  * So the workaround I used is to make it sleep by using
583                  * select() instead of setitimer()/pause().  select() is
584                  * perfectly happy being called with a timeout and
585                  * no file descriptors; it just sleeps until it hits the
586                  * timeout.  The only concern I had was that it might
587                  * implement its timeout with SIGALRM--there are some
588                  * Unices where this is done, because select() is a library
589                  * function--but apparently not.
590                  */
591                 struct itimerval ntimeout;
592
593                 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
594                 ntimeout.it_value.tv_sec  = poll_interval;
595                 ntimeout.it_value.tv_usec = 0;
596
597                 setitimer(ITIMER_REAL,&ntimeout,NULL);
598                 signal(SIGALRM, donothing);
599                 pause();
600                 signal(SIGALRM, SIG_IGN);
601 #endif
602 #else /* EMX */
603                 signal(SIGALRM, donothing);
604                 _beginthread(itimerthread, NULL, 32768, NULL);
605                 pause();
606                 signal(SIGALRM, SIG_IGN);
607 #endif /* ! EMX */
608                 if (lastsig == SIGUSR1
609                         || ((poll_interval && !getuid()) && lastsig == SIGHUP))
610                 {
611 #ifdef SYS_SIGLIST_DECLARED
612                     error(0, 0, "awakened by %s", sys_siglist[lastsig]);
613 #else
614                     error(0, 0, "awakened by signal %d", lastsig);
615 #endif
616                 }
617             }
618
619             /* now lock out interrupts again */
620             signal(SIGUSR1, SIG_IGN);
621             if (!getuid())
622                 signal(SIGHUP, SIG_IGN);
623
624             if (outlevel == O_VERBOSE)
625             {
626                 time_t  now;
627
628                 time(&now);
629                 fprintf(stderr, "fetchmail: awakened at %s", ctime(&now));
630             }
631         }
632     } while
633         (poll_interval);
634
635     if (outlevel == O_VERBOSE)
636         fprintf(stderr,"fetchmail: normal termination, status %d\n",
637                 successes ? PS_SUCCESS : querystatus);
638
639     termhook(0);
640     exit(successes ? PS_SUCCESS : querystatus);
641 }
642
643 static int load_params(int argc, char **argv, int optind)
644 {
645     int implicitmode, st;
646     struct passwd *pw;
647     struct query def_opts, *ctl;
648
649     memset(&def_opts, '\0', sizeof(struct query));
650     def_opts.smtp_socket = -1;
651     def_opts.smtpaddress = (char *)0;
652
653     def_opts.server.protocol = P_AUTO;
654     def_opts.server.timeout = CLIENT_TIMEOUT;
655     def_opts.remotename = user;
656     def_opts.expunge = 1;
657
658     /* this builds the host list */
659     if (prc_parse_file(rcfile, !versioninfo) != 0)
660         exit(PS_SYNTAX);
661
662     if ((implicitmode = (optind >= argc)))
663     {
664         for (ctl = querylist; ctl; ctl = ctl->next)
665             ctl->active = TRUE;
666     }
667     else
668         for (; optind < argc; optind++) 
669         {
670             /*
671              * If hostname corresponds to a host known from the rc file,
672              * simply declare it active.  Otherwise synthesize a host
673              * record from command line and defaults
674              */
675             for (ctl = querylist; ctl; ctl = ctl->next)
676                 if (!strcmp(ctl->server.pollname, argv[optind])
677                         || str_in_list(&ctl->server.akalist, argv[optind]))
678                     goto foundit;
679
680             ctl = hostalloc(&cmd_opts);
681             ctl->server.pollname = xstrdup(argv[optind]);
682
683         foundit:
684             ctl->active = TRUE;
685         }
686
687     /* if there's a defaults record, merge it and lose it */ 
688     if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
689     {
690         for (ctl = querylist->next; ctl; ctl = ctl->next)
691             optmerge(ctl, querylist);
692         querylist = querylist->next;
693     }
694
695     /* don't allow a defaults record after the first */
696     for (ctl = querylist; ctl; ctl = ctl->next)
697         if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
698             exit(PS_SYNTAX);
699
700     /* merge in wired defaults, do sanity checks and prepare internal fields */
701     for (ctl = querylist; ctl; ctl = ctl->next)
702     {
703         if (ctl->active && !(implicitmode && ctl->server.skip))
704         {
705             /* merge in defaults */
706             optmerge(ctl, &def_opts);
707
708             /* make sure we have a nonempty host list to forward to */
709             if (!ctl->smtphunt)
710                 save_str(&ctl->smtphunt, FALSE, fetchmailhost);
711
712             /* keep lusers from shooting themselves in the foot :-) */
713             if (poll_interval && ctl->limit)
714             {
715                 fprintf(stderr,"fetchmail: you'd never see large messages!\n");
716                 exit(PS_SYNTAX);
717             }
718
719             /* if `user' doesn't name a real local user, try to run as root */
720             if ((pw = getpwnam(user)) == (struct passwd *)NULL)
721                 ctl->uid = 0;
722             else
723                 ctl->uid = pw->pw_uid;  /* for local delivery via MDA */
724             if (!ctl->localnames)       /* for local delivery via SMTP */
725                 save_str_pair(&ctl->localnames, user, NULL);
726
727             /* this code enables flags to be turned off */
728 #define DEFAULT(flag, dflt)     if (flag == FLAG_TRUE)\
729                                         flag = TRUE;\
730                                 else if (flag == FLAG_FALSE)\
731                                         flag = FALSE;\
732                                 else\
733                                         flag = (dflt)
734             DEFAULT(ctl->keep, FALSE);
735             DEFAULT(ctl->fetchall, FALSE);
736             DEFAULT(ctl->flush, FALSE);
737             DEFAULT(ctl->rewrite, TRUE);
738             DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL)); 
739             DEFAULT(ctl->forcecr, FALSE);
740             DEFAULT(ctl->pass8bits, FALSE);
741             DEFAULT(ctl->dropstatus, FALSE);
742             DEFAULT(ctl->server.dns, TRUE);
743             DEFAULT(ctl->server.uidl, FALSE);
744 #undef DEFAULT
745
746 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
747             /* can't handle multidrop mailboxes unless we can do DNS lookups */
748             if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
749             {
750                 ctl->server.dns = FALSE;
751                 fprintf(stderr, "fetchmail: warning: no DNS available to check multidrop fetches from %s\n", ctl->server.pollname);
752             }
753 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
754
755             /*
756              *
757              * Compute the true name of the mailserver host.  
758              * There are two clashing cases here:
759              *
760              * (1) The poll name is a label, possibly on one of several
761              *     poll configurations for the same host.  In this case 
762              *     the `via' option will be present and give the true name.
763              *
764              * (2) The poll name is the true one, the via name is 
765              *     localhost.   This is going to be typical for ssh-using
766              *     configurations.
767              *
768              * We're going to assume the via name is true unless it's
769              * localhost.
770              *
771              * Each poll cycle, if we've got DNS, we'll try to canonicalize
772              * the name.  This will function as a probe to ensure the
773              * host's nameserver is up.
774              */
775             if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
776                 ctl->server.queryname = xstrdup(ctl->server.via);
777             else
778                 ctl->server.queryname = xstrdup(ctl->server.pollname);
779             ctl->server.truename = xstrdup(ctl->server.queryname);
780
781             /* if no folders were specified, set up the null one as default */
782             if (!ctl->mailboxes)
783                 save_str(&ctl->mailboxes, -1, (char *)NULL);
784
785             /* maybe user overrode timeout on command line? */
786             if (ctl->server.timeout == -1)      
787                 ctl->server.timeout = CLIENT_TIMEOUT;
788
789 #if !INET6
790             /* sanity checks */
791             if (ctl->server.port < 0)
792             {
793                 (void) fprintf(stderr,
794                                "%s configuration invalid, port number cannot be negative",
795                                ctl->server.pollname);
796                 exit(PS_SYNTAX);
797             }
798             if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
799             {
800                 (void) fprintf(stderr,
801                                "%s configuration invalid, RPOP requires a privileged port",
802                                ctl->server.pollname);
803                 exit(PS_SYNTAX);
804             }
805 #endif /* !INET6 */
806         }
807     }
808
809     /* initialize UID handling */
810     if (!versioninfo && (st = prc_filecheck(idfile)) != 0)
811         exit(st);
812 #ifdef POP3_ENABLE
813     else
814         initialize_saved_lists(querylist, idfile);
815 #endif /* POP3_ENABLE */
816
817     /* if cmd_logfile was explicitly set, use it to override logfile */
818     if (cmd_logfile)
819         logfile = cmd_logfile;
820
821     /* likewise for poll_interval */
822     if (cmd_daemon >= 0)
823         poll_interval = cmd_daemon;
824
825     /* check and daemon options are not compatible */
826     if (check_only && poll_interval)
827         poll_interval = 0;
828     return(implicitmode);
829 }
830
831 void termhook(int sig)
832 /* to be executed on normal or signal-induced termination */
833 {
834     struct query        *ctl;
835
836     /*
837      * Sending SMTP QUIT on signal is theoretically nice, but led to a 
838      * subtle bug.  If fetchmail was terminated by signal while it was 
839      * shipping message text, it would hang forever waiting for a
840      * command acknowledge.  In theory we could enable the QUIT
841      * only outside of the message send.  In practice, we don't
842      * care.  All mailservers hang up on a dropped TCP/IP connection
843      * anyway.
844      */
845
846     if (sig != 0)
847         error(0, 0, "terminated with signal %d", sig);
848     else
849         /* terminate all SMTP connections cleanly */
850         for (ctl = querylist; ctl; ctl = ctl->next)
851             if (ctl->smtp_socket != -1)
852                 SMTP_quit(ctl->smtp_socket);
853
854 #ifdef POP3_ENABLE
855     if (!check_only)
856         write_saved_lists(querylist, idfile);
857 #endif /* POP3_ENABLE */
858
859     /* 
860      * Craig Metz, the RFC1938 one-time-password guy, points out:
861      * "Remember that most kernels don't zero pages before handing them to the
862      * next process and many kernels share pages between user and kernel space.
863      * You'd be very surprised what you can find from a short program to do a
864      * malloc() and then dump the contents of the pages you got. By zeroing
865      * the secrets at end of run (earlier if you can), you make sure the next
866      * guy can't get the password/pass phrase."
867      *
868      * Right you are, Craig!
869      */
870     for (ctl = querylist; ctl; ctl = ctl->next)
871         if (ctl->password)
872           memset(ctl->password, '\0', strlen(ctl->password));
873
874 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
875     unlockit();
876 #endif
877
878     exit(successes ? PS_SUCCESS : querystatus);
879 }
880
881 /*
882  * Sequence of protocols to try when autoprobing, most capable to least.
883  */
884 static const int autoprobe[] = 
885 {
886 #ifdef IMAP_ENABLE
887     P_IMAP,
888 #endif /* IMAP_ENABLE */
889 #ifdef POP3_ENABLE
890     P_POP3,
891 #endif /* POP3_ENABLE */
892 #ifdef POP2_ENABLE
893     P_POP2
894 #endif /* POP2_ENABLE */
895 };
896
897 static int query_host(struct query *ctl)
898 /* perform fetch transaction with single host */
899 {
900     int i, st;
901
902     if (outlevel == O_VERBOSE)
903     {
904         time_t now;
905
906         time(&now);
907         fprintf(stderr, "fetchmail: %s querying %s (protocol %s) at %s",
908             RELEASE_ID,
909             ctl->server.pollname, showproto(ctl->server.protocol), ctime(&now));
910     }
911     switch (ctl->server.protocol) {
912     case P_AUTO:
913         for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
914         {
915             ctl->server.protocol = autoprobe[i];
916             if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
917                 break;
918         }
919         ctl->server.protocol = P_AUTO;
920         return(st);
921         break;
922     case P_POP2:
923 #ifdef POP2_ENABLE
924         return(doPOP2(ctl));
925 #else
926         fprintf(stderr, "POP2 support is not configured.\n");
927         return(PS_PROTOCOL);
928 #endif /* POP2_ENABLE */
929         break;
930     case P_POP3:
931     case P_APOP:
932     case P_RPOP:
933 #ifdef POP3_ENABLE
934         return(doPOP3(ctl));
935 #else
936         fprintf(stderr, "POP3 support is not configured.\n");
937         return(PS_PROTOCOL);
938 #endif /* POP3_ENABLE */
939         break;
940     case P_IMAP:
941     case P_IMAP_K4:
942     case P_IMAP_GSS:
943 #ifdef IMAP_ENABLE
944         return(doIMAP(ctl));
945 #else
946         fprintf(stderr, "IMAP support is not configured.\n");
947         return(PS_PROTOCOL);
948 #endif /* IMAP_ENABLE */
949         break;
950     case P_ETRN:
951 #ifndef ETRN_ENABLE
952         fprintf(stderr, "ETRN support is not configured.\n");
953         return(PS_PROTOCOL);
954 #else
955 #ifdef HAVE_GETHOSTBYNAME
956         return(doETRN(ctl));
957 #else
958         fprintf(stderr, "Cannot support ETRN without gethostbyname(2).\n");
959         return(PS_PROTOCOL);
960 #endif /* HAVE_GETHOSTBYNAME */
961 #endif /* ETRN_ENABLE */
962     default:
963         error(0, 0, "unsupported protocol selected.");
964         return(PS_PROTOCOL);
965     }
966 }
967
968 void dump_params (struct query *ctl)
969 /* display query parameters in English */
970 {
971     printf("Options for retrieving from %s@%s:\n",
972            ctl->remotename, visbuf(ctl->server.pollname));
973
974     if (ctl->server.via)
975         printf("  Mail will be retrieved via %s\n", ctl->server.via);
976
977     if (ctl->server.interval)
978         printf("  Poll of this server will occur every %d intervals.\n",
979                ctl->server.interval);
980     if (ctl->server.truename)
981         printf("  True name of server is %s.\n", ctl->server.truename);
982     if (ctl->server.skip || outlevel == O_VERBOSE)
983         printf("  This host will%s be queried when no host is specified.\n",
984                ctl->server.skip ? " not" : "");
985     if (!ctl->password)
986         printf("  Password will be prompted for.\n");
987     else if (outlevel == O_VERBOSE)
988         if (ctl->server.protocol == P_APOP)
989             printf("  APOP secret = '%s'.\n", visbuf(ctl->password));
990         else if (ctl->server.protocol == P_RPOP)
991             printf("  RPOP id = '%s'.\n", visbuf(ctl->password));
992         else
993             printf("  Password = '%s'.\n", visbuf(ctl->password));
994     if (ctl->server.protocol == P_POP3 
995 #if INET6
996                 && !strcmp(ctl->server.service, KPOP_PORT)
997 #else /* INET6 */
998                 && ctl->server.port == KPOP_PORT
999 #endif /* INET6 */
1000                 && ctl->server.preauthenticate == A_KERBEROS_V4)
1001         printf("  Protocol is KPOP");
1002     else
1003         printf("  Protocol is %s", showproto(ctl->server.protocol));
1004 #if INET6
1005     if (ctl->server.service)
1006         printf(" (using service %s)", ctl->server.service);
1007     if (ctl->server.netsec)
1008         printf(" (using network security options %s)", ctl->server.netsec);
1009 #else /* INET6 */
1010     if (ctl->server.port)
1011         printf(" (using port %d)", ctl->server.port);
1012 #endif /* INET6 */
1013     else if (outlevel == O_VERBOSE)
1014         printf(" (using default port)");
1015     if (ctl->server.uidl)
1016         printf(" (forcing UIDL use)");
1017     putchar('.');
1018     putchar('\n');
1019     if (ctl->server.preauthenticate == A_KERBEROS_V4)
1020             printf("  Kerberos V4 preauthentication enabled.\n");
1021     if (ctl->server.timeout > 0)
1022         printf("  Server nonresponse timeout is %d seconds", ctl->server.timeout);
1023     if (ctl->server.timeout ==  CLIENT_TIMEOUT)
1024         printf(" (default).\n");
1025     else
1026         printf(".\n");
1027
1028     if (!ctl->mailboxes->id)
1029         printf("  Default mailbox selected.\n");
1030     else
1031     {
1032         struct idlist *idp;
1033
1034         printf("  Selected mailboxes are:");
1035         for (idp = ctl->mailboxes; idp; idp = idp->next)
1036             printf(" %s", idp->id);
1037         printf("\n");
1038     }
1039     printf("  %s messages will be retrieved (--all %s).\n",
1040            ctl->fetchall ? "All" : "Only new",
1041            ctl->fetchall ? "on" : "off");
1042     printf("  Fetched messages will%s be kept on the server (--keep %s).\n",
1043            ctl->keep ? "" : " not",
1044            ctl->keep ? "on" : "off");
1045     printf("  Old messages will%s be flushed before message retrieval (--flush %s).\n",
1046            ctl->flush ? "" : " not",
1047            ctl->flush ? "on" : "off");
1048     printf("  Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
1049            ctl->rewrite ? "en" : "dis",
1050            ctl->rewrite ? "off" : "on");
1051     printf("  Carriage-return stripping is %sabled (stripcr %s).\n",
1052            ctl->stripcr ? "en" : "dis",
1053            ctl->stripcr ? "on" : "off");
1054     printf("  Carriage-return forcing is %sabled (forcecr %s).\n",
1055            ctl->forcecr ? "en" : "dis",
1056            ctl->forcecr ? "on" : "off");
1057     printf("  Interpretation of Content-Transfer-Encoding is %sabled (pass8bits %s).\n",
1058            ctl->pass8bits ? "dis" : "en",
1059            ctl->pass8bits ? "on" : "off");
1060     printf("  Nonempty Status lines will be %s (dropstatus %s)\n",
1061            ctl->dropstatus ? "discarded" : "kept",
1062            ctl->dropstatus ? "on" : "off");
1063     if (NUM_NONZERO(ctl->limit))
1064         printf("  Message size limit is %d bytes (--limit %d).\n", 
1065                ctl->limit, ctl->limit);
1066     else if (outlevel == O_VERBOSE)
1067         printf("  No message size limit (--limit 0).\n");
1068     if (NUM_NONZERO(ctl->fetchlimit))
1069         printf("  Received-message limit is %d (--fetchlimit %d).\n",
1070                ctl->fetchlimit, ctl->fetchlimit);
1071     else if (outlevel == O_VERBOSE)
1072         printf("  No received-message limit (--fetchlimit 0).\n");
1073     if (NUM_NONZERO(ctl->batchlimit))
1074         printf("  SMTP message batch limit is %d.\n", ctl->batchlimit);
1075     else if (outlevel == O_VERBOSE)
1076         printf("  No SMTP message batch limit (--batchlimit 0).\n");
1077     if (ctl->server.protocol == P_IMAP)
1078         if (NUM_NONZERO(ctl->expunge))
1079             printf("  Deletion interval between expunges is %d (--expunge %d).\n", ctl->expunge, ctl->expunge);
1080         else if (outlevel == O_VERBOSE)
1081             printf("  No expunges (--expunge 0).\n");
1082     if (ctl->mda)
1083         printf("  Messages will be delivered with '%s.'\n", visbuf(ctl->mda));
1084     else
1085     {
1086         struct idlist *idp;
1087
1088         printf("  Messages will be SMTP-forwarded to:");
1089         for (idp = ctl->smtphunt; idp; idp = idp->next)
1090             if (ctl->server.protocol != P_ETRN || idp->val.num)
1091             {
1092                 printf(" %s", idp->id);
1093                 if (!idp->val.num)
1094                     printf(" (default)");
1095             }
1096         printf("\n");
1097         if (ctl->smtpaddress)
1098             printf("  Host part of MAIL FROM line will be %s\n",
1099                    ctl->smtpaddress);
1100     }
1101     if (ctl->preconnect)
1102         printf("  Server connection will be brought up with '%s.'\n",
1103                visbuf(ctl->preconnect));
1104     else if (outlevel == O_VERBOSE)
1105         printf("  No pre-connection command.\n");
1106     if (ctl->postconnect)
1107         printf("  Server connection will be taken down with '%s.'\n",
1108                visbuf(ctl->postconnect));
1109     else if (outlevel == O_VERBOSE)
1110         printf("  No post-connection command.\n");
1111     if (!ctl->localnames)
1112         printf("  No localnames declared for this host.\n");
1113     else
1114     {
1115         struct idlist *idp;
1116         int count = 0;
1117
1118         for (idp = ctl->localnames; idp; idp = idp->next)
1119             ++count;
1120
1121         if (count > 1 || ctl->wildcard)
1122             printf("  Multi-drop mode: ");
1123         else
1124             printf("  Single-drop mode: ");
1125
1126         printf("%d local name(s) recognized.\n", count);
1127         if (outlevel == O_VERBOSE)
1128         {
1129             for (idp = ctl->localnames; idp; idp = idp->next)
1130                 if (idp->val.id2)
1131                     printf("\t%s -> %s\n", idp->id, idp->val.id2);
1132                 else
1133                     printf("\t%s\n", idp->id);
1134             if (ctl->wildcard)
1135                 fputs("*\n", stdout);
1136         }
1137
1138         if (count > 1 || ctl->wildcard)
1139         {
1140             printf("  DNS lookup for multidrop addresses is %sabled.\n",
1141                    ctl->server.dns ? "en" : "dis");
1142
1143             if (ctl->server.envelope == STRING_DISABLED)
1144                 printf("  Envelope-address routing is disabled\n");
1145             else
1146             {
1147                 printf("  Envelope header is assumed to be: %s\n",
1148                        ctl->server.envelope ? ctl->server.envelope:"Received");
1149                 if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1150                     printf("  Number of envelope header to be parsed: %d\n",
1151                            ctl->server.envskip);
1152                 if (ctl->server.qvirtual)
1153                     printf("  Prefix %s will be removed from user id\n",
1154                            ctl->server.qvirtual);
1155                 else if (outlevel >= O_VERBOSE) 
1156                     printf("  No prefix stripping\n");
1157             }
1158
1159             if (ctl->server.akalist)
1160             {
1161                 struct idlist *idp;
1162
1163                 printf("  Predeclared mailserver aliases:");
1164                 for (idp = ctl->server.akalist; idp; idp = idp->next)
1165                     printf(" %s", idp->id);
1166                 putchar('\n');
1167             }
1168             if (ctl->server.localdomains)
1169             {
1170                 struct idlist *idp;
1171
1172                 printf("  Local domains:");
1173                 for (idp = ctl->server.localdomains; idp; idp = idp->next)
1174                     printf(" %s", idp->id);
1175                 putchar('\n');
1176             }
1177         }
1178     }
1179 #ifdef  linux
1180     if (ctl->server.interface)
1181         printf("  Connection must be through interface %s.\n", ctl->server.interface);
1182     else if (outlevel == O_VERBOSE)
1183         printf("  No interface requirement specified.\n");
1184     if (ctl->server.monitor)
1185         printf("  Polling loop will monitor %s.\n", ctl->server.monitor);
1186     else if (outlevel == O_VERBOSE)
1187         printf("  No monitor interface specified.\n");
1188 #endif
1189
1190     if (ctl->server.protocol > P_POP2)
1191         if (!ctl->oldsaved)
1192             printf("  No UIDs saved from this host.\n");
1193         else
1194         {
1195             struct idlist *idp;
1196             int count = 0;
1197
1198             for (idp = ctl->oldsaved; idp; idp = idp->next)
1199                 ++count;
1200
1201             printf("  %d UIDs saved.\n", count);
1202             if (outlevel == O_VERBOSE)
1203                 for (idp = ctl->oldsaved; idp; idp = idp->next)
1204                     fprintf(stderr, "\t%s\n", idp->id);
1205         }
1206 }
1207
1208 /* fetchmail.c ends here */