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