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