2 * fetchmail.c -- main driver module for fetchmail
4 * For license terms, see the file COPYING in this directory.
10 #if defined(STDC_HEADERS)
13 #if defined(HAVE_UNISTD_H)
18 #if defined(HAVE_SYSLOG)
24 #include <sys/types.h>
27 #include <sys/resource.h>
28 #endif /* HAVE_SETRLIMIT */
29 #ifdef HAVE_SYS_WAIT_H
33 #ifdef HAVE_GETHOSTBYNAME
35 #endif /* HAVE_GETHOSTBYNAME */
37 #include "fetchmail.h"
44 #define ENETUNREACH 128 /* Interactive doesn't know this */
45 #endif /* ENETUNREACH */
47 /* prototypes for internal functions */
48 static int load_params(int, char **, int);
49 static void dump_params (struct runctl *runp, struct query *, flag implicit);
50 static int query_host(struct query *);
52 /* controls the detail level of status/progress messages written to stderr */
53 int outlevel; /* see the O_.* constants above */
55 /* miscellaneous global controls */
56 struct runctl run; /* global controls for this run */
57 flag nodetach; /* if TRUE, don't detach daemon process */
58 flag quitmode; /* if --quit was set */
59 flag check_only; /* if --probe was set */
60 flag versioninfo; /* emit only version info */
61 char *user; /* the name of the invoking user */
62 char *home; /* invoking user's home directory */
63 char *program_name; /* the name to prefix error messages with */
64 flag configdump; /* dump control blocks for configurator */
65 const char *fetchmailhost; /* either `localhost' or the host's FQDN */
70 #endif /* NET_SECURITY */
72 static char *lockfile; /* name of lockfile */
73 static int querystatus; /* status of query */
74 static int successes; /* count number of successful polls */
75 static int lastsig; /* last signal received */
76 static struct runctl cmd_run; /* global options set from command line */
78 static void termhook(int); /* forward declaration of exit hook */
81 #define SLEEP_WITH_ALARM
84 #ifdef SLEEP_WITH_ALARM
86 * The function of this variable is to remove the window during which a
87 * SIGALRM can hose the code (ALARM is triggered *before* pause() is called).
88 * This is a bit of a kluge; the real right thing would use sigprocmask(),
90 * This work around lets the interval timer trigger the first alarm after the
91 * required interval and will then generate alarms all 5 seconds, until it
92 * is certain, that the critical section (ie., the window) is left.
94 #if defined(STDC_HEADERS)
95 static sig_atomic_t alarm_latch = FALSE;
97 /* assume int can be written in one atomic operation on non ANSI-C systems */
98 static int alarm_latch = FALSE;
101 RETSIGTYPE gotsigalrm(sig)
104 signal(sig, gotsigalrm);
108 #endif /* SLEEP_WITH_ALARM */
110 RETSIGTYPE donothing(int sig) {signal(sig, donothing); lastsig = sig;}
113 static void unlockit(int n, void *p)
115 static void unlockit(void)
117 /* must-do actions for exit (but we can't count on being able to do malloc) */
123 /* Various EMX-specific definitions */
125 void itimerthread(void* dummy) {
126 if (outlevel >= O_VERBOSE)
127 fprintf(stderr, "fetchmail: thread sleeping for %d sec.\n", poll_interval);
129 _sleep2(poll_interval*1000);
130 kill((getpid()), SIGALRM);
135 int main (int argc, char **argv)
137 int st, bkgd = FALSE;
138 int parsestatus, implicitmode = FALSE;
141 netrc_entry *netrc_list;
142 char *netrc_file, *tmpbuf;
145 envquery(argc, argv);
147 #define IDFILE_NAME ".fetchids"
148 run.idfile = (char *) xmalloc(strlen(home)+strlen(IDFILE_NAME)+2);
149 strcpy(run.idfile, home);
150 strcat(run.idfile, "/");
151 strcat(run.idfile, IDFILE_NAME);
155 if ((parsestatus = parsecmdline(argc,argv, &cmd_run, &cmd_opts)) < 0)
158 /* this hint to stdio should help messages come out in the right order */
159 setvbuf(stdout, NULL, _IOLBF, MSGBUFSIZE);
163 printf("This is fetchmail release %s", RELEASE_ID);
166 #endif /* POP2_ENABLE */
169 #endif /* POP3_ENABLE */
172 #endif /* IMAP_ENABLE */
178 #endif /* RPA_ENABLE */
181 #endif /* SDPS_ENABLE */
184 #endif /* ETRN_ENABLE */
193 #endif /* NET_SECURITY */
196 /* this is an attempt to help remote debugging */
200 /* avoid parsing the config file if all we're doing is killing a daemon */
201 if (!(quitmode && argc == 2))
202 implicitmode = load_params(argc, argv, optind);
204 /* set up to do lock protocol */
205 #define FETCHMAIL_PIDFILE "fetchmail.pid"
206 xalloca(tmpbuf, char *, strlen(home) + strlen(FETCHMAIL_PIDFILE) + 3);
208 sprintf(tmpbuf, "%s/%s", PID_DIR, FETCHMAIL_PIDFILE);
210 strcpy(tmpbuf, home);
211 strcat(tmpbuf, "/.");
212 strcat(tmpbuf, FETCHMAIL_PIDFILE);
214 #undef FETCHMAIL_PIDFILE
216 /* perhaps we just want to check options? */
219 printf("Taking options from command line");
220 if (access(rcfile, 0))
223 printf(" and %s\n", rcfile);
224 if (outlevel >= O_VERBOSE)
225 printf("Lockfile at %s\n", tmpbuf);
227 if (querylist == NULL)
228 (void) fprintf(stderr,
229 "No mailservers set up -- perhaps %s is missing?\n", rcfile);
231 dump_params(&run, querylist, implicitmode);
235 /* dump options as a Python dictionary, for configurator use */
238 dump_config(&run, querylist);
242 /* check for another fetchmail running concurrently */
244 if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
246 fprintf(stderr,"fetchmail: cannot allocate memory for lock name.\n");
250 (void) strcpy(lockfile, tmpbuf);
251 if ((lockfp = fopen(lockfile, "r")) != NULL )
253 bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
255 if (kill(pid, 0) == -1) {
256 fprintf(stderr,"fetchmail: removing stale lockfile\n");
264 /* if no mail servers listed and nothing in background, we're done */
265 if (!(quitmode && argc == 2) && pid == -1 && querylist == NULL) {
266 (void)fputs("fetchmail: no mailservers have been specified.\n",stderr);
270 /* perhaps user asked us to kill the other fetchmail */
275 fprintf(stderr,"fetchmail: no other fetchmail is running\n");
279 else if (kill(pid, SIGTERM) < 0)
281 fprintf(stderr,"fetchmail: error killing %s fetchmail at %d; bailing out.\n",
282 bkgd ? "background" : "foreground", pid);
287 fprintf(stderr,"fetchmail: %s fetchmail at %d killed.\n",
288 bkgd ? "background" : "foreground", pid);
297 /* another fetchmail is running -- wake it up or die */
303 "fetchmail: can't check mail while another fetchmail to same host is running.\n");
306 else if (!implicitmode)
309 "fetchmail: can't poll specified hosts with another fetchmail running at %d.\n",
316 "fetchmail: another foreground fetchmail is running at %d.\n",
323 "fetchmail: can't accept options while a background fetchmail is running.\n");
326 else if (kill(pid, SIGUSR1) == 0)
329 "fetchmail: background fetchmail at %d awakened.\n",
336 * Should never happen -- possible only if a background fetchmail
337 * croaks after the first kill probe above but before the
338 * SIGUSR1/SIGHUP transmission.
341 "fetchmail: elder sibling at %d died mysteriously.\n",
343 return(PS_UNDEFINED);
347 /* parse the ~/.netrc file (if present) for future password lookups. */
348 xalloca(netrc_file, char *, strlen (home) + 8);
349 strcpy (netrc_file, home);
350 strcat (netrc_file, "/.netrc");
351 netrc_list = parse_netrc(netrc_file);
353 #ifdef HAVE_SETRLIMIT
355 * Before getting passwords, disable core dumps unless -v -d0 mode is on.
356 * Core dumps could otherwise contain passwords to be scavenged by a
359 if (outlevel < O_VERBOSE || run.poll_interval > 0)
361 struct rlimit corelimit;
362 corelimit.rlim_cur = 0;
363 corelimit.rlim_max = 0;
364 setrlimit(RLIMIT_CORE, &corelimit);
366 #endif /* HAVE_SETRLIMIT */
368 /* pick up interactively any passwords we need but don't have */
369 for (ctl = querylist; ctl; ctl = ctl->next)
371 ctl->authfailcount = 0;
373 if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
375 if (ctl->server.preauthenticate == A_KERBEROS_V4 ||
376 ctl->server.preauthenticate == A_KERBEROS_V5 ||
378 ctl->server.protocol == P_IMAP_GSS ||
380 ctl->server.protocol == P_IMAP_K4)
381 /* Server won't care what the password is, but there
382 must be some non-null string here. */
383 ctl->password = ctl->remotename;
386 /* look up the host and account in the .netrc file. */
387 netrc_entry *p = search_netrc(netrc_list,ctl->server.pollname);
388 while (p && strcmp(p->account, ctl->remotename))
389 p = search_netrc(p->next, ctl->remotename);
391 /* if we find a matching entry with a password, use it */
392 if (p && p->password)
393 ctl->password = xstrdup(p->password);
396 if (ctl->server.protocol != P_ETRN && ctl->server.protocol != P_IMAP_K4
398 && ctl->server.protocol != P_IMAP_GSS
402 #define PASSWORD_PROMPT "Enter password for %s@%s: "
403 xalloca(tmpbuf, char *, strlen(PASSWORD_PROMPT) +
404 strlen(ctl->remotename) +
405 strlen(ctl->server.pollname) + 1);
406 (void) sprintf(tmpbuf, PASSWORD_PROMPT,
407 ctl->remotename, ctl->server.pollname);
408 ctl->password = xstrdup((char *)getpassword(tmpbuf));
409 #undef PASSWORD_PROMPT
415 * Maybe time to go to demon mode...
417 #if defined(HAVE_SYSLOG)
420 openlog(program_name, LOG_PID, LOG_MAIL);
425 error_init((run.poll_interval == 0 || nodetach) && !run.logfile);
427 if (run.poll_interval)
430 daemonize(run.logfile, termhook);
431 error( 0, 0, "starting fetchmail %s daemon ", RELEASE_ID);
434 * We'll set up a handler for these when we're sleeping,
435 * but ignore them otherwise so as not to interrupt a poll.
437 signal(SIGUSR1, SIG_IGN);
438 if (run.poll_interval && !getuid())
439 signal(SIGHUP, SIG_IGN);
442 /* beyond here we don't want more than one fetchmail running per user */
444 signal(SIGABRT, termhook);
445 signal(SIGINT, termhook);
446 signal(SIGTERM, termhook);
447 signal(SIGALRM, termhook);
448 signal(SIGPIPE, termhook);
449 signal(SIGQUIT, termhook);
451 /* here's the exclusion lock */
452 if ((lockfp = fopen(lockfile,"w")) != NULL) {
453 fprintf(lockfp,"%d",getpid());
454 if (run.poll_interval)
455 fprintf(lockfp," %d", run.poll_interval);
462 on_exit(unlockit, (char *)NULL);
467 * Query all hosts. If there's only one, the error return will
468 * reflect the status of that transaction.
471 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
473 * This was an efficiency hack that backfired. The theory
474 * was that using TCP/IP for DNS queries would get us better
475 * reliability and shave off some per-UDP-packet costs.
476 * Unfortunately it interacted badly with diald, which effectively
477 * filters out DNS queries over TCP/IP for reasons having to do
478 * with some obscure kernel problem involving bootstrapping of
479 * dynamically-addressed links. I don't understand this mess
480 * and don't want to, so it's "See ya!" to this hack.
482 sethostent(TRUE); /* use TCP/IP for mailserver queries */
483 #endif /* HAVE_RES_SEARCH */
486 for (ctl = querylist; ctl; ctl = ctl->next)
488 if (ctl->authfailcount)
491 "poll of %s skipped until authentication is unwedged",
492 ctl->server.pollname);
495 if (ctl->active && !(implicitmode && ctl->server.skip))
497 /* check skip interval first so that it counts all polls */
498 if (run.poll_interval && ctl->server.interval)
500 if (ctl->server.poll_count++ % ctl->server.interval)
502 if (outlevel >= O_VERBOSE)
504 "interval not reached, not querying %s",
505 ctl->server.pollname);
510 #if defined(linux) && !INET6
511 /* interface_approve() does its own error logging */
512 if (!interface_approve(&ctl->server))
514 #endif /* defined(linux) && !INET6 */
516 querystatus = query_host(ctl);
518 if (querystatus == PS_SUCCESS)
523 update_str_lists(ctl);
525 /* Save UID list to prevent re-fetch in case fetchmail
526 recover from crash */
529 write_saved_lists(querylist, run.idfile);
530 if (outlevel >= O_DEBUG)
531 error(0, 0, "saved UID List");
533 #endif /* POP3_ENABLE */
535 else if (!check_only &&
536 ((querystatus!=PS_NOMAIL) || (outlevel==O_DEBUG)))
537 error(0, 0, "Query status=%d", querystatus);
539 #if defined(linux) && !INET6
540 if (ctl->server.monitor)
543 * Allow some time for the link to quiesce. One
544 * second is usually sufficient, three is safe.
545 * Note: this delay is important - don't remove!
548 interface_note_activity(&ctl->server);
550 #endif /* defined(linux) && !INET6 */
554 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
555 endhostent(); /* release TCP/IP connection to nameserver */
556 #endif /* HAVE_RES_SEARCH */
559 * Close all SMTP delivery sockets. For optimum performance
560 * we'd like to hold them open til end of run, but (1) this
561 * loses if our poll interval is longer than the MTA's inactivity
562 * timeout, and (2) some MTAs (like smail) don't deliver after
563 * each message, but rather queue up mail and wait to actually
564 * deliver it until the input socket is closed.
566 for (ctl = querylist; ctl; ctl = ctl->next)
567 if (ctl->smtp_socket != -1)
569 SMTP_quit(ctl->smtp_socket);
570 close(ctl->smtp_socket);
571 ctl->smtp_socket = -1;
575 * OK, we've polled. Now sleep.
577 if (run.poll_interval)
580 * Because passwords can expire, it may happen that *all*
581 * hosts are now out of the loop due to authfail
582 * conditions. If this happens daemon-mode fetchmail
583 * should softly and silently vanish away, rather than
584 * spinning uselessly.
588 for (ctl = querylist; ctl; ctl = ctl->next)
589 if (!ctl->authfailcount)
593 error(0, -1, "All authentications have failed. Exiting.");
597 if (outlevel >= O_VERBOSE)
598 error(0, -1, "fetchmail: sleeping at %s", rfc822timestamp());
601 * With this simple hack, we make it possible for a foreground
602 * fetchmail to wake up one in daemon mode. What we want is the
603 * side effect of interrupting any sleep that may be going on,
604 * forcing fetchmail to re-poll its hosts. The second line is
605 * for people who think all system daemons wake up on SIGHUP.
607 signal(SIGUSR1, donothing);
609 signal(SIGHUP, donothing);
612 * We can't use sleep(3) here because we need an alarm(3)
613 * equivalent in order to implement server nonresponse timeout.
614 * We'll just assume setitimer(2) is available since fetchmail
615 * has to have a BSDoid socket layer to work at all.
619 #ifdef SLEEP_WITH_ALARM /* not normally on */
621 * This code stopped working under glibc-2, apparently due
622 * to the change in signal(2) semantics. (The siginterrupt
623 * line, added later, should fix this problem.) John Stracke
624 * <francis@netscape.com> wrote:
626 * The problem seems to be that, after hitting the interval
627 * timer while talking to the server, the process no longer
628 * responds to SIGALRM. I put in printf()s to see when it
629 * reached the pause() for the poll interval, and I checked
630 * the return from setitimer(), and everything seemed to be
631 * working fine, except that the pause() just ignored SIGALRM.
632 * I thought maybe the itimer wasn't being fired, so I hit
633 * it with a SIGALRM from the command line, and it ignored
634 * that, too. SIGUSR1 woke it up just fine, and it proceeded
635 * to repoll--but, when the dummy server didn't respond, it
636 * never timed out, and SIGALRM wouldn't make it.
638 * (continued below...)
640 struct itimerval ntimeout;
642 ntimeout.it_interval.tv_sec = 5; /* repeat alarm every 5 secs */
643 ntimeout.it_interval.tv_usec = 0;
644 ntimeout.it_value.tv_sec = run.poll_interval;
645 ntimeout.it_value.tv_usec = 0;
647 siginterrupt(SIGALRM, 1);
649 signal(SIGALRM, gotsigalrm); /* first trap signals */
650 setitimer(ITIMER_REAL,&ntimeout,NULL); /* then start timer */
651 /* there is a very small window between the next two lines */
652 /* which could result in a deadlock. But this will now be */
653 /* caught by periodical alarms (see it_interval) */
657 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
658 ntimeout.it_value.tv_sec = ntimeout.it_value.tv_usec = 0;
659 setitimer(ITIMER_REAL,&ntimeout,NULL); /* now stop timer */
660 signal(SIGALRM, SIG_IGN);
663 * So the workaround I used is to make it sleep by using
664 * select() instead of setitimer()/pause(). select() is
665 * perfectly happy being called with a timeout and
666 * no file descriptors; it just sleeps until it hits the
667 * timeout. The only concern I had was that it might
668 * implement its timeout with SIGALRM--there are some
669 * Unices where this is done, because select() is a library
670 * function--but apparently not.
672 struct timeval timeout;
674 timeout.tv_sec = run.poll_interval;
677 select(0,0,0,0, &timeout);
681 signal(SIGALRM, gotsigalrm);
682 _beginthread(itimerthread, NULL, 32768, NULL);
683 /* see similar code above */
686 signal(SIGALRM, SIG_IGN);
688 if (lastsig == SIGUSR1
689 || ((run.poll_interval && !getuid()) && lastsig == SIGHUP))
691 #ifdef SYS_SIGLIST_DECLARED
692 error(0, 0, "awakened by %s", sys_siglist[lastsig]);
694 error(0, 0, "awakened by signal %d", lastsig);
699 /* now lock out interrupts again */
700 signal(SIGUSR1, SIG_IGN);
702 signal(SIGHUP, SIG_IGN);
704 if (outlevel >= O_VERBOSE)
705 error(0, -1, "awakened at %s", rfc822timestamp());
710 if (outlevel >= O_VERBOSE)
711 error(0, -1, "normal termination, status %d",
712 successes ? PS_SUCCESS : querystatus);
715 exit(successes ? PS_SUCCESS : querystatus);
718 static void optmerge(struct query *h2, struct query *h1, int force)
719 /* merge two options records */
722 * If force is off, modify h2 fields only when they're empty (treat h1
723 * as defaults). If force is on, modify each h2 field whenever h1
724 * is nonempty (treat h1 as an override).
726 #define LIST_MERGE(dstl, srcl) if (force ? !!srcl : !dstl) \
727 free_str_list(&dstl), \
728 append_str_list(&dstl, &srcl)
729 LIST_MERGE(h2->server.localdomains, h1->server.localdomains);
730 LIST_MERGE(h2->localnames, h1->localnames);
731 LIST_MERGE(h2->mailboxes, h1->mailboxes);
732 LIST_MERGE(h2->smtphunt, h1->smtphunt);
733 LIST_MERGE(h2->antispam, h1->antispam);
736 #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld
737 FLAG_MERGE(server.via);
738 FLAG_MERGE(server.protocol);
740 FLAG_MERGE(server.service);
741 FLAG_MERGE(server.netsec);
743 FLAG_MERGE(server.port);
745 FLAG_MERGE(server.interval);
746 FLAG_MERGE(server.preauthenticate);
747 FLAG_MERGE(server.timeout);
748 FLAG_MERGE(server.envelope);
749 FLAG_MERGE(server.envskip);
750 FLAG_MERGE(server.qvirtual);
751 FLAG_MERGE(server.skip);
752 FLAG_MERGE(server.dns);
753 FLAG_MERGE(server.checkalias);
754 FLAG_MERGE(server.uidl);
757 FLAG_MERGE(server.interface);
758 FLAG_MERGE(server.monitor);
759 FLAG_MERGE(server.interface_pair);
762 FLAG_MERGE(wildcard);
763 FLAG_MERGE(remotename);
764 FLAG_MERGE(password);
767 FLAG_MERGE(smtpaddress);
768 FLAG_MERGE(preconnect);
769 FLAG_MERGE(postconnect);
773 FLAG_MERGE(fetchall);
777 FLAG_MERGE(pass8bits);
778 FLAG_MERGE(dropstatus);
779 FLAG_MERGE(mimedecode);
781 FLAG_MERGE(warnings);
782 FLAG_MERGE(fetchlimit);
783 FLAG_MERGE(batchlimit);
786 FLAG_MERGE(properties);
790 static int load_params(int argc, char **argv, int optind)
792 int implicitmode, st;
794 struct query def_opts, *ctl;
796 memset(&def_opts, '\0', sizeof(struct query));
797 def_opts.smtp_socket = -1;
798 def_opts.smtpaddress = (char *)0;
799 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 571;
800 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 550;
801 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 501;
803 def_opts.server.protocol = P_AUTO;
804 def_opts.server.timeout = CLIENT_TIMEOUT;
805 def_opts.warnings = WARNING_INTERVAL;
806 def_opts.remotename = user;
807 def_opts.expunge = 1;
809 /* this builds the host list */
810 if (prc_parse_file(rcfile, !versioninfo) != 0)
813 if ((implicitmode = (optind >= argc)))
815 for (ctl = querylist; ctl; ctl = ctl->next)
819 for (; optind < argc; optind++)
821 flag predeclared = FALSE;
824 * If hostname corresponds to a host known from the rc file,
825 * simply declare it active. Otherwise synthesize a host
826 * record from command line and defaults
828 for (ctl = querylist; ctl; ctl = ctl->next)
829 if (!strcmp(ctl->server.pollname, argv[optind])
830 || str_in_list(&ctl->server.akalist, argv[optind], TRUE))
832 /* Is this correct? */
834 fprintf(stderr,"Warning: multiple mentions of host %s in config file\n",argv[optind]);
842 * Allocate and link record without copying in
843 * command-line args; we'll do that with the optmerge
846 ctl = hostalloc((struct query *)NULL);
848 ctl->server.pollname = xstrdup(argv[optind]);
850 ctl->server.lead_server = (struct hostdata *)NULL;
855 * If there's a defaults record, merge it and lose it.
857 if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
859 for (ctl = querylist->next; ctl; ctl = ctl->next)
860 optmerge(ctl, querylist, FALSE);
861 querylist = querylist->next;
864 /* don't allow a defaults record after the first */
865 for (ctl = querylist; ctl; ctl = ctl->next)
866 if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
869 /* use localhost if we never fetch the FQDN of this host */
870 fetchmailhost = "localhost";
872 /* merge in wired defaults, do sanity checks and prepare internal fields */
873 for (ctl = querylist; ctl; ctl = ctl->next)
875 if (configdump || (ctl->active && !(implicitmode && ctl->server.skip)))
877 /* merge in defaults */
878 optmerge(ctl, &def_opts, FALSE);
880 /* force command-line options */
881 optmerge(ctl, &cmd_opts, TRUE);
883 /* this code enables flags to be turned off */
884 #define DEFAULT(flag, dflt) if (flag == FLAG_TRUE)\
886 else if (flag == FLAG_FALSE)\
890 DEFAULT(ctl->keep, FALSE);
891 DEFAULT(ctl->fetchall, FALSE);
892 DEFAULT(ctl->flush, FALSE);
893 DEFAULT(ctl->rewrite, TRUE);
894 DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL));
895 DEFAULT(ctl->forcecr, FALSE);
896 DEFAULT(ctl->pass8bits, FALSE);
897 DEFAULT(ctl->dropstatus, FALSE);
898 DEFAULT(ctl->mimedecode, FALSE);
899 DEFAULT(ctl->server.dns, TRUE);
900 DEFAULT(ctl->server.uidl, FALSE);
901 DEFAULT(ctl->server.checkalias, FALSE);
905 * DNS support is required for some protocols.
907 * If we're using ETRN, the smtp hunt list is the list of
908 * systems we're polling on behalf of; these have to be
909 * fully-qualified domain names. The default for this list
910 * should be the FQDN of localhost.
912 * If we're using Kerberos for authentication, we need
913 * the FQDN in order to generate capability keys.
915 if (ctl->server.protocol == P_ETRN
916 || ctl->server.preauthenticate == A_KERBEROS_V4
917 || ctl->server.preauthenticate == A_KERBEROS_V5)
918 if (strcmp(fetchmailhost, "localhost") == 0)
919 fetchmailhost = host_fqdn();
922 * Make sure we have a nonempty host list to forward to.
925 save_str(&ctl->smtphunt, fetchmailhost, FALSE);
927 /* if `user' doesn't name a real local user, try to run as root */
928 if ((pw = getpwnam(user)) == (struct passwd *)NULL)
931 ctl->uid = pw->pw_uid; /* for local delivery via MDA */
932 if (!ctl->localnames) /* for local delivery via SMTP */
933 save_str_pair(&ctl->localnames, user, NULL);
935 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
936 /* can't handle multidrop mailboxes unless we can do DNS lookups */
937 if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
939 ctl->server.dns = FALSE;
940 fprintf(stderr, "fetchmail: warning: no DNS available to check multidrop fetches from %s\n", ctl->server.pollname);
942 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
946 * Compute the true name of the mailserver host.
947 * There are two clashing cases here:
949 * (1) The poll name is a label, possibly on one of several
950 * poll configurations for the same host. In this case
951 * the `via' option will be present and give the true name.
953 * (2) The poll name is the true one, the via name is
954 * localhost. This is going to be typical for ssh-using
957 * We're going to assume the via name is true unless it's
960 if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
961 ctl->server.queryname = xstrdup(ctl->server.via);
963 ctl->server.queryname = xstrdup(ctl->server.pollname);
966 * We may have to canonicalize the server truename for later use.
967 * Do this just once for each lead server, if necessary, in order
968 * to minimize DNS round trips.
970 if (ctl->server.lead_server)
971 ctl->server.truename = xstrdup(ctl->server.lead_server->truename);
972 #ifdef HAVE_GETHOSTBYNAME
973 else if (ctl->server.preauthenticate==A_KERBEROS_V4 ||
974 ctl->server.preauthenticate==A_KERBEROS_V5 ||
975 (ctl->server.dns && MULTIDROP(ctl)))
977 struct hostent *namerec;
979 /* compute the canonical name of the host */
981 namerec = gethostbyname(ctl->server.queryname);
982 if (namerec == (struct hostent *)NULL)
985 "couldn't find canonical DNS name of %s",
986 ctl->server.pollname);
990 ctl->server.truename=xstrdup((char *)namerec->h_name);
992 #endif /* HAVE_GETHOSTBYNAME */
994 ctl->server.truename = xstrdup(ctl->server.queryname);
996 /* if no folders were specified, set up the null one as default */
998 save_str(&ctl->mailboxes, (char *)NULL, 0);
1000 /* maybe user overrode timeout on command line? */
1001 if (ctl->server.timeout == -1)
1002 ctl->server.timeout = CLIENT_TIMEOUT;
1006 if (ctl->server.port < 0)
1008 (void) fprintf(stderr,
1009 "%s configuration invalid, port number cannot be negative",
1010 ctl->server.pollname);
1013 if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
1015 (void) fprintf(stderr,
1016 "%s configuration invalid, RPOP requires a privileged port",
1017 ctl->server.pollname);
1024 /* here's where we override globals */
1025 if (cmd_run.logfile)
1026 run.logfile = cmd_run.logfile;
1028 run.idfile = cmd_run.idfile;
1029 if (cmd_run.poll_interval >= 0)
1030 run.poll_interval = cmd_run.poll_interval;
1031 if (cmd_run.invisible)
1032 run.invisible = cmd_run.invisible;
1033 if (cmd_run.use_syslog)
1034 run.use_syslog = (cmd_run.use_syslog == FLAG_TRUE);
1036 /* check and daemon options are not compatible */
1037 if (check_only && run.poll_interval)
1038 run.poll_interval = 0;
1041 /* initialize UID handling */
1042 if (!versioninfo && (st = prc_filecheck(run.idfile, !versioninfo)) != 0)
1045 initialize_saved_lists(querylist, run.idfile);
1046 #endif /* POP3_ENABLE */
1049 * If the user didn't set a last-resort user to get misaddressed
1050 * multidrop mail, set an appropriate default here.
1052 if (!run.postmaster)
1053 if (getuid()) /* ordinary user */
1054 run.postmaster = user;
1056 run.postmaster = "postmaster";
1058 return(implicitmode);
1061 void termhook(int sig)
1062 /* to be executed on normal or signal-induced termination */
1067 * Sending SMTP QUIT on signal is theoretically nice, but led to a
1068 * subtle bug. If fetchmail was terminated by signal while it was
1069 * shipping message text, it would hang forever waiting for a
1070 * command acknowledge. In theory we could enable the QUIT
1071 * only outside of the message send. In practice, we don't
1072 * care. All mailservers hang up on a dropped TCP/IP connection
1077 error(0, 0, "terminated with signal %d", sig);
1079 /* terminate all SMTP connections cleanly */
1080 for (ctl = querylist; ctl; ctl = ctl->next)
1081 if (ctl->smtp_socket != -1)
1082 SMTP_quit(ctl->smtp_socket);
1086 write_saved_lists(querylist, run.idfile);
1087 #endif /* POP3_ENABLE */
1090 * Craig Metz, the RFC1938 one-time-password guy, points out:
1091 * "Remember that most kernels don't zero pages before handing them to the
1092 * next process and many kernels share pages between user and kernel space.
1093 * You'd be very surprised what you can find from a short program to do a
1094 * malloc() and then dump the contents of the pages you got. By zeroing
1095 * the secrets at end of run (earlier if you can), you make sure the next
1096 * guy can't get the password/pass phrase."
1098 * Right you are, Craig!
1100 for (ctl = querylist; ctl; ctl = ctl->next)
1102 memset(ctl->password, '\0', strlen(ctl->password));
1104 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
1108 exit(successes ? PS_SUCCESS : querystatus);
1112 * Sequence of protocols to try when autoprobing, most capable to least.
1114 static const int autoprobe[] =
1118 #endif /* IMAP_ENABLE */
1121 #endif /* POP3_ENABLE */
1124 #endif /* POP2_ENABLE */
1127 static int query_host(struct query *ctl)
1128 /* perform fetch transaction with single host */
1132 if (outlevel >= O_VERBOSE)
1137 error(0, -1, "fetchmail: %s querying %s (protocol %s) at %s",
1139 ctl->server.pollname, showproto(ctl->server.protocol), ctime(&now));
1141 switch (ctl->server.protocol) {
1143 for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
1145 ctl->server.protocol = autoprobe[i];
1146 if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
1149 ctl->server.protocol = P_AUTO;
1154 return(doPOP2(ctl));
1156 error(0, -1, "POP2 support is not configured.\n");
1157 return(PS_PROTOCOL);
1158 #endif /* POP2_ENABLE */
1164 return(doPOP3(ctl));
1166 error(0, -1, "POP3 support is not configured.\n");
1167 return(PS_PROTOCOL);
1168 #endif /* POP3_ENABLE */
1176 return(doIMAP(ctl));
1178 error(0, -1, "IMAP support is not configured.\n");
1179 return(PS_PROTOCOL);
1180 #endif /* IMAP_ENABLE */
1184 error(0, -1, "ETRN support is not configured.\n");
1185 return(PS_PROTOCOL);
1187 #ifdef HAVE_GETHOSTBYNAME
1188 return(doETRN(ctl));
1190 error(0, -1, "Cannot support ETRN without gethostbyname(2).\n");
1191 return(PS_PROTOCOL);
1192 #endif /* HAVE_GETHOSTBYNAME */
1193 #endif /* ETRN_ENABLE */
1195 error(0, 0, "unsupported protocol selected.");
1196 return(PS_PROTOCOL);
1200 void dump_params (struct runctl *runp, struct query *querylist, flag implicit)
1201 /* display query parameters in English */
1205 if (runp->poll_interval)
1206 printf("Poll interval is %d seconds\n", runp->poll_interval);
1208 printf("Logfile is %s\n", runp->logfile);
1209 if (strcmp(runp->idfile, IDFILE_NAME))
1210 printf("Idfile is %s\n", runp->idfile);
1211 #if defined(HAVE_SYSLOG)
1212 if (runp->use_syslog)
1213 printf("Progress messages will be logged via syslog\n");
1215 if (runp->invisible)
1216 printf("Fetchmail will masquerade and will not generate Received\n");
1217 if (runp->postmaster)
1218 printf("Fetchmail will forward misaddressed multidrop messages to %s.\n",
1221 for (ctl = querylist; ctl; ctl = ctl->next)
1223 if (!ctl->active || (implicit && ctl->server.skip))
1226 printf("Options for retrieving from %s@%s:\n",
1227 ctl->remotename, visbuf(ctl->server.pollname));
1229 if (ctl->server.via && (ctl->server.protocol != P_ETRN))
1230 printf(" Mail will be retrieved via %s\n", ctl->server.via);
1232 if (ctl->server.interval)
1233 printf(" Poll of this server will occur every %d intervals.\n",
1234 ctl->server.interval);
1235 if (ctl->server.truename)
1236 printf(" True name of server is %s.\n", ctl->server.truename);
1237 if (ctl->server.skip || outlevel >= O_VERBOSE)
1238 printf(" This host will%s be queried when no host is specified.\n",
1239 ctl->server.skip ? " not" : "");
1241 * Don't poll for password when there is one or when using the ETRN
1242 * or IMAP-GSS protocol
1244 if (!ctl->password && (ctl->server.protocol != P_ETRN)
1246 && (ctl->server.protocol != P_IMAP_GSS)
1249 printf(" Password will be prompted for.\n");
1250 else if (outlevel >= O_VERBOSE)
1251 if (ctl->server.protocol == P_APOP)
1252 printf(" APOP secret = \"%s\".\n", visbuf(ctl->password));
1253 else if (ctl->server.protocol == P_RPOP)
1254 printf(" RPOP id = \"%s\".\n", visbuf(ctl->password));
1256 printf(" Password = \"%s\".\n", visbuf(ctl->password));
1257 if (ctl->server.protocol == P_POP3
1259 && !strcmp(ctl->server.service, KPOP_PORT)
1261 && ctl->server.port == KPOP_PORT
1263 && (ctl->server.preauthenticate == A_KERBEROS_V4 ||
1264 ctl->server.preauthenticate == A_KERBEROS_V5))
1265 printf(" Protocol is KPOP with Kerberos %s authentication",
1266 ctl->server.preauthenticate == A_KERBEROS_V5 ? "V" : "IV");
1268 printf(" Protocol is %s", showproto(ctl->server.protocol));
1270 if (ctl->server.service)
1271 printf(" (using service %s)", ctl->server.service);
1272 if (ctl->server.netsec)
1273 printf(" (using network security options %s)", ctl->server.netsec);
1275 if (ctl->server.port)
1276 printf(" (using port %d)", ctl->server.port);
1278 else if (outlevel >= O_VERBOSE)
1279 printf(" (using default port)");
1280 if (ctl->server.uidl && (ctl->server.protocol != P_ETRN))
1281 printf(" (forcing UIDL use)");
1284 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1285 printf(" Kerberos V4 preauthentication enabled.\n");
1286 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1287 printf(" Kerberos V5 preauthentication enabled.\n");
1288 if (ctl->server.timeout > 0)
1289 printf(" Server nonresponse timeout is %d seconds", ctl->server.timeout);
1290 if (ctl->server.timeout == CLIENT_TIMEOUT)
1291 printf(" (default).\n");
1295 if (ctl->server.protocol != P_ETRN) {
1296 if (!ctl->mailboxes->id)
1297 printf(" Default mailbox selected.\n");
1302 printf(" Selected mailboxes are:");
1303 for (idp = ctl->mailboxes; idp; idp = idp->next)
1304 printf(" %s", idp->id);
1307 printf(" %s messages will be retrieved (--all %s).\n",
1308 ctl->fetchall ? "All" : "Only new",
1309 ctl->fetchall ? "on" : "off");
1310 printf(" Fetched messages will%s be kept on the server (--keep %s).\n",
1311 ctl->keep ? "" : " not",
1312 ctl->keep ? "on" : "off");
1313 printf(" Old messages will%s be flushed before message retrieval (--flush %s).\n",
1314 ctl->flush ? "" : " not",
1315 ctl->flush ? "on" : "off");
1316 printf(" Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
1317 ctl->rewrite ? "en" : "dis",
1318 ctl->rewrite ? "off" : "on");
1319 printf(" Carriage-return stripping is %sabled (stripcr %s).\n",
1320 ctl->stripcr ? "en" : "dis",
1321 ctl->stripcr ? "on" : "off");
1322 printf(" Carriage-return forcing is %sabled (forcecr %s).\n",
1323 ctl->forcecr ? "en" : "dis",
1324 ctl->forcecr ? "on" : "off");
1325 printf(" Interpretation of Content-Transfer-Encoding is %sabled (pass8bits %s).\n",
1326 ctl->pass8bits ? "dis" : "en",
1327 ctl->pass8bits ? "on" : "off");
1328 printf(" MIME decoding is %sabled (mimedecode %s).\n",
1329 ctl->mimedecode ? "en" : "dis",
1330 ctl->mimedecode ? "on" : "off");
1331 printf(" Nonempty Status lines will be %s (dropstatus %s)\n",
1332 ctl->dropstatus ? "discarded" : "kept",
1333 ctl->dropstatus ? "on" : "off");
1334 if (NUM_NONZERO(ctl->limit))
1336 if (NUM_NONZERO(ctl->limit))
1337 printf(" Message size limit is %d bytes (--limit %d).\n",
1338 ctl->limit, ctl->limit);
1339 else if (outlevel >= O_VERBOSE)
1340 printf(" No message size limit (--limit 0).\n");
1341 if (run.poll_interval > 0)
1342 printf(" Message size warning interval is %d seconds (--warnings %d).\n",
1343 ctl->warnings, ctl->warnings);
1344 else if (outlevel >= O_VERBOSE)
1345 printf(" Size warnings on every poll (--warnings 0).\n");
1347 if (NUM_NONZERO(ctl->fetchlimit))
1348 printf(" Received-message limit is %d (--fetchlimit %d).\n",
1349 ctl->fetchlimit, ctl->fetchlimit);
1350 else if (outlevel >= O_VERBOSE)
1351 printf(" No received-message limit (--fetchlimit 0).\n");
1352 if (NUM_NONZERO(ctl->batchlimit))
1353 printf(" SMTP message batch limit is %d.\n", ctl->batchlimit);
1354 else if (outlevel >= O_VERBOSE)
1355 printf(" No SMTP message batch limit (--batchlimit 0).\n");
1356 if (ctl->server.protocol == P_IMAP)
1357 if (NUM_NONZERO(ctl->expunge))
1358 printf(" Deletion interval between expunges is %d (--expunge %d).\n", ctl->expunge, ctl->expunge);
1359 else if (outlevel >= O_VERBOSE)
1360 printf(" No expunges (--expunge 0).\n");
1363 printf(" Messages will be appended to %s as BSMTP\n", visbuf(ctl->bsmtp));
1364 else if (ctl->mda && (ctl->server.protocol != P_ETRN))
1365 printf(" Messages will be delivered with \"%s\".\n", visbuf(ctl->mda));
1370 printf(" Messages will be SMTP-forwarded to:");
1371 for (idp = ctl->smtphunt; idp; idp = idp->next)
1373 printf(" %s", idp->id);
1374 if (!idp->val.status.mark)
1375 printf(" (default)");
1378 if (ctl->smtpaddress)
1379 printf(" Host part of MAIL FROM line will be %s\n",
1382 if (ctl->server.protocol != P_ETRN)
1384 if (ctl->antispam != (struct idlist *)NULL)
1388 printf(" Recognized listener spam block responses are:");
1389 for (idp = ctl->antispam; idp; idp = idp->next)
1390 printf(" %d", idp->val.status.num);
1393 else if (outlevel >= O_VERBOSE)
1394 printf(" Spam-blocking disabled\n");
1396 if (ctl->preconnect)
1397 printf(" Server connection will be brought up with \"%s\".\n",
1398 visbuf(ctl->preconnect));
1399 else if (outlevel >= O_VERBOSE)
1400 printf(" No pre-connection command.\n");
1401 if (ctl->postconnect)
1402 printf(" Server connection will be taken down with \"%s\".\n",
1403 visbuf(ctl->postconnect));
1404 else if (outlevel >= O_VERBOSE)
1405 printf(" No post-connection command.\n");
1406 if (ctl->server.protocol != P_ETRN) {
1407 if (!ctl->localnames)
1408 printf(" No localnames declared for this host.\n");
1414 for (idp = ctl->localnames; idp; idp = idp->next)
1417 if (count > 1 || ctl->wildcard)
1418 printf(" Multi-drop mode: ");
1420 printf(" Single-drop mode: ");
1422 printf("%d local name(s) recognized.\n", count);
1423 if (outlevel >= O_VERBOSE)
1425 for (idp = ctl->localnames; idp; idp = idp->next)
1427 printf("\t%s -> %s\n", idp->id, idp->val.id2);
1429 printf("\t%s\n", idp->id);
1431 fputs("\t*\n", stdout);
1434 if (count > 1 || ctl->wildcard)
1436 printf(" DNS lookup for multidrop addresses is %sabled.\n",
1437 ctl->server.dns ? "en" : "dis");
1438 if (ctl->server.dns)
1440 printf(" Server aliases will be compared with multidrop addresses by ");
1441 if (ctl->server.checkalias)
1442 printf("IP address.\n");
1446 if (ctl->server.envelope == STRING_DISABLED)
1447 printf(" Envelope-address routing is disabled\n");
1450 printf(" Envelope header is assumed to be: %s\n",
1451 ctl->server.envelope ? ctl->server.envelope:"Received");
1452 if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1453 printf(" Number of envelope header to be parsed: %d\n",
1454 ctl->server.envskip);
1455 if (ctl->server.qvirtual)
1456 printf(" Prefix %s will be removed from user id\n",
1457 ctl->server.qvirtual);
1458 else if (outlevel >= O_VERBOSE)
1459 printf(" No prefix stripping\n");
1462 if (ctl->server.akalist)
1466 printf(" Predeclared mailserver aliases:");
1467 for (idp = ctl->server.akalist; idp; idp = idp->next)
1468 printf(" %s", idp->id);
1471 if (ctl->server.localdomains)
1475 printf(" Local domains:");
1476 for (idp = ctl->server.localdomains; idp; idp = idp->next)
1477 printf(" %s", idp->id);
1484 if (ctl->server.interface)
1485 printf(" Connection must be through interface %s.\n", ctl->server.interface);
1486 else if (outlevel >= O_VERBOSE)
1487 printf(" No interface requirement specified.\n");
1488 if (ctl->server.monitor)
1489 printf(" Polling loop will monitor %s.\n", ctl->server.monitor);
1490 else if (outlevel >= O_VERBOSE)
1491 printf(" No monitor interface specified.\n");
1494 if (ctl->server.protocol > P_POP2 && (ctl->server.protocol != P_ETRN))
1496 printf(" No UIDs saved from this host.\n");
1502 for (idp = ctl->oldsaved; idp; idp = idp->next)
1505 printf(" %d UIDs saved.\n", count);
1506 if (outlevel >= O_VERBOSE)
1507 for (idp = ctl->oldsaved; idp; idp = idp->next)
1508 printf("\t%s\n", idp->id);
1511 if (ctl->properties)
1512 printf(" Pass-through properties \"%s\".\n",
1513 visbuf(ctl->properties));
1517 /* fetchmail.c ends here */