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)
16 #if defined(HAVE_ALLOCA_H)
25 #if defined(HAVE_SYSLOG)
31 #include <sys/types.h>
34 #include <sys/resource.h>
35 #endif /* HAVE_SETRLIMIT */
36 #ifdef HAVE_SYS_WAIT_H
40 #ifdef HAVE_GETHOSTBYNAME
42 #endif /* HAVE_GETHOSTBYNAME */
44 #include "fetchmail.h"
51 #define ENETUNREACH 128 /* Interactive doesn't know this */
52 #endif /* ENETUNREACH */
54 /* prototypes for internal functions */
55 static int load_params(int, char **, int);
56 static void dump_params (struct runctl *runp, struct query *, flag implicit);
57 static int query_host(struct query *);
59 /* controls the detail level of status/progress messages written to stderr */
60 int outlevel; /* see the O_.* constants above */
62 /* miscellaneous global controls */
63 struct runctl run; /* global controls for this run */
64 flag nodetach; /* if TRUE, don't detach daemon process */
65 flag quitmode; /* if --quit was set */
66 flag check_only; /* if --probe was set */
67 flag versioninfo; /* emit only version info */
68 char *user; /* the name of the invoking user */
69 char *home; /* invoking user's home directory */
70 char *program_name; /* the name to prefix error messages with */
71 flag configdump; /* dump control blocks for configurator */
72 char *fetchmailhost; /* either `localhost' or the host FQDN */
77 #endif /* NET_SECURITY */
79 static char *lockfile; /* name of lockfile */
80 static int querystatus; /* status of query */
81 static int successes; /* count number of successful polls */
82 static int lastsig; /* last signal received */
83 static struct runctl cmd_run; /* global options set from command line */
85 static void termhook(); /* forward declaration of exit hook */
88 #define SLEEP_WITH_ALARM
91 #ifdef SLEEP_WITH_ALARM
93 * The function of this variable is to remove the window during which a
94 * SIGALRM can hose the code (ALARM is triggered *before* pause() is called).
95 * This is a bit of a kluge; the real right thing would use sigprocmask(),
97 * This work around lets the interval timer trigger the first alarm after the
98 * required interval and will then generate alarms all 5 seconds, until it
99 * is certain, that the critical section (ie., the window) is left.
101 #if defined(STDC_HEADERS)
102 static sig_atomic_t alarm_latch = FALSE;
104 /* assume int can be written in one atomic operation on non ANSI-C systems */
105 static int alarm_latch = FALSE;
108 RETSIGTYPE gotsigalrm(sig)
111 signal(sig, gotsigalrm);
115 #endif /* SLEEP_WITH_ALARM */
117 RETSIGTYPE donothing(sig) int sig; {signal(sig, donothing); lastsig = sig;}
120 static void unlockit(int n, void *p)
122 static void unlockit(void)
124 /* must-do actions for exit (but we can't count on being able to do malloc) */
130 /* Various EMX-specific definitions */
132 void itimerthread(void* dummy) {
133 if (outlevel == O_VERBOSE)
134 fprintf(stderr, "fetchmail: thread sleeping for %d sec.\n", poll_interval);
136 _sleep2(poll_interval*1000);
137 kill((getpid()), SIGALRM);
142 int main (int argc, char **argv)
144 int st, bkgd = FALSE;
145 int parsestatus, implicitmode = FALSE;
148 netrc_entry *netrc_list;
149 char *netrc_file, *tmpbuf;
152 envquery(argc, argv);
154 #define IDFILE_NAME ".fetchids"
155 run.idfile = (char *) xmalloc(strlen(home)+strlen(IDFILE_NAME)+2);
156 strcpy(run.idfile, home);
157 strcat(run.idfile, "/");
158 strcat(run.idfile, IDFILE_NAME);
162 if ((parsestatus = parsecmdline(argc,argv, &cmd_run, &cmd_opts)) < 0)
165 /* this hint to stdio should help messages come out in the right order */
166 setvbuf(stdout, NULL, _IOLBF, MSGBUFSIZE);
170 printf("This is fetchmail release %s", RELEASE_ID);
173 #endif /* POP2_ENABLE */
176 #endif /* POP3_ENABLE */
179 #endif /* IMAP_ENABLE */
185 #endif /* RPA_ENABLE */
188 #endif /* SDPS_ENABLE */
191 #endif /* ETRN_ENABLE */
200 #endif /* NET_SECURITY */
203 /* this is an attempt to help remote debugging */
207 /* avoid parsing the config file if all we're doing is killing a daemon */
208 if (!(quitmode && argc == 2))
209 implicitmode = load_params(argc, argv, optind);
211 /* set up to do lock protocol */
212 #define FETCHMAIL_PIDFILE "fetchmail.pid"
213 tmpbuf = alloca(strlen(home) + strlen(FETCHMAIL_PIDFILE) + 3);
215 sprintf(tmpbuf, "%s/%s", PID_DIR, FETCHMAIL_PIDFILE);
217 strcpy(tmpbuf, home);
218 strcat(tmpbuf, "/.");
219 strcat(tmpbuf, FETCHMAIL_PIDFILE);
221 #undef FETCHMAIL_PIDFILE
223 /* perhaps we just want to check options? */
226 printf("Taking options from command line");
227 if (access(rcfile, 0))
230 printf(" and %s\n", rcfile);
231 if (outlevel == O_VERBOSE)
232 printf("Lockfile at %s\n", tmpbuf);
234 if (querylist == NULL)
235 (void) fprintf(stderr,
236 "No mailservers set up -- perhaps %s is missing?\n", rcfile);
238 dump_params(&run, querylist, implicitmode);
242 /* dump options as a Python dictionary, for configurator use */
245 dump_config(&run, querylist);
249 /* check for another fetchmail running concurrently */
251 if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
253 fprintf(stderr,"fetchmail: cannot allocate memory for lock name.\n");
257 (void) strcpy(lockfile, tmpbuf);
258 if ((lockfp = fopen(lockfile, "r")) != NULL )
260 bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
262 if (kill(pid, 0) == -1) {
263 fprintf(stderr,"fetchmail: removing stale lockfile\n");
271 /* if no mail servers listed and nothing in background, we're done */
272 if (!(quitmode && argc == 2) && pid == -1 && querylist == NULL) {
273 (void)fputs("fetchmail: no mailservers have been specified.\n",stderr);
277 /* perhaps user asked us to kill the other fetchmail */
282 fprintf(stderr,"fetchmail: no other fetchmail is running\n");
286 else if (kill(pid, SIGTERM) < 0)
288 fprintf(stderr,"fetchmail: error killing %s fetchmail at %d; bailing out.\n",
289 bkgd ? "background" : "foreground", pid);
294 fprintf(stderr,"fetchmail: %s fetchmail at %d killed.\n",
295 bkgd ? "background" : "foreground", pid);
304 /* another fetchmail is running -- wake it up or die */
310 "fetchmail: can't check mail while another fetchmail to same host is running.\n");
313 else if (!implicitmode)
316 "fetchmail: can't poll specified hosts with another fetchmail running at %d.\n",
323 "fetchmail: another foreground fetchmail is running at %d.\n",
330 "fetchmail: can't accept options while a background fetchmail is running.\n");
333 else if (kill(pid, SIGUSR1) == 0)
336 "fetchmail: background fetchmail at %d awakened.\n",
343 * Should never happen -- possible only if a background fetchmail
344 * croaks after the first kill probe above but before the
345 * SIGUSR1/SIGHUP transmission.
348 "fetchmail: elder sibling at %d died mysteriously.\n",
350 return(PS_UNDEFINED);
354 /* parse the ~/.netrc file (if present) for future password lookups. */
355 netrc_file = (char *) alloca (strlen (home) + 8);
356 strcpy (netrc_file, home);
357 strcat (netrc_file, "/.netrc");
358 netrc_list = parse_netrc(netrc_file);
360 #ifdef HAVE_SETRLIMIT
362 * Before getting passwords, disable core dumps unless -v -d0 mode is on.
363 * Core dumps could otherwise contain passwords to be scavenged by a
366 if (outlevel < O_VERBOSE || run.poll_interval > 0)
368 struct rlimit corelimit;
369 corelimit.rlim_cur = 0;
370 corelimit.rlim_max = 0;
371 setrlimit(RLIMIT_CORE, &corelimit);
373 #endif /* HAVE_SETRLIMIT */
375 /* pick up interactively any passwords we need but don't have */
376 for (ctl = querylist; ctl; ctl = ctl->next)
377 if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
379 if (ctl->server.preauthenticate == A_KERBEROS_V4 ||
380 ctl->server.preauthenticate == A_KERBEROS_V5 ||
382 ctl->server.protocol == P_IMAP_GSS ||
384 ctl->server.protocol == P_IMAP_K4)
385 /* Server won't care what the password is, but there
386 must be some non-null string here. */
387 ctl->password = ctl->remotename;
390 /* look up the host and account in the .netrc file. */
391 netrc_entry *p = search_netrc(netrc_list,ctl->server.pollname);
392 while (p && strcmp(p->account, ctl->remotename))
393 p = search_netrc(p->next, ctl->remotename);
395 /* if we find a matching entry with a password, use it */
396 if (p && p->password)
397 ctl->password = xstrdup(p->password);
400 if (ctl->server.protocol != P_ETRN && ctl->server.protocol != P_IMAP_K4
402 && ctl->server.protocol != P_IMAP_GSS
406 #define PASSWORD_PROMPT "Enter password for %s@%s: "
407 tmpbuf = alloca(strlen(PASSWORD_PROMPT) +
408 strlen(ctl->remotename) +
409 strlen(ctl->server.pollname) + 1);
410 (void) sprintf(tmpbuf, PASSWORD_PROMPT,
411 ctl->remotename, ctl->server.pollname);
412 ctl->password = xstrdup((char *)getpassword(tmpbuf));
413 #undef PASSWORD_PROMPT
418 * Maybe time to go to demon mode...
420 #if defined(HAVE_SYSLOG)
423 openlog(program_name, LOG_PID, LOG_MAIL);
428 error_init((run.poll_interval == 0 || nodetach) && !run.logfile);
430 if (run.poll_interval)
433 daemonize(run.logfile, termhook);
434 error( 0, 0, "starting fetchmail %s daemon ", RELEASE_ID);
437 * We'll set up a handler for these when we're sleeping,
438 * but ignore them otherwise so as not to interrupt a poll.
440 signal(SIGUSR1, SIG_IGN);
441 if (run.poll_interval && !getuid())
442 signal(SIGHUP, SIG_IGN);
445 /* beyond here we don't want more than one fetchmail running per user */
447 signal(SIGABRT, termhook);
448 signal(SIGINT, termhook);
449 signal(SIGTERM, termhook);
450 signal(SIGALRM, termhook);
451 signal(SIGPIPE, termhook);
452 signal(SIGQUIT, termhook);
454 /* here's the exclusion lock */
455 if ((lockfp = fopen(lockfile,"w")) != NULL) {
456 fprintf(lockfp,"%d",getpid());
457 if (run.poll_interval)
458 fprintf(lockfp," %d", run.poll_interval);
465 on_exit(unlockit, (char *)NULL);
470 * Query all hosts. If there's only one, the error return will
471 * reflect the status of that transaction.
474 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
476 * This was an efficiency hack that backfired. The theory
477 * was that using TCP/IP for DNS queries would get us better
478 * reliability and shave off some per-UDP-packet costs.
479 * Unfortunately it interacted badly with diald, which effectively
480 * filters out DNS queries over TCP/IP for reasons having to do
481 * with some obscure kernel problem involving bootstrapping of
482 * dynamically-addressed links. I don't understand this mess
483 * and don't want to, so it's "See ya!" to this hack.
485 sethostent(TRUE); /* use TCP/IP for mailserver queries */
486 #endif /* HAVE_RES_SEARCH */
489 for (ctl = querylist; ctl; ctl = ctl->next)
491 if (ctl->active && !(implicitmode && ctl->server.skip))
493 /* check skip interval first so that it counts all polls */
494 if (run.poll_interval && ctl->server.interval)
496 if (ctl->server.poll_count++ % ctl->server.interval)
498 if (outlevel == O_VERBOSE)
500 "fetchmail: interval not reached, not querying %s\n",
501 ctl->server.pollname);
506 #if defined(linux) && !INET6
507 /* interface_approve() does its own error logging */
508 if (!interface_approve(&ctl->server))
510 #endif /* defined(linux) && !INET6 */
512 querystatus = query_host(ctl);
514 if (querystatus == PS_SUCCESS)
519 update_str_lists(ctl);
521 /* Save UID list to prevent re-fetch in case fetchmail
522 recover from crash */
523 if (!check_only && outlevel == O_VERBOSE)
525 write_saved_lists(querylist, run.idfile);
526 if (outlevel == O_VERBOSE)
527 error(0, 0, "saved UID List");
529 #endif /* POP3_ENABLE */
531 else if (!check_only &&
532 ((querystatus!=PS_NOMAIL) || (outlevel==O_VERBOSE)))
533 error(0, 0, "Query status=%d", querystatus);
535 #if defined(linux) && !INET6
536 if (ctl->server.monitor)
539 * Allow some time for the link to quiesce. One
540 * second is usually sufficient, three is safe.
541 * Note: this delay is important - don't remove!
544 interface_note_activity(&ctl->server);
546 #endif /* defined(linux) && !INET6 */
550 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
551 endhostent(); /* release TCP/IP connection to nameserver */
552 #endif /* HAVE_RES_SEARCH */
555 * Close all SMTP delivery sockets. For optimum performance
556 * we'd like to hold them open til end of run, but (1) this
557 * loses if our poll interval is longer than the MTA's inactivity
558 * timeout, and (2) some MTAs (like smail) don't deliver after
559 * each message, but rather queue up mail and wait to actually
560 * deliver it until the input socket is closed.
562 for (ctl = querylist; ctl; ctl = ctl->next)
563 if (ctl->smtp_socket != -1)
565 SMTP_quit(ctl->smtp_socket);
566 close(ctl->smtp_socket);
567 ctl->smtp_socket = -1;
571 * OK, we've polled. Now sleep.
573 if (run.poll_interval)
575 if (outlevel == O_VERBOSE)
580 fprintf(stderr, "fetchmail: sleeping at %s", ctime(&now));
584 * With this simple hack, we make it possible for a foreground
585 * fetchmail to wake up one in daemon mode. What we want is the
586 * side effect of interrupting any sleep that may be going on,
587 * forcing fetchmail to re-poll its hosts. The second line is
588 * for people who think all system daemons wake up on SIGHUP.
590 signal(SIGUSR1, donothing);
592 signal(SIGHUP, donothing);
595 * We can't use sleep(3) here because we need an alarm(3)
596 * equivalent in order to implement server nonresponse timeout.
597 * We'll just assume setitimer(2) is available since fetchmail
598 * has to have a BSDoid socket layer to work at all.
602 #ifdef SLEEP_WITH_ALARM /* not normally on */
604 * This code stopped working under glibc-2, apparently due
605 * to the change in signal(2) semantics. (The siginterrupt
606 * line, added later, should fix this problem.) John Stracke
607 * <francis@netscape.com> wrote:
609 * The problem seems to be that, after hitting the interval
610 * timer while talking to the server, the process no longer
611 * responds to SIGALRM. I put in printf()s to see when it
612 * reached the pause() for the poll interval, and I checked
613 * the return from setitimer(), and everything seemed to be
614 * working fine, except that the pause() just ignored SIGALRM.
615 * I thought maybe the itimer wasn't being fired, so I hit
616 * it with a SIGALRM from the command line, and it ignored
617 * that, too. SIGUSR1 woke it up just fine, and it proceeded
618 * to repoll--but, when the dummy server didn't respond, it
619 * never timed out, and SIGALRM wouldn't make it.
621 * (continued below...)
623 struct itimerval ntimeout;
625 ntimeout.it_interval.tv_sec = 5; /* repeat alarm every 5 secs */
626 ntimeout.it_interval.tv_usec = 0;
627 ntimeout.it_value.tv_sec = run.poll_interval;
628 ntimeout.it_value.tv_usec = 0;
630 siginterrupt(SIGALRM, 1);
632 signal(SIGALRM, gotsigalrm); /* first trap signals */
633 setitimer(ITIMER_REAL,&ntimeout,NULL); /* then start timer */
634 /* there is a very small window between the next two lines */
635 /* which could result in a deadlock. But this will now be */
636 /* caught by periodical alarms (see it_interval) */
640 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
641 ntimeout.it_value.tv_sec = ntimeout.it_value.tv_usec = 0;
642 setitimer(ITIMER_REAL,&ntimeout,NULL); /* now stop timer */
643 signal(SIGALRM, SIG_IGN);
646 * So the workaround I used is to make it sleep by using
647 * select() instead of setitimer()/pause(). select() is
648 * perfectly happy being called with a timeout and
649 * no file descriptors; it just sleeps until it hits the
650 * timeout. The only concern I had was that it might
651 * implement its timeout with SIGALRM--there are some
652 * Unices where this is done, because select() is a library
653 * function--but apparently not.
655 struct timeval timeout;
657 timeout.tv_sec = run.poll_interval;
660 select(0,0,0,0, &timeout);
664 signal(SIGALRM, gotsigalrm);
665 _beginthread(itimerthread, NULL, 32768, NULL);
666 /* see similar code above */
669 signal(SIGALRM, SIG_IGN);
671 if (lastsig == SIGUSR1
672 || ((run.poll_interval && !getuid()) && lastsig == SIGHUP))
674 #ifdef SYS_SIGLIST_DECLARED
675 error(0, 0, "awakened by %s", sys_siglist[lastsig]);
677 error(0, 0, "awakened by signal %d", lastsig);
682 /* now lock out interrupts again */
683 signal(SIGUSR1, SIG_IGN);
685 signal(SIGHUP, SIG_IGN);
687 if (outlevel == O_VERBOSE)
692 fprintf(stderr, "fetchmail: awakened at %s", ctime(&now));
698 if (outlevel == O_VERBOSE)
699 fprintf(stderr,"fetchmail: normal termination, status %d\n",
700 successes ? PS_SUCCESS : querystatus);
703 exit(successes ? PS_SUCCESS : querystatus);
706 static void optmerge(struct query *h2, struct query *h1, int force)
707 /* merge two options records */
710 * If force is off, modify h2 fields only when they're empty (treat h1
711 * as defaults). If force is on, modify each h2 field whenever h1
712 * is nonempty (treat h1 as an override).
714 #define LIST_MERGE(dstl, srcl) if (force ? !!srcl : !dstl) \
715 free_str_list(&dstl), \
716 append_str_list(&dstl, &srcl)
717 LIST_MERGE(h2->server.localdomains, h1->server.localdomains);
718 LIST_MERGE(h2->localnames, h1->localnames);
719 LIST_MERGE(h2->mailboxes, h1->mailboxes);
720 LIST_MERGE(h2->smtphunt, h1->smtphunt);
721 LIST_MERGE(h2->antispam, h1->antispam);
724 #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld
725 FLAG_MERGE(server.via);
726 FLAG_MERGE(server.protocol);
728 FLAG_MERGE(server.service);
729 FLAG_MERGE(server.netsec);
731 FLAG_MERGE(server.port);
733 FLAG_MERGE(server.interval);
734 FLAG_MERGE(server.preauthenticate);
735 FLAG_MERGE(server.timeout);
736 FLAG_MERGE(server.envelope);
737 FLAG_MERGE(server.envskip);
738 FLAG_MERGE(server.qvirtual);
739 FLAG_MERGE(server.skip);
740 FLAG_MERGE(server.dns);
741 FLAG_MERGE(server.checkalias);
742 FLAG_MERGE(server.uidl);
745 FLAG_MERGE(server.interface);
746 FLAG_MERGE(server.monitor);
747 FLAG_MERGE(server.interface_pair);
750 FLAG_MERGE(wildcard);
751 FLAG_MERGE(remotename);
752 FLAG_MERGE(password);
754 FLAG_MERGE(smtpaddress);
755 FLAG_MERGE(preconnect);
756 FLAG_MERGE(postconnect);
760 FLAG_MERGE(fetchall);
764 FLAG_MERGE(pass8bits);
765 FLAG_MERGE(dropstatus);
766 FLAG_MERGE(mimedecode);
768 FLAG_MERGE(warnings);
769 FLAG_MERGE(fetchlimit);
770 FLAG_MERGE(batchlimit);
775 static int load_params(int argc, char **argv, int optind)
777 int implicitmode, st;
779 struct query def_opts, *ctl;
781 memset(&def_opts, '\0', sizeof(struct query));
782 def_opts.smtp_socket = -1;
783 def_opts.smtpaddress = (char *)0;
784 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 571;
785 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 550;
786 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 501;
788 def_opts.server.protocol = P_AUTO;
789 def_opts.server.timeout = CLIENT_TIMEOUT;
790 def_opts.warnings = WARNING_INTERVAL;
791 def_opts.remotename = user;
792 def_opts.expunge = 1;
794 /* this builds the host list */
795 if (prc_parse_file(rcfile, !versioninfo) != 0)
798 if ((implicitmode = (optind >= argc)))
800 for (ctl = querylist; ctl; ctl = ctl->next)
804 for (; optind < argc; optind++)
806 flag predeclared = FALSE;
809 * If hostname corresponds to a host known from the rc file,
810 * simply declare it active. Otherwise synthesize a host
811 * record from command line and defaults
813 for (ctl = querylist; ctl; ctl = ctl->next)
814 if (!strcmp(ctl->server.pollname, argv[optind])
815 || str_in_list(&ctl->server.akalist, argv[optind], TRUE))
824 * Allocate and link record without copying in
825 * command-line args; we'll do that with the optmerge
828 ctl = hostalloc((struct query *)NULL);
830 ctl->server.pollname = xstrdup(argv[optind]);
832 ctl->server.lead_server = (struct hostdata *)NULL;
837 * If there's a defaults record, merge it and lose it.
839 if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
841 for (ctl = querylist->next; ctl; ctl = ctl->next)
842 optmerge(ctl, querylist, FALSE);
843 querylist = querylist->next;
846 /* don't allow a defaults record after the first */
847 for (ctl = querylist; ctl; ctl = ctl->next)
848 if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
851 /* use localhost if we never fetch the FQDN of this host */
852 fetchmailhost = "localhost";
854 /* merge in wired defaults, do sanity checks and prepare internal fields */
855 for (ctl = querylist; ctl; ctl = ctl->next)
857 if (configdump || (ctl->active && !(implicitmode && ctl->server.skip)))
859 /* merge in defaults */
860 optmerge(ctl, &def_opts, FALSE);
862 /* force command-line options */
863 optmerge(ctl, &cmd_opts, TRUE);
866 * DNS support is required for some protocols.
868 * If we're using ETRN, the smtp hunt list is the list of
869 * systems we're polling on behalf of; these have to be
870 * fully-qualified domain names. The default for this list
871 * should be the FQDN of localhost.
873 * If we're using Kerberos for authentication, we need
874 * the FQDN in order to generate capability keys.
876 if ((ctl->server.protocol == P_ETRN
877 || ctl->server.preauthenticate == A_KERBEROS_V4
878 || ctl->server.preauthenticate == A_KERBEROS_V5))
879 if (strcmp(fetchmailhost, "localhost") == 0)
880 fetchmailhost = host_fqdn();
883 * Make sure we have a nonempty host list to forward to.
886 save_str(&ctl->smtphunt, fetchmailhost, FALSE);
888 /* if `user' doesn't name a real local user, try to run as root */
889 if ((pw = getpwnam(user)) == (struct passwd *)NULL)
892 ctl->uid = pw->pw_uid; /* for local delivery via MDA */
893 if (!ctl->localnames) /* for local delivery via SMTP */
894 save_str_pair(&ctl->localnames, user, NULL);
896 /* this code enables flags to be turned off */
897 #define DEFAULT(flag, dflt) if (flag == FLAG_TRUE)\
899 else if (flag == FLAG_FALSE)\
903 DEFAULT(ctl->keep, FALSE);
904 DEFAULT(ctl->fetchall, FALSE);
905 DEFAULT(ctl->flush, FALSE);
906 DEFAULT(ctl->rewrite, TRUE);
907 DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL));
908 DEFAULT(ctl->forcecr, FALSE);
909 DEFAULT(ctl->pass8bits, FALSE);
910 DEFAULT(ctl->dropstatus, FALSE);
911 DEFAULT(ctl->mimedecode, FALSE);
912 DEFAULT(ctl->server.dns, TRUE);
913 DEFAULT(ctl->server.uidl, FALSE);
914 DEFAULT(ctl->server.checkalias, FALSE);
917 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
918 /* can't handle multidrop mailboxes unless we can do DNS lookups */
919 if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
921 ctl->server.dns = FALSE;
922 fprintf(stderr, "fetchmail: warning: no DNS available to check multidrop fetches from %s\n", ctl->server.pollname);
924 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
928 * Compute the true name of the mailserver host.
929 * There are two clashing cases here:
931 * (1) The poll name is a label, possibly on one of several
932 * poll configurations for the same host. In this case
933 * the `via' option will be present and give the true name.
935 * (2) The poll name is the true one, the via name is
936 * localhost. This is going to be typical for ssh-using
939 * We're going to assume the via name is true unless it's
942 if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
943 ctl->server.queryname = xstrdup(ctl->server.via);
945 ctl->server.queryname = xstrdup(ctl->server.pollname);
948 * We may have to canonicalize the server truename for later use.
949 * Do this just once for each lead server, if necessary, in order
950 * to minimize DNS round trips.
952 if (ctl->server.lead_server)
953 ctl->server.truename = xstrdup(ctl->server.lead_server->truename);
954 #ifdef HAVE_GETHOSTBYNAME
955 else if (ctl->server.preauthenticate==A_KERBEROS_V4 ||
956 ctl->server.preauthenticate==A_KERBEROS_V5 ||
957 (ctl->server.dns && MULTIDROP(ctl)))
959 struct hostent *namerec;
961 /* compute the canonical name of the host */
963 namerec = gethostbyname(ctl->server.queryname);
964 if (namerec == (struct hostent *)NULL)
967 "couldn't find canonical DNS name of %s",
968 ctl->server.pollname);
972 ctl->server.truename=xstrdup((char *)namerec->h_name);
974 #endif /* HAVE_GETHOSTBYNAME */
976 ctl->server.truename = xstrdup(ctl->server.queryname);
978 /* if no folders were specified, set up the null one as default */
980 save_str(&ctl->mailboxes, (char *)NULL, 0);
982 /* maybe user overrode timeout on command line? */
983 if (ctl->server.timeout == -1)
984 ctl->server.timeout = CLIENT_TIMEOUT;
988 if (ctl->server.port < 0)
990 (void) fprintf(stderr,
991 "%s configuration invalid, port number cannot be negative",
992 ctl->server.pollname);
995 if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
997 (void) fprintf(stderr,
998 "%s configuration invalid, RPOP requires a privileged port",
999 ctl->server.pollname);
1006 /* here's where we override globals */
1007 if (cmd_run.logfile)
1008 run.logfile = cmd_run.logfile;
1010 run.idfile = cmd_run.idfile;
1011 if (cmd_run.poll_interval >= 0)
1012 run.poll_interval = cmd_run.poll_interval;
1013 if (cmd_run.invisible)
1014 run.invisible = cmd_run.invisible;
1015 if (cmd_run.use_syslog)
1016 run.use_syslog = (cmd_run.use_syslog == FLAG_TRUE);
1018 /* check and daemon options are not compatible */
1019 if (check_only && run.poll_interval)
1020 run.poll_interval = 0;
1023 /* initialize UID handling */
1024 if (!versioninfo && (st = prc_filecheck(run.idfile, !versioninfo)) != 0)
1027 initialize_saved_lists(querylist, run.idfile);
1028 #endif /* POP3_ENABLE */
1031 * If the user didn't set a last-resort user to get misaddressed
1032 * multidrop mail, set an appropriate default here.
1034 if (!run.postmaster)
1035 if (getuid()) /* ordinary user */
1036 run.postmaster = user;
1038 run.postmaster = "postmaster";
1040 return(implicitmode);
1043 void termhook(int sig)
1044 /* to be executed on normal or signal-induced termination */
1049 * Sending SMTP QUIT on signal is theoretically nice, but led to a
1050 * subtle bug. If fetchmail was terminated by signal while it was
1051 * shipping message text, it would hang forever waiting for a
1052 * command acknowledge. In theory we could enable the QUIT
1053 * only outside of the message send. In practice, we don't
1054 * care. All mailservers hang up on a dropped TCP/IP connection
1059 error(0, 0, "terminated with signal %d", sig);
1061 /* terminate all SMTP connections cleanly */
1062 for (ctl = querylist; ctl; ctl = ctl->next)
1063 if (ctl->smtp_socket != -1)
1064 SMTP_quit(ctl->smtp_socket);
1068 write_saved_lists(querylist, run.idfile);
1069 #endif /* POP3_ENABLE */
1072 * Craig Metz, the RFC1938 one-time-password guy, points out:
1073 * "Remember that most kernels don't zero pages before handing them to the
1074 * next process and many kernels share pages between user and kernel space.
1075 * You'd be very surprised what you can find from a short program to do a
1076 * malloc() and then dump the contents of the pages you got. By zeroing
1077 * the secrets at end of run (earlier if you can), you make sure the next
1078 * guy can't get the password/pass phrase."
1080 * Right you are, Craig!
1082 for (ctl = querylist; ctl; ctl = ctl->next)
1084 memset(ctl->password, '\0', strlen(ctl->password));
1086 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
1090 exit(successes ? PS_SUCCESS : querystatus);
1094 * Sequence of protocols to try when autoprobing, most capable to least.
1096 static const int autoprobe[] =
1100 #endif /* IMAP_ENABLE */
1103 #endif /* POP3_ENABLE */
1106 #endif /* POP2_ENABLE */
1109 static int query_host(struct query *ctl)
1110 /* perform fetch transaction with single host */
1114 if (outlevel == O_VERBOSE)
1119 fprintf(stderr, "fetchmail: %s querying %s (protocol %s) at %s",
1121 ctl->server.pollname, showproto(ctl->server.protocol), ctime(&now));
1123 switch (ctl->server.protocol) {
1125 for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
1127 ctl->server.protocol = autoprobe[i];
1128 if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
1131 ctl->server.protocol = P_AUTO;
1136 return(doPOP2(ctl));
1138 fprintf(stderr, "POP2 support is not configured.\n");
1139 return(PS_PROTOCOL);
1140 #endif /* POP2_ENABLE */
1146 return(doPOP3(ctl));
1148 fprintf(stderr, "POP3 support is not configured.\n");
1149 return(PS_PROTOCOL);
1150 #endif /* POP3_ENABLE */
1158 return(doIMAP(ctl));
1160 fprintf(stderr, "IMAP support is not configured.\n");
1161 return(PS_PROTOCOL);
1162 #endif /* IMAP_ENABLE */
1166 fprintf(stderr, "ETRN support is not configured.\n");
1167 return(PS_PROTOCOL);
1169 #ifdef HAVE_GETHOSTBYNAME
1170 return(doETRN(ctl));
1172 fprintf(stderr, "Cannot support ETRN without gethostbyname(2).\n");
1173 return(PS_PROTOCOL);
1174 #endif /* HAVE_GETHOSTBYNAME */
1175 #endif /* ETRN_ENABLE */
1177 error(0, 0, "unsupported protocol selected.");
1178 return(PS_PROTOCOL);
1182 void dump_params (struct runctl *runp, struct query *querylist, flag implicit)
1183 /* display query parameters in English */
1187 if (runp->poll_interval)
1188 printf("Poll interval is %d seconds\n", runp->poll_interval);
1190 printf("Logfile is %s\n", runp->logfile);
1191 if (strcmp(runp->idfile, IDFILE_NAME))
1192 printf("Idfile is %s\n", runp->idfile);
1193 #if defined(HAVE_SYSLOG)
1194 if (runp->use_syslog)
1195 printf("Progress messages will be logged via syslog\n");
1197 if (runp->invisible)
1198 printf("Fetchmail will masquerade and will not generate Received\n");
1199 if (runp->postmaster)
1200 printf("Fetchmail will forward misaddressed multidrop messages to %s.\n",
1203 for (ctl = querylist; ctl; ctl = ctl->next)
1205 if (!ctl->active || (implicit && ctl->server.skip))
1208 printf("Options for retrieving from %s@%s:\n",
1209 ctl->remotename, visbuf(ctl->server.pollname));
1211 if (ctl->server.via && (ctl->server.protocol != P_ETRN))
1212 printf(" Mail will be retrieved via %s\n", ctl->server.via);
1214 if (ctl->server.interval)
1215 printf(" Poll of this server will occur every %d intervals.\n",
1216 ctl->server.interval);
1217 if (ctl->server.truename)
1218 printf(" True name of server is %s.\n", ctl->server.truename);
1219 if (ctl->server.skip || outlevel == O_VERBOSE)
1220 printf(" This host will%s be queried when no host is specified.\n",
1221 ctl->server.skip ? " not" : "");
1223 * Don't poll for password when there is one or when using the ETRN
1224 * or IMAP-GSS protocol
1226 if (!ctl->password && (ctl->server.protocol != P_ETRN)
1228 && (ctl->server.protocol != P_IMAP_GSS)
1231 printf(" Password will be prompted for.\n");
1232 else if (outlevel == O_VERBOSE)
1233 if (ctl->server.protocol == P_APOP)
1234 printf(" APOP secret = \"%s\".\n", visbuf(ctl->password));
1235 else if (ctl->server.protocol == P_RPOP)
1236 printf(" RPOP id = \"%s\".\n", visbuf(ctl->password));
1238 printf(" Password = \"%s\".\n", visbuf(ctl->password));
1239 if (ctl->server.protocol == P_POP3
1241 && !strcmp(ctl->server.service, KPOP_PORT)
1243 && ctl->server.port == KPOP_PORT
1245 && (ctl->server.preauthenticate == A_KERBEROS_V4 ||
1246 ctl->server.preauthenticate == A_KERBEROS_V5))
1247 printf(" Protocol is KPOP");
1249 printf(" Protocol is %s", showproto(ctl->server.protocol));
1251 if (ctl->server.service)
1252 printf(" (using service %s)", ctl->server.service);
1253 if (ctl->server.netsec)
1254 printf(" (using network security options %s)", ctl->server.netsec);
1256 if (ctl->server.port)
1257 printf(" (using port %d)", ctl->server.port);
1259 else if (outlevel == O_VERBOSE)
1260 printf(" (using default port)");
1261 if (ctl->server.uidl && (ctl->server.protocol != P_ETRN))
1262 printf(" (forcing UIDL use)");
1265 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1266 printf(" Kerberos V4 preauthentication enabled.\n");
1267 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1268 printf(" Kerberos V5 preauthentication enabled.\n");
1269 if (ctl->server.timeout > 0)
1270 printf(" Server nonresponse timeout is %d seconds", ctl->server.timeout);
1271 if (ctl->server.timeout == CLIENT_TIMEOUT)
1272 printf(" (default).\n");
1276 if (ctl->server.protocol != P_ETRN) {
1277 if (!ctl->mailboxes->id)
1278 printf(" Default mailbox selected.\n");
1283 printf(" Selected mailboxes are:");
1284 for (idp = ctl->mailboxes; idp; idp = idp->next)
1285 printf(" %s", idp->id);
1288 printf(" %s messages will be retrieved (--all %s).\n",
1289 ctl->fetchall ? "All" : "Only new",
1290 ctl->fetchall ? "on" : "off");
1291 printf(" Fetched messages will%s be kept on the server (--keep %s).\n",
1292 ctl->keep ? "" : " not",
1293 ctl->keep ? "on" : "off");
1294 printf(" Old messages will%s be flushed before message retrieval (--flush %s).\n",
1295 ctl->flush ? "" : " not",
1296 ctl->flush ? "on" : "off");
1297 printf(" Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
1298 ctl->rewrite ? "en" : "dis",
1299 ctl->rewrite ? "off" : "on");
1300 printf(" Carriage-return stripping is %sabled (stripcr %s).\n",
1301 ctl->stripcr ? "en" : "dis",
1302 ctl->stripcr ? "on" : "off");
1303 printf(" Carriage-return forcing is %sabled (forcecr %s).\n",
1304 ctl->forcecr ? "en" : "dis",
1305 ctl->forcecr ? "on" : "off");
1306 printf(" Interpretation of Content-Transfer-Encoding is %sabled (pass8bits %s).\n",
1307 ctl->pass8bits ? "dis" : "en",
1308 ctl->pass8bits ? "on" : "off");
1309 printf(" MIME decoding is %sabled (mimedecode %s).\n",
1310 ctl->mimedecode ? "en" : "dis",
1311 ctl->mimedecode ? "on" : "off");
1312 printf(" Nonempty Status lines will be %s (dropstatus %s)\n",
1313 ctl->dropstatus ? "discarded" : "kept",
1314 ctl->dropstatus ? "on" : "off");
1315 if (NUM_NONZERO(ctl->limit))
1317 if (NUM_NONZERO(ctl->limit))
1318 printf(" Message size limit is %d bytes (--limit %d).\n",
1319 ctl->limit, ctl->limit);
1320 else if (outlevel == O_VERBOSE)
1321 printf(" No message size limit (--limit 0).\n");
1322 if (run.poll_interval > 0)
1323 printf(" Message size warning interval is %d seconds (--warnings %d).\n",
1324 ctl->warnings, ctl->warnings);
1325 else if (outlevel == O_VERBOSE)
1326 printf(" Size warnings on every poll (--warnings 0).\n");
1328 if (NUM_NONZERO(ctl->fetchlimit))
1329 printf(" Received-message limit is %d (--fetchlimit %d).\n",
1330 ctl->fetchlimit, ctl->fetchlimit);
1331 else if (outlevel == O_VERBOSE)
1332 printf(" No received-message limit (--fetchlimit 0).\n");
1333 if (NUM_NONZERO(ctl->batchlimit))
1334 printf(" SMTP message batch limit is %d.\n", ctl->batchlimit);
1335 else if (outlevel == O_VERBOSE)
1336 printf(" No SMTP message batch limit (--batchlimit 0).\n");
1337 if (ctl->server.protocol == P_IMAP)
1338 if (NUM_NONZERO(ctl->expunge))
1339 printf(" Deletion interval between expunges is %d (--expunge %d).\n", ctl->expunge, ctl->expunge);
1340 else if (outlevel == O_VERBOSE)
1341 printf(" No expunges (--expunge 0).\n");
1343 if (ctl->mda && (ctl->server.protocol != P_ETRN))
1344 printf(" Messages will be delivered with \"%s\".\n", visbuf(ctl->mda));
1349 printf(" Messages will be SMTP-forwarded to:");
1350 for (idp = ctl->smtphunt; idp; idp = idp->next)
1352 printf(" %s", idp->id);
1353 if (!idp->val.status.mark)
1354 printf(" (default)");
1357 if (ctl->smtpaddress)
1358 printf(" Host part of MAIL FROM line will be %s\n",
1361 if (ctl->server.protocol != P_ETRN)
1363 if (ctl->antispam != (struct idlist *)NULL)
1367 printf(" Recognized listener spam block responses are:",
1369 for (idp = ctl->antispam; idp; idp = idp->next)
1370 printf(" %d", idp->val.status.num);
1373 else if (outlevel == O_VERBOSE)
1374 printf(" Spam-blocking disabled\n");
1376 if (ctl->preconnect)
1377 printf(" Server connection will be brought up with \"%s\".\n",
1378 visbuf(ctl->preconnect));
1379 else if (outlevel == O_VERBOSE)
1380 printf(" No pre-connection command.\n");
1381 if (ctl->postconnect)
1382 printf(" Server connection will be taken down with \"%s\".\n",
1383 visbuf(ctl->postconnect));
1384 else if (outlevel == O_VERBOSE)
1385 printf(" No post-connection command.\n");
1386 if (ctl->server.protocol != P_ETRN) {
1387 if (!ctl->localnames)
1388 printf(" No localnames declared for this host.\n");
1394 for (idp = ctl->localnames; idp; idp = idp->next)
1397 if (count > 1 || ctl->wildcard)
1398 printf(" Multi-drop mode: ");
1400 printf(" Single-drop mode: ");
1402 printf("%d local name(s) recognized.\n", count);
1403 if (outlevel == O_VERBOSE)
1405 for (idp = ctl->localnames; idp; idp = idp->next)
1407 printf("\t%s -> %s\n", idp->id, idp->val.id2);
1409 printf("\t%s\n", idp->id);
1411 fputs("\t*\n", stdout);
1414 if (count > 1 || ctl->wildcard)
1416 printf(" DNS lookup for multidrop addresses is %sabled.\n",
1417 ctl->server.dns ? "en" : "dis");
1418 if (ctl->server.dns)
1420 printf(" Server aliases will be compared with multidrop addresses by ");
1421 if (ctl->server.checkalias)
1422 printf("IP address.\n");
1426 if (ctl->server.envelope == STRING_DISABLED)
1427 printf(" Envelope-address routing is disabled\n");
1430 printf(" Envelope header is assumed to be: %s\n",
1431 ctl->server.envelope ? ctl->server.envelope:"Received");
1432 if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1433 printf(" Number of envelope header to be parsed: %d\n",
1434 ctl->server.envskip);
1435 if (ctl->server.qvirtual)
1436 printf(" Prefix %s will be removed from user id\n",
1437 ctl->server.qvirtual);
1438 else if (outlevel >= O_VERBOSE)
1439 printf(" No prefix stripping\n");
1442 if (ctl->server.akalist)
1446 printf(" Predeclared mailserver aliases:");
1447 for (idp = ctl->server.akalist; idp; idp = idp->next)
1448 printf(" %s", idp->id);
1451 if (ctl->server.localdomains)
1455 printf(" Local domains:");
1456 for (idp = ctl->server.localdomains; idp; idp = idp->next)
1457 printf(" %s", idp->id);
1464 if (ctl->server.interface)
1465 printf(" Connection must be through interface %s.\n", ctl->server.interface);
1466 else if (outlevel == O_VERBOSE)
1467 printf(" No interface requirement specified.\n");
1468 if (ctl->server.monitor)
1469 printf(" Polling loop will monitor %s.\n", ctl->server.monitor);
1470 else if (outlevel == O_VERBOSE)
1471 printf(" No monitor interface specified.\n");
1474 if (ctl->server.protocol > P_POP2 && (ctl->server.protocol != P_ETRN))
1476 printf(" No UIDs saved from this host.\n");
1482 for (idp = ctl->oldsaved; idp; idp = idp->next)
1485 printf(" %d UIDs saved.\n", count);
1486 if (outlevel == O_VERBOSE)
1487 for (idp = ctl->oldsaved; idp; idp = idp->next)
1488 fprintf(stderr, "\t%s\n", idp->id);
1493 /* fetchmail.c ends here */