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 */
41 #include "fetchmail.h"
48 #define ENETUNREACH 128 /* Interactive doesn't know this */
49 #endif /* ENETUNREACH */
51 /* prototypes for internal functions */
52 static int load_params(int, char **, int);
53 static void dump_params (struct runctl *runp, struct query *, flag implicit);
54 static int query_host(struct query *);
56 /* controls the detail level of status/progress messages written to stderr */
57 int outlevel; /* see the O_.* constants above */
59 /* miscellaneous global controls */
60 struct runctl run; /* global controls for this run */
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 flag versioninfo; /* emit only version info */
65 char *user; /* the name of the invoking user */
66 char *home; /* invoking user's home directory */
67 char *program_name; /* the name to prefix error messages with */
68 flag configdump; /* dump control blocks for configurator */
69 const char *fetchmailhost; /* either `localhost' or the host's FQDN */
74 #endif /* NET_SECURITY */
76 static char *lockfile; /* name of lockfile */
77 static int querystatus; /* status of query */
78 static int successes; /* count number of successful polls */
79 static int lastsig; /* last signal received */
80 static struct runctl cmd_run; /* global options set from command line */
82 static void termhook(int); /* forward declaration of exit hook */
85 #define SLEEP_WITH_ALARM
88 #ifdef SLEEP_WITH_ALARM
90 * The function of this variable is to remove the window during which a
91 * SIGALRM can hose the code (ALARM is triggered *before* pause() is called).
92 * This is a bit of a kluge; the real right thing would use sigprocmask(),
94 * This work around lets the interval timer trigger the first alarm after the
95 * required interval and will then generate alarms all 5 seconds, until it
96 * is certain, that the critical section (ie., the window) is left.
98 #if defined(STDC_HEADERS)
99 static sig_atomic_t alarm_latch = FALSE;
101 /* assume int can be written in one atomic operation on non ANSI-C systems */
102 static int alarm_latch = FALSE;
105 RETSIGTYPE gotsigalrm(sig)
108 signal(sig, gotsigalrm);
112 #endif /* SLEEP_WITH_ALARM */
114 RETSIGTYPE donothing(int sig) {signal(sig, donothing); lastsig = sig;}
117 static void unlockit(int n, void *p)
119 static void unlockit(void)
121 /* must-do actions for exit (but we can't count on being able to do malloc) */
127 /* Various EMX-specific definitions */
129 void itimerthread(void* dummy) {
130 if (outlevel >= O_VERBOSE)
131 fprintf(stderr, "fetchmail: thread sleeping for %d sec.\n", poll_interval);
133 _sleep2(poll_interval*1000);
134 kill((getpid()), SIGALRM);
139 int main (int argc, char **argv)
141 int st, bkgd = FALSE;
142 int parsestatus, implicitmode = FALSE;
145 netrc_entry *netrc_list;
146 char *netrc_file, *tmpbuf;
149 envquery(argc, argv);
151 #define IDFILE_NAME ".fetchids"
152 run.idfile = (char *) xmalloc(strlen(home)+strlen(IDFILE_NAME)+2);
153 strcpy(run.idfile, home);
154 strcat(run.idfile, "/");
155 strcat(run.idfile, IDFILE_NAME);
159 if ((parsestatus = parsecmdline(argc,argv, &cmd_run, &cmd_opts)) < 0)
162 /* this hint to stdio should help messages come out in the right order */
163 setvbuf(stdout, NULL, _IOLBF, MSGBUFSIZE);
167 printf("This is fetchmail release %s", RELEASE_ID);
170 #endif /* POP2_ENABLE */
173 #endif /* POP3_ENABLE */
176 #endif /* IMAP_ENABLE */
182 #endif /* RPA_ENABLE */
185 #endif /* SDPS_ENABLE */
188 #endif /* ETRN_ENABLE */
197 #endif /* NET_SECURITY */
202 #endif /* HAVE_SOCKS */
205 /* this is an attempt to help remote debugging */
209 /* avoid parsing the config file if all we're doing is killing a daemon */
210 if (!(quitmode && argc == 2))
211 implicitmode = load_params(argc, argv, optind);
213 /* set up to do lock protocol */
214 #define FETCHMAIL_PIDFILE "fetchmail.pid"
215 xalloca(tmpbuf, char *, strlen(home) + strlen(FETCHMAIL_PIDFILE) + 3);
217 sprintf(tmpbuf, "%s/%s", PID_DIR, FETCHMAIL_PIDFILE);
219 strcpy(tmpbuf, home);
220 strcat(tmpbuf, "/.");
221 strcat(tmpbuf, FETCHMAIL_PIDFILE);
223 #undef FETCHMAIL_PIDFILE
225 /* perhaps we just want to check options? */
228 printf("Taking options from command line");
229 if (access(rcfile, 0))
232 printf(" and %s\n", rcfile);
233 if (outlevel >= O_VERBOSE)
234 printf("Lockfile at %s\n", tmpbuf);
236 if (querylist == NULL)
237 (void) fprintf(stderr,
238 "No mailservers set up -- perhaps %s is missing?\n", rcfile);
240 dump_params(&run, querylist, implicitmode);
244 /* dump options as a Python dictionary, for configurator use */
247 dump_config(&run, querylist);
251 /* check for another fetchmail running concurrently */
253 if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
255 fprintf(stderr,"fetchmail: cannot allocate memory for lock name.\n");
259 (void) strcpy(lockfile, tmpbuf);
260 if ((lockfp = fopen(lockfile, "r")) != NULL )
262 bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
264 if (kill(pid, 0) == -1) {
265 fprintf(stderr,"fetchmail: removing stale lockfile\n");
273 /* if no mail servers listed and nothing in background, we're done */
274 if (!(quitmode && argc == 2) && pid == -1 && querylist == NULL) {
275 (void)fputs("fetchmail: no mailservers have been specified.\n",stderr);
279 /* perhaps user asked us to kill the other fetchmail */
284 fprintf(stderr,"fetchmail: no other fetchmail is running\n");
288 else if (kill(pid, SIGTERM) < 0)
290 fprintf(stderr,"fetchmail: error killing %s fetchmail at %d; bailing out.\n",
291 bkgd ? "background" : "foreground", pid);
296 fprintf(stderr,"fetchmail: %s fetchmail at %d killed.\n",
297 bkgd ? "background" : "foreground", pid);
306 /* another fetchmail is running -- wake it up or die */
312 "fetchmail: can't check mail while another fetchmail to same host is running.\n");
315 else if (!implicitmode)
318 "fetchmail: can't poll specified hosts with another fetchmail running at %d.\n",
325 "fetchmail: another foreground fetchmail is running at %d.\n",
332 "fetchmail: can't accept options while a background fetchmail is running.\n");
335 else if (kill(pid, SIGUSR1) == 0)
338 "fetchmail: background fetchmail at %d awakened.\n",
345 * Should never happen -- possible only if a background fetchmail
346 * croaks after the first kill probe above but before the
347 * SIGUSR1/SIGHUP transmission.
350 "fetchmail: elder sibling at %d died mysteriously.\n",
352 return(PS_UNDEFINED);
356 /* parse the ~/.netrc file (if present) for future password lookups. */
357 xalloca(netrc_file, char *, strlen (home) + 8);
358 strcpy (netrc_file, home);
359 strcat (netrc_file, "/.netrc");
360 netrc_list = parse_netrc(netrc_file);
362 #ifdef HAVE_SETRLIMIT
364 * Before getting passwords, disable core dumps unless -v -d0 mode is on.
365 * Core dumps could otherwise contain passwords to be scavenged by a
368 if (outlevel < O_VERBOSE || run.poll_interval > 0)
370 struct rlimit corelimit;
371 corelimit.rlim_cur = 0;
372 corelimit.rlim_max = 0;
373 setrlimit(RLIMIT_CORE, &corelimit);
375 #endif /* HAVE_SETRLIMIT */
377 /* pick up interactively any passwords we need but don't have */
378 for (ctl = querylist; ctl; ctl = ctl->next)
380 ctl->authfailcount = 0;
382 if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
384 if (ctl->server.preauthenticate == A_KERBEROS_V4 ||
385 ctl->server.preauthenticate == A_KERBEROS_V5 ||
387 ctl->server.protocol == P_IMAP_GSS ||
389 ctl->server.protocol == P_IMAP_K4)
390 /* Server won't care what the password is, but there
391 must be some non-null string here. */
392 ctl->password = ctl->remotename;
395 /* look up the host and account in the .netrc file. */
396 netrc_entry *p = search_netrc(netrc_list,ctl->server.pollname);
397 while (p && strcmp(p->account, ctl->remotename))
398 p = search_netrc(p->next, ctl->remotename);
400 /* if we find a matching entry with a password, use it */
401 if (p && p->password)
402 ctl->password = xstrdup(p->password);
405 if (ctl->server.protocol != P_ETRN && ctl->server.protocol != P_IMAP_K4
407 && ctl->server.protocol != P_IMAP_GSS
411 #define PASSWORD_PROMPT "Enter password for %s@%s: "
412 xalloca(tmpbuf, char *, strlen(PASSWORD_PROMPT) +
413 strlen(ctl->remotename) +
414 strlen(ctl->server.pollname) + 1);
415 (void) sprintf(tmpbuf, PASSWORD_PROMPT,
416 ctl->remotename, ctl->server.pollname);
417 ctl->password = xstrdup((char *)getpassword(tmpbuf));
418 #undef PASSWORD_PROMPT
423 /* Time to initiate the SOCKS library (this is not mandatory: it just
424 registers the correct application name for logging purpose. If you
425 have some problem, comment these lines). */
428 /* Mmmh... I don't like hardcoded application names,
429 but "fetchmail" is everywhere... */
430 SOCKSinit("fetchmail");
432 #endif /* HAVE_SOCKS */
435 * Maybe time to go to demon mode...
437 #if defined(HAVE_SYSLOG)
440 openlog(program_name, LOG_PID, LOG_MAIL);
445 error_init((run.poll_interval == 0 || nodetach) && !run.logfile);
447 if (run.poll_interval)
450 daemonize(run.logfile, termhook);
451 error( 0, 0, "starting fetchmail %s daemon ", RELEASE_ID);
454 * We'll set up a handler for these when we're sleeping,
455 * but ignore them otherwise so as not to interrupt a poll.
457 signal(SIGUSR1, SIG_IGN);
458 if (run.poll_interval && !getuid())
459 signal(SIGHUP, SIG_IGN);
462 /* beyond here we don't want more than one fetchmail running per user */
464 signal(SIGABRT, termhook);
465 signal(SIGINT, termhook);
466 signal(SIGTERM, termhook);
467 signal(SIGALRM, termhook);
468 signal(SIGPIPE, termhook);
469 signal(SIGQUIT, termhook);
471 /* here's the exclusion lock */
472 if ((lockfp = fopen(lockfile,"w")) != NULL) {
473 fprintf(lockfp,"%d",getpid());
474 if (run.poll_interval)
475 fprintf(lockfp," %d", run.poll_interval);
482 on_exit(unlockit, (char *)NULL);
487 * Query all hosts. If there's only one, the error return will
488 * reflect the status of that transaction.
491 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
493 * This was an efficiency hack that backfired. The theory
494 * was that using TCP/IP for DNS queries would get us better
495 * reliability and shave off some per-UDP-packet costs.
496 * Unfortunately it interacted badly with diald, which effectively
497 * filters out DNS queries over TCP/IP for reasons having to do
498 * with some obscure kernel problem involving bootstrapping of
499 * dynamically-addressed links. I don't understand this mess
500 * and don't want to, so it's "See ya!" to this hack.
502 sethostent(TRUE); /* use TCP/IP for mailserver queries */
503 #endif /* HAVE_RES_SEARCH */
506 for (ctl = querylist; ctl; ctl = ctl->next)
508 if (ctl->authfailcount)
511 "poll of %s skipped until authentication is unwedged",
512 ctl->server.pollname);
515 if (ctl->active && !(implicitmode && ctl->server.skip))
517 /* check skip interval first so that it counts all polls */
518 if (run.poll_interval && ctl->server.interval)
520 if (ctl->server.poll_count++ % ctl->server.interval)
522 if (outlevel >= O_VERBOSE)
524 "interval not reached, not querying %s",
525 ctl->server.pollname);
530 #if defined(linux) && !INET6
531 /* interface_approve() does its own error logging */
532 if (!interface_approve(&ctl->server))
534 #endif /* defined(linux) && !INET6 */
536 querystatus = query_host(ctl);
538 if (querystatus == PS_SUCCESS)
543 update_str_lists(ctl);
545 /* Save UID list to prevent re-fetch in case fetchmail
546 recover from crash */
549 write_saved_lists(querylist, run.idfile);
550 if (outlevel >= O_DEBUG)
551 error(0, 0, "saved UID List");
553 #endif /* POP3_ENABLE */
555 else if (!check_only &&
556 ((querystatus!=PS_NOMAIL) || (outlevel==O_DEBUG)))
557 error(0, 0, "Query status=%d", querystatus);
559 #if defined(linux) && !INET6
560 if (ctl->server.monitor)
563 * Allow some time for the link to quiesce. One
564 * second is usually sufficient, three is safe.
565 * Note: this delay is important - don't remove!
568 interface_note_activity(&ctl->server);
570 #endif /* defined(linux) && !INET6 */
574 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
575 endhostent(); /* release TCP/IP connection to nameserver */
576 #endif /* HAVE_RES_SEARCH */
579 * Close all SMTP delivery sockets. For optimum performance
580 * we'd like to hold them open til end of run, but (1) this
581 * loses if our poll interval is longer than the MTA's inactivity
582 * timeout, and (2) some MTAs (like smail) don't deliver after
583 * each message, but rather queue up mail and wait to actually
584 * deliver it until the input socket is closed.
586 for (ctl = querylist; ctl; ctl = ctl->next)
587 if (ctl->smtp_socket != -1)
589 SMTP_quit(ctl->smtp_socket);
590 close(ctl->smtp_socket);
591 ctl->smtp_socket = -1;
595 * OK, we've polled. Now sleep.
597 if (run.poll_interval)
600 * Because passwords can expire, it may happen that *all*
601 * hosts are now out of the loop due to authfail
602 * conditions. If this happens daemon-mode fetchmail
603 * should softly and silently vanish away, rather than
604 * spinning uselessly.
608 for (ctl = querylist; ctl; ctl = ctl->next)
609 if (!ctl->authfailcount)
613 error(0, -1, "All authentications have failed. Exiting.");
617 if (outlevel >= O_VERBOSE)
618 error(0, -1, "fetchmail: sleeping at %s", rfc822timestamp());
621 * With this simple hack, we make it possible for a foreground
622 * fetchmail to wake up one in daemon mode. What we want is the
623 * side effect of interrupting any sleep that may be going on,
624 * forcing fetchmail to re-poll its hosts. The second line is
625 * for people who think all system daemons wake up on SIGHUP.
627 signal(SIGUSR1, donothing);
629 signal(SIGHUP, donothing);
632 * We can't use sleep(3) here because we need an alarm(3)
633 * equivalent in order to implement server nonresponse timeout.
634 * We'll just assume setitimer(2) is available since fetchmail
635 * has to have a BSDoid socket layer to work at all.
639 #ifdef SLEEP_WITH_ALARM /* not normally on */
641 * This code stopped working under glibc-2, apparently due
642 * to the change in signal(2) semantics. (The siginterrupt
643 * line, added later, should fix this problem.) John Stracke
644 * <francis@netscape.com> wrote:
646 * The problem seems to be that, after hitting the interval
647 * timer while talking to the server, the process no longer
648 * responds to SIGALRM. I put in printf()s to see when it
649 * reached the pause() for the poll interval, and I checked
650 * the return from setitimer(), and everything seemed to be
651 * working fine, except that the pause() just ignored SIGALRM.
652 * I thought maybe the itimer wasn't being fired, so I hit
653 * it with a SIGALRM from the command line, and it ignored
654 * that, too. SIGUSR1 woke it up just fine, and it proceeded
655 * to repoll--but, when the dummy server didn't respond, it
656 * never timed out, and SIGALRM wouldn't make it.
658 * (continued below...)
660 struct itimerval ntimeout;
662 ntimeout.it_interval.tv_sec = 5; /* repeat alarm every 5 secs */
663 ntimeout.it_interval.tv_usec = 0;
664 ntimeout.it_value.tv_sec = run.poll_interval;
665 ntimeout.it_value.tv_usec = 0;
667 siginterrupt(SIGALRM, 1);
669 signal(SIGALRM, gotsigalrm); /* first trap signals */
670 setitimer(ITIMER_REAL,&ntimeout,NULL); /* then start timer */
671 /* there is a very small window between the next two lines */
672 /* which could result in a deadlock. But this will now be */
673 /* caught by periodical alarms (see it_interval) */
677 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
678 ntimeout.it_value.tv_sec = ntimeout.it_value.tv_usec = 0;
679 setitimer(ITIMER_REAL,&ntimeout,NULL); /* now stop timer */
680 signal(SIGALRM, SIG_IGN);
683 * So the workaround I used is to make it sleep by using
684 * select() instead of setitimer()/pause(). select() is
685 * perfectly happy being called with a timeout and
686 * no file descriptors; it just sleeps until it hits the
687 * timeout. The only concern I had was that it might
688 * implement its timeout with SIGALRM--there are some
689 * Unices where this is done, because select() is a library
690 * function--but apparently not.
692 struct timeval timeout;
694 timeout.tv_sec = run.poll_interval;
697 select(0,0,0,0, &timeout);
701 signal(SIGALRM, gotsigalrm);
702 _beginthread(itimerthread, NULL, 32768, NULL);
703 /* see similar code above */
706 signal(SIGALRM, SIG_IGN);
708 if (lastsig == SIGUSR1
709 || ((run.poll_interval && !getuid()) && lastsig == SIGHUP))
711 #ifdef SYS_SIGLIST_DECLARED
712 error(0, 0, "awakened by %s", sys_siglist[lastsig]);
714 error(0, 0, "awakened by signal %d", lastsig);
719 /* now lock out interrupts again */
720 signal(SIGUSR1, SIG_IGN);
722 signal(SIGHUP, SIG_IGN);
724 if (outlevel >= O_VERBOSE)
725 error(0, -1, "awakened at %s", rfc822timestamp());
730 if (outlevel >= O_VERBOSE)
731 error(0, -1, "normal termination, status %d",
732 successes ? PS_SUCCESS : querystatus);
735 exit(successes ? PS_SUCCESS : querystatus);
738 static void optmerge(struct query *h2, struct query *h1, int force)
739 /* merge two options records */
742 * If force is off, modify h2 fields only when they're empty (treat h1
743 * as defaults). If force is on, modify each h2 field whenever h1
744 * is nonempty (treat h1 as an override).
746 #define LIST_MERGE(dstl, srcl) if (force ? !!srcl : !dstl) \
747 free_str_list(&dstl), \
748 append_str_list(&dstl, &srcl)
749 LIST_MERGE(h2->server.localdomains, h1->server.localdomains);
750 LIST_MERGE(h2->localnames, h1->localnames);
751 LIST_MERGE(h2->mailboxes, h1->mailboxes);
752 LIST_MERGE(h2->smtphunt, h1->smtphunt);
753 LIST_MERGE(h2->antispam, h1->antispam);
756 #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld
757 FLAG_MERGE(server.via);
758 FLAG_MERGE(server.protocol);
760 FLAG_MERGE(server.service);
761 FLAG_MERGE(server.netsec);
763 FLAG_MERGE(server.port);
765 FLAG_MERGE(server.interval);
766 FLAG_MERGE(server.preauthenticate);
767 FLAG_MERGE(server.timeout);
768 FLAG_MERGE(server.envelope);
769 FLAG_MERGE(server.envskip);
770 FLAG_MERGE(server.qvirtual);
771 FLAG_MERGE(server.skip);
772 FLAG_MERGE(server.dns);
773 FLAG_MERGE(server.checkalias);
774 FLAG_MERGE(server.uidl);
777 FLAG_MERGE(server.interface);
778 FLAG_MERGE(server.monitor);
779 FLAG_MERGE(server.interface_pair);
782 FLAG_MERGE(server.plugin);
783 FLAG_MERGE(server.plugout);
784 FLAG_MERGE(wildcard);
785 FLAG_MERGE(remotename);
786 FLAG_MERGE(password);
789 FLAG_MERGE(listener);
790 FLAG_MERGE(smtpaddress);
791 FLAG_MERGE(preconnect);
792 FLAG_MERGE(postconnect);
796 FLAG_MERGE(fetchall);
800 FLAG_MERGE(pass8bits);
801 FLAG_MERGE(dropstatus);
802 FLAG_MERGE(mimedecode);
804 FLAG_MERGE(warnings);
805 FLAG_MERGE(fetchlimit);
806 FLAG_MERGE(batchlimit);
809 FLAG_MERGE(properties);
813 static int load_params(int argc, char **argv, int optind)
815 int implicitmode, st;
817 struct query def_opts, *ctl;
819 memset(&def_opts, '\0', sizeof(struct query));
820 def_opts.smtp_socket = -1;
821 def_opts.smtpaddress = (char *)0;
822 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 571;
823 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 550;
824 save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = 501;
826 def_opts.server.protocol = P_AUTO;
827 def_opts.server.timeout = CLIENT_TIMEOUT;
828 def_opts.warnings = WARNING_INTERVAL;
829 def_opts.remotename = user;
830 def_opts.expunge = 1;
831 def_opts.listener = SMTP_MODE;
833 /* this builds the host list */
834 if (prc_parse_file(rcfile, !versioninfo) != 0)
837 if ((implicitmode = (optind >= argc)))
839 for (ctl = querylist; ctl; ctl = ctl->next)
843 for (; optind < argc; optind++)
845 flag predeclared = FALSE;
848 * If hostname corresponds to a host known from the rc file,
849 * simply declare it active. Otherwise synthesize a host
850 * record from command line and defaults
852 for (ctl = querylist; ctl; ctl = ctl->next)
853 if (!strcmp(ctl->server.pollname, argv[optind])
854 || str_in_list(&ctl->server.akalist, argv[optind], TRUE))
856 /* Is this correct? */
858 fprintf(stderr,"Warning: multiple mentions of host %s in config file\n",argv[optind]);
866 * Allocate and link record without copying in
867 * command-line args; we'll do that with the optmerge
870 ctl = hostalloc((struct query *)NULL);
872 ctl->server.pollname = xstrdup(argv[optind]);
874 ctl->server.lead_server = (struct hostdata *)NULL;
879 * If there's a defaults record, merge it and lose it.
881 if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
883 for (ctl = querylist->next; ctl; ctl = ctl->next)
884 optmerge(ctl, querylist, FALSE);
885 querylist = querylist->next;
888 /* don't allow a defaults record after the first */
889 for (ctl = querylist; ctl; ctl = ctl->next)
890 if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
893 /* use localhost if we never fetch the FQDN of this host */
894 fetchmailhost = "localhost";
896 /* merge in wired defaults, do sanity checks and prepare internal fields */
897 for (ctl = querylist; ctl; ctl = ctl->next)
899 if (configdump || (ctl->active && !(implicitmode && ctl->server.skip)))
901 /* merge in defaults */
902 optmerge(ctl, &def_opts, FALSE);
904 /* force command-line options */
905 optmerge(ctl, &cmd_opts, TRUE);
907 /* this code enables flags to be turned off */
908 #define DEFAULT(flag, dflt) if (flag == FLAG_TRUE)\
910 else if (flag == FLAG_FALSE)\
914 DEFAULT(ctl->keep, FALSE);
915 DEFAULT(ctl->fetchall, FALSE);
916 DEFAULT(ctl->flush, FALSE);
917 DEFAULT(ctl->rewrite, TRUE);
918 DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL));
919 DEFAULT(ctl->forcecr, FALSE);
920 DEFAULT(ctl->pass8bits, FALSE);
921 DEFAULT(ctl->dropstatus, FALSE);
922 DEFAULT(ctl->mimedecode, FALSE);
923 DEFAULT(ctl->server.dns, TRUE);
924 DEFAULT(ctl->server.uidl, FALSE);
925 DEFAULT(ctl->server.checkalias, FALSE);
929 * DNS support is required for some protocols.
931 * If we're using ETRN, the smtp hunt list is the list of
932 * systems we're polling on behalf of; these have to be
933 * fully-qualified domain names. The default for this list
934 * should be the FQDN of localhost.
936 * If we're using Kerberos for authentication, we need
937 * the FQDN in order to generate capability keys.
939 if (ctl->server.protocol == P_ETRN
940 || ctl->server.preauthenticate == A_KERBEROS_V4
941 || ctl->server.preauthenticate == A_KERBEROS_V5)
942 if (strcmp(fetchmailhost, "localhost") == 0)
943 fetchmailhost = host_fqdn();
946 * Make sure we have a nonempty host list to forward to.
949 save_str(&ctl->smtphunt, fetchmailhost, FALSE);
951 /* if `user' doesn't name a real local user, try to run as root */
952 if ((pw = getpwnam(user)) == (struct passwd *)NULL)
955 ctl->uid = pw->pw_uid; /* for local delivery via MDA */
956 if (!ctl->localnames) /* for local delivery via SMTP */
957 save_str_pair(&ctl->localnames, user, NULL);
959 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
960 /* can't handle multidrop mailboxes unless we can do DNS lookups */
961 if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
963 ctl->server.dns = FALSE;
964 fprintf(stderr, "fetchmail: warning: no DNS available to check multidrop fetches from %s\n", ctl->server.pollname);
966 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
970 * Compute the true name of the mailserver host.
971 * There are two clashing cases here:
973 * (1) The poll name is a label, possibly on one of several
974 * poll configurations for the same host. In this case
975 * the `via' option will be present and give the true name.
977 * (2) The poll name is the true one, the via name is
978 * localhost. This is going to be typical for ssh-using
981 * We're going to assume the via name is true unless it's
984 if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
985 ctl->server.queryname = xstrdup(ctl->server.via);
987 ctl->server.queryname = xstrdup(ctl->server.pollname);
990 /* If either the pollname or vianame are "hesiod" we want to
991 lookup the user's hesiod pobox host */
993 if (!strcasecmp(ctl->server.queryname, "hesiod")) {
994 struct hes_postoffice *hes_p;
995 hes_p = hes_getmailhost(ctl->remotename);
996 if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
997 free(ctl->server.queryname);
998 ctl->server.queryname = xstrdup(hes_p->po_host);
1000 free(ctl->server.via);
1001 ctl->server.via = xstrdup(hes_p->po_host);
1003 error(0, errno, "couldn't find HESIOD pobox for %s",
1010 * We may have to canonicalize the server truename for later use.
1011 * Do this just once for each lead server, if necessary, in order
1012 * to minimize DNS round trips.
1014 if (ctl->server.lead_server)
1015 ctl->server.truename = xstrdup(ctl->server.lead_server->truename);
1016 #ifdef HAVE_GETHOSTBYNAME
1017 else if (ctl->server.preauthenticate==A_KERBEROS_V4 ||
1018 ctl->server.preauthenticate==A_KERBEROS_V5 ||
1019 (ctl->server.dns && MULTIDROP(ctl)))
1021 struct hostent *namerec;
1023 /* compute the canonical name of the host */
1025 namerec = gethostbyname(ctl->server.queryname);
1026 if (namerec == (struct hostent *)NULL)
1029 "couldn't find canonical DNS name of %s",
1030 ctl->server.pollname);
1034 ctl->server.truename=xstrdup((char *)namerec->h_name);
1036 #endif /* HAVE_GETHOSTBYNAME */
1038 ctl->server.truename = xstrdup(ctl->server.queryname);
1040 /* if no folders were specified, set up the null one as default */
1041 if (!ctl->mailboxes)
1042 save_str(&ctl->mailboxes, (char *)NULL, 0);
1044 /* maybe user overrode timeout on command line? */
1045 if (ctl->server.timeout == -1)
1046 ctl->server.timeout = CLIENT_TIMEOUT;
1050 if (ctl->server.port < 0)
1052 (void) fprintf(stderr,
1053 "%s configuration invalid, port number cannot be negative",
1054 ctl->server.pollname);
1057 if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
1059 (void) fprintf(stderr,
1060 "%s configuration invalid, RPOP requires a privileged port",
1061 ctl->server.pollname);
1064 if (ctl->server.port == 25 && ctl->listener == LMTP_MODE)
1066 (void) fprintf(stderr,
1067 "%s configuration invalid, LMTP can't use SMTP port",
1068 ctl->server.pollname);
1075 /* here's where we override globals */
1076 if (cmd_run.logfile)
1077 run.logfile = cmd_run.logfile;
1079 run.idfile = cmd_run.idfile;
1080 if (cmd_run.poll_interval >= 0)
1081 run.poll_interval = cmd_run.poll_interval;
1082 if (cmd_run.invisible)
1083 run.invisible = cmd_run.invisible;
1084 if (cmd_run.use_syslog)
1085 run.use_syslog = (cmd_run.use_syslog == FLAG_TRUE);
1086 if (cmd_run.postmaster)
1087 run.postmaster = cmd_run.postmaster;
1089 /* check and daemon options are not compatible */
1090 if (check_only && run.poll_interval)
1091 run.poll_interval = 0;
1094 /* initialize UID handling */
1095 if (!versioninfo && (st = prc_filecheck(run.idfile, !versioninfo)) != 0)
1098 initialize_saved_lists(querylist, run.idfile);
1099 #endif /* POP3_ENABLE */
1102 * If the user didn't set a last-resort user to get misaddressed
1103 * multidrop mail, set an appropriate default here.
1105 if (!run.postmaster)
1106 if (getuid()) /* ordinary user */
1107 run.postmaster = user;
1109 run.postmaster = "postmaster";
1111 return(implicitmode);
1114 void termhook(int sig)
1115 /* to be executed on normal or signal-induced termination */
1120 * Sending SMTP QUIT on signal is theoretically nice, but led to a
1121 * subtle bug. If fetchmail was terminated by signal while it was
1122 * shipping message text, it would hang forever waiting for a
1123 * command acknowledge. In theory we could enable the QUIT
1124 * only outside of the message send. In practice, we don't
1125 * care. All mailservers hang up on a dropped TCP/IP connection
1130 error(0, 0, "terminated with signal %d", sig);
1132 /* terminate all SMTP connections cleanly */
1133 for (ctl = querylist; ctl; ctl = ctl->next)
1134 if (ctl->smtp_socket != -1)
1135 SMTP_quit(ctl->smtp_socket);
1139 write_saved_lists(querylist, run.idfile);
1140 #endif /* POP3_ENABLE */
1143 * Craig Metz, the RFC1938 one-time-password guy, points out:
1144 * "Remember that most kernels don't zero pages before handing them to the
1145 * next process and many kernels share pages between user and kernel space.
1146 * You'd be very surprised what you can find from a short program to do a
1147 * malloc() and then dump the contents of the pages you got. By zeroing
1148 * the secrets at end of run (earlier if you can), you make sure the next
1149 * guy can't get the password/pass phrase."
1151 * Right you are, Craig!
1153 for (ctl = querylist; ctl; ctl = ctl->next)
1155 memset(ctl->password, '\0', strlen(ctl->password));
1157 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
1161 exit(successes ? PS_SUCCESS : querystatus);
1165 * Sequence of protocols to try when autoprobing, most capable to least.
1167 static const int autoprobe[] =
1171 #endif /* IMAP_ENABLE */
1174 #endif /* POP3_ENABLE */
1177 #endif /* POP2_ENABLE */
1180 static int query_host(struct query *ctl)
1181 /* perform fetch transaction with single host */
1185 if (outlevel >= O_VERBOSE)
1190 error(0, -1, "fetchmail: %s querying %s (protocol %s) at %s",
1192 ctl->server.pollname, showproto(ctl->server.protocol), ctime(&now));
1194 switch (ctl->server.protocol) {
1196 for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
1198 ctl->server.protocol = autoprobe[i];
1199 if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
1202 ctl->server.protocol = P_AUTO;
1207 return(doPOP2(ctl));
1209 error(0, -1, "POP2 support is not configured.\n");
1210 return(PS_PROTOCOL);
1211 #endif /* POP2_ENABLE */
1217 return(doPOP3(ctl));
1219 error(0, -1, "POP3 support is not configured.\n");
1220 return(PS_PROTOCOL);
1221 #endif /* POP3_ENABLE */
1229 return(doIMAP(ctl));
1231 error(0, -1, "IMAP support is not configured.\n");
1232 return(PS_PROTOCOL);
1233 #endif /* IMAP_ENABLE */
1237 error(0, -1, "ETRN support is not configured.\n");
1238 return(PS_PROTOCOL);
1240 #ifdef HAVE_GETHOSTBYNAME
1241 return(doETRN(ctl));
1243 error(0, -1, "Cannot support ETRN without gethostbyname(2).\n");
1244 return(PS_PROTOCOL);
1245 #endif /* HAVE_GETHOSTBYNAME */
1246 #endif /* ETRN_ENABLE */
1248 error(0, 0, "unsupported protocol selected.");
1249 return(PS_PROTOCOL);
1253 void dump_params (struct runctl *runp, struct query *querylist, flag implicit)
1254 /* display query parameters in English */
1258 if (runp->poll_interval)
1259 printf("Poll interval is %d seconds\n", runp->poll_interval);
1261 printf("Logfile is %s\n", runp->logfile);
1262 if (strcmp(runp->idfile, IDFILE_NAME))
1263 printf("Idfile is %s\n", runp->idfile);
1264 #if defined(HAVE_SYSLOG)
1265 if (runp->use_syslog)
1266 printf("Progress messages will be logged via syslog\n");
1268 if (runp->invisible)
1269 printf("Fetchmail will masquerade and will not generate Received\n");
1270 if (runp->postmaster)
1271 printf("Fetchmail will forward misaddressed multidrop messages to %s.\n",
1274 for (ctl = querylist; ctl; ctl = ctl->next)
1276 if (!ctl->active || (implicit && ctl->server.skip))
1279 printf("Options for retrieving from %s@%s:\n",
1280 ctl->remotename, visbuf(ctl->server.pollname));
1282 if (ctl->server.via && (ctl->server.protocol != P_ETRN))
1283 printf(" Mail will be retrieved via %s\n", ctl->server.via);
1285 if (ctl->server.interval)
1286 printf(" Poll of this server will occur every %d intervals.\n",
1287 ctl->server.interval);
1288 if (ctl->server.truename)
1289 printf(" True name of server is %s.\n", ctl->server.truename);
1290 if (ctl->server.skip || outlevel >= O_VERBOSE)
1291 printf(" This host will%s be queried when no host is specified.\n",
1292 ctl->server.skip ? " not" : "");
1294 * Don't poll for password when there is one or when using the ETRN
1295 * or IMAP-GSS protocol
1297 if (!ctl->password && (ctl->server.protocol != P_ETRN)
1299 && (ctl->server.protocol != P_IMAP_GSS)
1302 printf(" Password will be prompted for.\n");
1303 else if (outlevel >= O_VERBOSE)
1304 if (ctl->server.protocol == P_APOP)
1305 printf(" APOP secret = \"%s\".\n", visbuf(ctl->password));
1306 else if (ctl->server.protocol == P_RPOP)
1307 printf(" RPOP id = \"%s\".\n", visbuf(ctl->password));
1309 printf(" Password = \"%s\".\n", visbuf(ctl->password));
1310 if (ctl->server.protocol == P_POP3
1312 && !strcmp(ctl->server.service, KPOP_PORT)
1314 && ctl->server.port == KPOP_PORT
1316 && (ctl->server.preauthenticate == A_KERBEROS_V4 ||
1317 ctl->server.preauthenticate == A_KERBEROS_V5))
1318 printf(" Protocol is KPOP with Kerberos %s authentication",
1319 ctl->server.preauthenticate == A_KERBEROS_V5 ? "V" : "IV");
1321 printf(" Protocol is %s", showproto(ctl->server.protocol));
1323 if (ctl->server.service)
1324 printf(" (using service %s)", ctl->server.service);
1325 if (ctl->server.netsec)
1326 printf(" (using network security options %s)", ctl->server.netsec);
1328 if (ctl->server.port)
1329 printf(" (using port %d)", ctl->server.port);
1331 else if (outlevel >= O_VERBOSE)
1332 printf(" (using default port)");
1333 if (ctl->server.uidl && (ctl->server.protocol != P_ETRN))
1334 printf(" (forcing UIDL use)");
1337 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1338 printf(" Kerberos V4 preauthentication enabled.\n");
1339 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1340 printf(" Kerberos V5 preauthentication enabled.\n");
1341 if (ctl->server.timeout > 0)
1342 printf(" Server nonresponse timeout is %d seconds", ctl->server.timeout);
1343 if (ctl->server.timeout == CLIENT_TIMEOUT)
1344 printf(" (default).\n");
1348 if (ctl->server.protocol != P_ETRN) {
1349 if (!ctl->mailboxes->id)
1350 printf(" Default mailbox selected.\n");
1355 printf(" Selected mailboxes are:");
1356 for (idp = ctl->mailboxes; idp; idp = idp->next)
1357 printf(" %s", idp->id);
1360 printf(" %s messages will be retrieved (--all %s).\n",
1361 ctl->fetchall ? "All" : "Only new",
1362 ctl->fetchall ? "on" : "off");
1363 printf(" Fetched messages will%s be kept on the server (--keep %s).\n",
1364 ctl->keep ? "" : " not",
1365 ctl->keep ? "on" : "off");
1366 printf(" Old messages will%s be flushed before message retrieval (--flush %s).\n",
1367 ctl->flush ? "" : " not",
1368 ctl->flush ? "on" : "off");
1369 printf(" Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
1370 ctl->rewrite ? "en" : "dis",
1371 ctl->rewrite ? "off" : "on");
1372 printf(" Carriage-return stripping is %sabled (stripcr %s).\n",
1373 ctl->stripcr ? "en" : "dis",
1374 ctl->stripcr ? "on" : "off");
1375 printf(" Carriage-return forcing is %sabled (forcecr %s).\n",
1376 ctl->forcecr ? "en" : "dis",
1377 ctl->forcecr ? "on" : "off");
1378 printf(" Interpretation of Content-Transfer-Encoding is %sabled (pass8bits %s).\n",
1379 ctl->pass8bits ? "dis" : "en",
1380 ctl->pass8bits ? "on" : "off");
1381 printf(" MIME decoding is %sabled (mimedecode %s).\n",
1382 ctl->mimedecode ? "en" : "dis",
1383 ctl->mimedecode ? "on" : "off");
1384 printf(" Nonempty Status lines will be %s (dropstatus %s)\n",
1385 ctl->dropstatus ? "discarded" : "kept",
1386 ctl->dropstatus ? "on" : "off");
1387 if (NUM_NONZERO(ctl->limit))
1389 if (NUM_NONZERO(ctl->limit))
1390 printf(" Message size limit is %d bytes (--limit %d).\n",
1391 ctl->limit, ctl->limit);
1392 else if (outlevel >= O_VERBOSE)
1393 printf(" No message size limit (--limit 0).\n");
1394 if (run.poll_interval > 0)
1395 printf(" Message size warning interval is %d seconds (--warnings %d).\n",
1396 ctl->warnings, ctl->warnings);
1397 else if (outlevel >= O_VERBOSE)
1398 printf(" Size warnings on every poll (--warnings 0).\n");
1400 if (NUM_NONZERO(ctl->fetchlimit))
1401 printf(" Received-message limit is %d (--fetchlimit %d).\n",
1402 ctl->fetchlimit, ctl->fetchlimit);
1403 else if (outlevel >= O_VERBOSE)
1404 printf(" No received-message limit (--fetchlimit 0).\n");
1405 if (NUM_NONZERO(ctl->batchlimit))
1406 printf(" SMTP message batch limit is %d.\n", ctl->batchlimit);
1407 else if (outlevel >= O_VERBOSE)
1408 printf(" No SMTP message batch limit (--batchlimit 0).\n");
1409 if (ctl->server.protocol == P_IMAP)
1410 if (NUM_NONZERO(ctl->expunge))
1411 printf(" Deletion interval between expunges is %d (--expunge %d).\n", ctl->expunge, ctl->expunge);
1412 else if (outlevel >= O_VERBOSE)
1413 printf(" No expunges (--expunge 0).\n");
1416 printf(" Messages will be appended to %s as BSMTP\n", visbuf(ctl->bsmtp));
1417 else if (ctl->mda && (ctl->server.protocol != P_ETRN))
1418 printf(" Messages will be delivered with \"%s\".\n", visbuf(ctl->mda));
1423 printf(" Messages will be %cMTP-forwarded to:", ctl->listener);
1424 for (idp = ctl->smtphunt; idp; idp = idp->next)
1426 printf(" %s", idp->id);
1427 if (!idp->val.status.mark)
1428 printf(" (default)");
1431 if (ctl->smtpaddress)
1432 printf(" Host part of MAIL FROM line will be %s\n",
1435 if (ctl->server.protocol != P_ETRN)
1437 if (ctl->antispam != (struct idlist *)NULL)
1441 printf(" Recognized listener spam block responses are:");
1442 for (idp = ctl->antispam; idp; idp = idp->next)
1443 printf(" %d", idp->val.status.num);
1446 else if (outlevel >= O_VERBOSE)
1447 printf(" Spam-blocking disabled\n");
1449 if (ctl->preconnect)
1450 printf(" Server connection will be brought up with \"%s\".\n",
1451 visbuf(ctl->preconnect));
1452 else if (outlevel >= O_VERBOSE)
1453 printf(" No pre-connection command.\n");
1454 if (ctl->postconnect)
1455 printf(" Server connection will be taken down with \"%s\".\n",
1456 visbuf(ctl->postconnect));
1457 else if (outlevel >= O_VERBOSE)
1458 printf(" No post-connection command.\n");
1459 if (ctl->server.protocol != P_ETRN) {
1460 if (!ctl->localnames)
1461 printf(" No localnames declared for this host.\n");
1467 for (idp = ctl->localnames; idp; idp = idp->next)
1470 if (count > 1 || ctl->wildcard)
1471 printf(" Multi-drop mode: ");
1473 printf(" Single-drop mode: ");
1475 printf("%d local name(s) recognized.\n", count);
1476 if (outlevel >= O_VERBOSE)
1478 for (idp = ctl->localnames; idp; idp = idp->next)
1480 printf("\t%s -> %s\n", idp->id, idp->val.id2);
1482 printf("\t%s\n", idp->id);
1484 fputs("\t*\n", stdout);
1487 if (count > 1 || ctl->wildcard)
1489 printf(" DNS lookup for multidrop addresses is %sabled.\n",
1490 ctl->server.dns ? "en" : "dis");
1491 if (ctl->server.dns)
1493 printf(" Server aliases will be compared with multidrop addresses by ");
1494 if (ctl->server.checkalias)
1495 printf("IP address.\n");
1499 if (ctl->server.envelope == STRING_DISABLED)
1500 printf(" Envelope-address routing is disabled\n");
1503 printf(" Envelope header is assumed to be: %s\n",
1504 ctl->server.envelope ? ctl->server.envelope:"Received");
1505 if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1506 printf(" Number of envelope header to be parsed: %d\n",
1507 ctl->server.envskip);
1508 if (ctl->server.qvirtual)
1509 printf(" Prefix %s will be removed from user id\n",
1510 ctl->server.qvirtual);
1511 else if (outlevel >= O_VERBOSE)
1512 printf(" No prefix stripping\n");
1515 if (ctl->server.akalist)
1519 printf(" Predeclared mailserver aliases:");
1520 for (idp = ctl->server.akalist; idp; idp = idp->next)
1521 printf(" %s", idp->id);
1524 if (ctl->server.localdomains)
1528 printf(" Local domains:");
1529 for (idp = ctl->server.localdomains; idp; idp = idp->next)
1530 printf(" %s", idp->id);
1537 if (ctl->server.interface)
1538 printf(" Connection must be through interface %s.\n", ctl->server.interface);
1539 else if (outlevel >= O_VERBOSE)
1540 printf(" No interface requirement specified.\n");
1541 if (ctl->server.monitor)
1542 printf(" Polling loop will monitor %s.\n", ctl->server.monitor);
1543 else if (outlevel >= O_VERBOSE)
1544 printf(" No monitor interface specified.\n");
1547 if (ctl->server.plugin)
1548 printf(" Server connections will be mode via plugin %s (--plugin %s).\n", ctl->server.plugin, ctl->server.plugin);
1549 else if (outlevel >= O_VERBOSE)
1550 printf(" No plugin command specified.\n");
1551 if (ctl->server.plugout)
1552 printf(" Listener connections will be mode via plugout %s (--plugout %s).\n", ctl->server.plugout, ctl->server.plugout);
1553 else if (outlevel >= O_VERBOSE)
1554 printf(" No plugout command specified.\n");
1556 if (ctl->server.protocol > P_POP2 && (ctl->server.protocol != P_ETRN))
1558 printf(" No UIDs saved from this host.\n");
1564 for (idp = ctl->oldsaved; idp; idp = idp->next)
1567 printf(" %d UIDs saved.\n", count);
1568 if (outlevel >= O_VERBOSE)
1569 for (idp = ctl->oldsaved; idp; idp = idp->next)
1570 printf("\t%s\n", idp->id);
1573 if (ctl->properties)
1574 printf(" Pass-through properties \"%s\".\n",
1575 visbuf(ctl->properties));
1579 /* fetchmail.c ends here */