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 char *fetchmailhost; /* either `localhost' or the host 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(); /* 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(sig) 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)
370 if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
372 if (ctl->server.preauthenticate == A_KERBEROS_V4 ||
373 ctl->server.preauthenticate == A_KERBEROS_V5 ||
375 ctl->server.protocol == P_IMAP_GSS ||
377 ctl->server.protocol == P_IMAP_K4)
378 /* Server won't care what the password is, but there
379 must be some non-null string here. */
380 ctl->password = ctl->remotename;
383 /* look up the host and account in the .netrc file. */
384 netrc_entry *p = search_netrc(netrc_list,ctl->server.pollname);
385 while (p && strcmp(p->account, ctl->remotename))
386 p = search_netrc(p->next, ctl->remotename);
388 /* if we find a matching entry with a password, use it */
389 if (p && p->password)
390 ctl->password = xstrdup(p->password);
393 if (ctl->server.protocol != P_ETRN && ctl->server.protocol != P_IMAP_K4
395 && ctl->server.protocol != P_IMAP_GSS
399 #define PASSWORD_PROMPT "Enter password for %s@%s: "
400 xalloca(tmpbuf, char *, strlen(PASSWORD_PROMPT) +
401 strlen(ctl->remotename) +
402 strlen(ctl->server.pollname) + 1);
403 (void) sprintf(tmpbuf, PASSWORD_PROMPT,
404 ctl->remotename, ctl->server.pollname);
405 ctl->password = xstrdup((char *)getpassword(tmpbuf));
406 #undef PASSWORD_PROMPT
411 * Maybe time to go to demon mode...
413 #if defined(HAVE_SYSLOG)
416 openlog(program_name, LOG_PID, LOG_MAIL);
421 error_init((run.poll_interval == 0 || nodetach) && !run.logfile);
423 if (run.poll_interval)
426 daemonize(run.logfile, termhook);
427 error( 0, 0, "starting fetchmail %s daemon ", RELEASE_ID);
430 * We'll set up a handler for these when we're sleeping,
431 * but ignore them otherwise so as not to interrupt a poll.
433 signal(SIGUSR1, SIG_IGN);
434 if (run.poll_interval && !getuid())
435 signal(SIGHUP, SIG_IGN);
438 /* beyond here we don't want more than one fetchmail running per user */
440 signal(SIGABRT, termhook);
441 signal(SIGINT, termhook);
442 signal(SIGTERM, termhook);
443 signal(SIGALRM, termhook);
444 signal(SIGPIPE, termhook);
445 signal(SIGQUIT, termhook);
447 /* here's the exclusion lock */
448 if ((lockfp = fopen(lockfile,"w")) != NULL) {
449 fprintf(lockfp,"%d",getpid());
450 if (run.poll_interval)
451 fprintf(lockfp," %d", run.poll_interval);
458 on_exit(unlockit, (char *)NULL);
463 * Query all hosts. If there's only one, the error return will
464 * reflect the status of that transaction.
467 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
469 * This was an efficiency hack that backfired. The theory
470 * was that using TCP/IP for DNS queries would get us better
471 * reliability and shave off some per-UDP-packet costs.
472 * Unfortunately it interacted badly with diald, which effectively
473 * filters out DNS queries over TCP/IP for reasons having to do
474 * with some obscure kernel problem involving bootstrapping of
475 * dynamically-addressed links. I don't understand this mess
476 * and don't want to, so it's "See ya!" to this hack.
478 sethostent(TRUE); /* use TCP/IP for mailserver queries */
479 #endif /* HAVE_RES_SEARCH */
482 for (ctl = querylist; ctl; ctl = ctl->next)
484 if (ctl->active && !(implicitmode && ctl->server.skip))
486 /* check skip interval first so that it counts all polls */
487 if (run.poll_interval && ctl->server.interval)
489 if (ctl->server.poll_count++ % ctl->server.interval)
491 if (outlevel >= O_VERBOSE)
493 "fetchmail: interval not reached, not querying %s\n",
494 ctl->server.pollname);
499 #if defined(linux) && !INET6
500 /* interface_approve() does its own error logging */
501 if (!interface_approve(&ctl->server))
503 #endif /* defined(linux) && !INET6 */
505 querystatus = query_host(ctl);
507 if (querystatus == PS_SUCCESS)
512 update_str_lists(ctl);
514 /* Save UID list to prevent re-fetch in case fetchmail
515 recover from crash */
518 write_saved_lists(querylist, run.idfile);
519 if (outlevel >= O_DEBUG)
520 error(0, 0, "saved UID List");
522 #endif /* POP3_ENABLE */
524 else if (querystatus == PS_AUTHFAIL) {
525 /* have it logged with priority LOG_ALERT */
526 error(querystatus, -1, "Authentication failed for %s@%s",
527 ctl->remotename, visbuf(ctl->server.pollname));
529 else if (!check_only &&
530 ((querystatus!=PS_NOMAIL) || (outlevel==O_DEBUG)))
531 error(0, 0, "Query status=%d", querystatus);
533 #if defined(linux) && !INET6
534 if (ctl->server.monitor)
537 * Allow some time for the link to quiesce. One
538 * second is usually sufficient, three is safe.
539 * Note: this delay is important - don't remove!
542 interface_note_activity(&ctl->server);
544 #endif /* defined(linux) && !INET6 */
548 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
549 endhostent(); /* release TCP/IP connection to nameserver */
550 #endif /* HAVE_RES_SEARCH */
553 * Close all SMTP delivery sockets. For optimum performance
554 * we'd like to hold them open til end of run, but (1) this
555 * loses if our poll interval is longer than the MTA's inactivity
556 * timeout, and (2) some MTAs (like smail) don't deliver after
557 * each message, but rather queue up mail and wait to actually
558 * deliver it until the input socket is closed.
560 for (ctl = querylist; ctl; ctl = ctl->next)
561 if (ctl->smtp_socket != -1)
563 SMTP_quit(ctl->smtp_socket);
564 close(ctl->smtp_socket);
565 ctl->smtp_socket = -1;
569 * OK, we've polled. Now sleep.
571 if (run.poll_interval)
573 if (outlevel >= O_VERBOSE)
578 fprintf(stderr, "fetchmail: sleeping at %s", ctime(&now));
582 * With this simple hack, we make it possible for a foreground
583 * fetchmail to wake up one in daemon mode. What we want is the
584 * side effect of interrupting any sleep that may be going on,
585 * forcing fetchmail to re-poll its hosts. The second line is
586 * for people who think all system daemons wake up on SIGHUP.
588 signal(SIGUSR1, donothing);
590 signal(SIGHUP, donothing);
593 * We can't use sleep(3) here because we need an alarm(3)
594 * equivalent in order to implement server nonresponse timeout.
595 * We'll just assume setitimer(2) is available since fetchmail
596 * has to have a BSDoid socket layer to work at all.
600 #ifdef SLEEP_WITH_ALARM /* not normally on */
602 * This code stopped working under glibc-2, apparently due
603 * to the change in signal(2) semantics. (The siginterrupt
604 * line, added later, should fix this problem.) John Stracke
605 * <francis@netscape.com> wrote:
607 * The problem seems to be that, after hitting the interval
608 * timer while talking to the server, the process no longer
609 * responds to SIGALRM. I put in printf()s to see when it
610 * reached the pause() for the poll interval, and I checked
611 * the return from setitimer(), and everything seemed to be
612 * working fine, except that the pause() just ignored SIGALRM.
613 * I thought maybe the itimer wasn't being fired, so I hit
614 * it with a SIGALRM from the command line, and it ignored
615 * that, too. SIGUSR1 woke it up just fine, and it proceeded
616 * to repoll--but, when the dummy server didn't respond, it
617 * never timed out, and SIGALRM wouldn't make it.
619 * (continued below...)
621 struct itimerval ntimeout;
623 ntimeout.it_interval.tv_sec = 5; /* repeat alarm every 5 secs */
624 ntimeout.it_interval.tv_usec = 0;
625 ntimeout.it_value.tv_sec = run.poll_interval;
626 ntimeout.it_value.tv_usec = 0;
628 siginterrupt(SIGALRM, 1);
630 signal(SIGALRM, gotsigalrm); /* first trap signals */
631 setitimer(ITIMER_REAL,&ntimeout,NULL); /* then start timer */
632 /* there is a very small window between the next two lines */
633 /* which could result in a deadlock. But this will now be */
634 /* caught by periodical alarms (see it_interval) */
638 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
639 ntimeout.it_value.tv_sec = ntimeout.it_value.tv_usec = 0;
640 setitimer(ITIMER_REAL,&ntimeout,NULL); /* now stop timer */
641 signal(SIGALRM, SIG_IGN);
644 * So the workaround I used is to make it sleep by using
645 * select() instead of setitimer()/pause(). select() is
646 * perfectly happy being called with a timeout and
647 * no file descriptors; it just sleeps until it hits the
648 * timeout. The only concern I had was that it might
649 * implement its timeout with SIGALRM--there are some
650 * Unices where this is done, because select() is a library
651 * function--but apparently not.
653 struct timeval timeout;
655 timeout.tv_sec = run.poll_interval;
658 select(0,0,0,0, &timeout);
662 signal(SIGALRM, gotsigalrm);
663 _beginthread(itimerthread, NULL, 32768, NULL);
664 /* see similar code above */
667 signal(SIGALRM, SIG_IGN);
669 if (lastsig == SIGUSR1
670 || ((run.poll_interval && !getuid()) && lastsig == SIGHUP))
672 #ifdef SYS_SIGLIST_DECLARED
673 error(0, 0, "awakened by %s", sys_siglist[lastsig]);
675 error(0, 0, "awakened by signal %d", lastsig);
680 /* now lock out interrupts again */
681 signal(SIGUSR1, SIG_IGN);
683 signal(SIGHUP, SIG_IGN);
685 if (outlevel >= O_VERBOSE)
690 fprintf(stderr, "fetchmail: awakened at %s", ctime(&now));
696 if (outlevel >= O_VERBOSE)
697 fprintf(stderr,"fetchmail: normal termination, status %d\n",
698 successes ? PS_SUCCESS : querystatus);
701 exit(successes ? PS_SUCCESS : querystatus);
704 static void optmerge(struct query *h2, struct query *h1, int force)
705 /* merge two options records */
708 * If force is off, modify h2 fields only when they're empty (treat h1
709 * as defaults). If force is on, modify each h2 field whenever h1
710 * is nonempty (treat h1 as an override).
712 #define LIST_MERGE(dstl, srcl) if (force ? !!srcl : !dstl) \
713 free_str_list(&dstl), \
714 append_str_list(&dstl, &srcl)
715 LIST_MERGE(h2->server.localdomains, h1->server.localdomains);
716 LIST_MERGE(h2->localnames, h1->localnames);
717 LIST_MERGE(h2->mailboxes, h1->mailboxes);
718 LIST_MERGE(h2->smtphunt, h1->smtphunt);
719 LIST_MERGE(h2->antispam, h1->antispam);
722 #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld
723 FLAG_MERGE(server.via);
724 FLAG_MERGE(server.protocol);
726 FLAG_MERGE(server.service);
727 FLAG_MERGE(server.netsec);
729 FLAG_MERGE(server.port);
731 FLAG_MERGE(server.interval);
732 FLAG_MERGE(server.preauthenticate);
733 FLAG_MERGE(server.timeout);
734 FLAG_MERGE(server.envelope);
735 FLAG_MERGE(server.envskip);
736 FLAG_MERGE(server.qvirtual);
737 FLAG_MERGE(server.skip);
738 FLAG_MERGE(server.dns);
739 FLAG_MERGE(server.checkalias);
740 FLAG_MERGE(server.uidl);
743 FLAG_MERGE(server.interface);
744 FLAG_MERGE(server.monitor);
745 FLAG_MERGE(server.interface_pair);
748 FLAG_MERGE(wildcard);
749 FLAG_MERGE(remotename);
750 FLAG_MERGE(password);
752 FLAG_MERGE(smtpaddress);
753 FLAG_MERGE(preconnect);
754 FLAG_MERGE(postconnect);
758 FLAG_MERGE(fetchall);
762 FLAG_MERGE(pass8bits);
763 FLAG_MERGE(dropstatus);
764 FLAG_MERGE(mimedecode);
766 FLAG_MERGE(warnings);
767 FLAG_MERGE(fetchlimit);
768 FLAG_MERGE(batchlimit);
771 FLAG_MERGE(properties);
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 with Kerberos %s authentication",
1248 ctl->server.preauthenticate == A_KERBEROS_V5 ? "V" : "IV");
1250 printf(" Protocol is %s", showproto(ctl->server.protocol));
1252 if (ctl->server.service)
1253 printf(" (using service %s)", ctl->server.service);
1254 if (ctl->server.netsec)
1255 printf(" (using network security options %s)", ctl->server.netsec);
1257 if (ctl->server.port)
1258 printf(" (using port %d)", ctl->server.port);
1260 else if (outlevel >= O_VERBOSE)
1261 printf(" (using default port)");
1262 if (ctl->server.uidl && (ctl->server.protocol != P_ETRN))
1263 printf(" (forcing UIDL use)");
1266 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1267 printf(" Kerberos V4 preauthentication enabled.\n");
1268 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1269 printf(" Kerberos V5 preauthentication enabled.\n");
1270 if (ctl->server.timeout > 0)
1271 printf(" Server nonresponse timeout is %d seconds", ctl->server.timeout);
1272 if (ctl->server.timeout == CLIENT_TIMEOUT)
1273 printf(" (default).\n");
1277 if (ctl->server.protocol != P_ETRN) {
1278 if (!ctl->mailboxes->id)
1279 printf(" Default mailbox selected.\n");
1284 printf(" Selected mailboxes are:");
1285 for (idp = ctl->mailboxes; idp; idp = idp->next)
1286 printf(" %s", idp->id);
1289 printf(" %s messages will be retrieved (--all %s).\n",
1290 ctl->fetchall ? "All" : "Only new",
1291 ctl->fetchall ? "on" : "off");
1292 printf(" Fetched messages will%s be kept on the server (--keep %s).\n",
1293 ctl->keep ? "" : " not",
1294 ctl->keep ? "on" : "off");
1295 printf(" Old messages will%s be flushed before message retrieval (--flush %s).\n",
1296 ctl->flush ? "" : " not",
1297 ctl->flush ? "on" : "off");
1298 printf(" Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
1299 ctl->rewrite ? "en" : "dis",
1300 ctl->rewrite ? "off" : "on");
1301 printf(" Carriage-return stripping is %sabled (stripcr %s).\n",
1302 ctl->stripcr ? "en" : "dis",
1303 ctl->stripcr ? "on" : "off");
1304 printf(" Carriage-return forcing is %sabled (forcecr %s).\n",
1305 ctl->forcecr ? "en" : "dis",
1306 ctl->forcecr ? "on" : "off");
1307 printf(" Interpretation of Content-Transfer-Encoding is %sabled (pass8bits %s).\n",
1308 ctl->pass8bits ? "dis" : "en",
1309 ctl->pass8bits ? "on" : "off");
1310 printf(" MIME decoding is %sabled (mimedecode %s).\n",
1311 ctl->mimedecode ? "en" : "dis",
1312 ctl->mimedecode ? "on" : "off");
1313 printf(" Nonempty Status lines will be %s (dropstatus %s)\n",
1314 ctl->dropstatus ? "discarded" : "kept",
1315 ctl->dropstatus ? "on" : "off");
1316 if (NUM_NONZERO(ctl->limit))
1318 if (NUM_NONZERO(ctl->limit))
1319 printf(" Message size limit is %d bytes (--limit %d).\n",
1320 ctl->limit, ctl->limit);
1321 else if (outlevel >= O_VERBOSE)
1322 printf(" No message size limit (--limit 0).\n");
1323 if (run.poll_interval > 0)
1324 printf(" Message size warning interval is %d seconds (--warnings %d).\n",
1325 ctl->warnings, ctl->warnings);
1326 else if (outlevel >= O_VERBOSE)
1327 printf(" Size warnings on every poll (--warnings 0).\n");
1329 if (NUM_NONZERO(ctl->fetchlimit))
1330 printf(" Received-message limit is %d (--fetchlimit %d).\n",
1331 ctl->fetchlimit, ctl->fetchlimit);
1332 else if (outlevel >= O_VERBOSE)
1333 printf(" No received-message limit (--fetchlimit 0).\n");
1334 if (NUM_NONZERO(ctl->batchlimit))
1335 printf(" SMTP message batch limit is %d.\n", ctl->batchlimit);
1336 else if (outlevel >= O_VERBOSE)
1337 printf(" No SMTP message batch limit (--batchlimit 0).\n");
1338 if (ctl->server.protocol == P_IMAP)
1339 if (NUM_NONZERO(ctl->expunge))
1340 printf(" Deletion interval between expunges is %d (--expunge %d).\n", ctl->expunge, ctl->expunge);
1341 else if (outlevel >= O_VERBOSE)
1342 printf(" No expunges (--expunge 0).\n");
1344 if (ctl->mda && (ctl->server.protocol != P_ETRN))
1345 printf(" Messages will be delivered with \"%s\".\n", visbuf(ctl->mda));
1350 printf(" Messages will be SMTP-forwarded to:");
1351 for (idp = ctl->smtphunt; idp; idp = idp->next)
1353 printf(" %s", idp->id);
1354 if (!idp->val.status.mark)
1355 printf(" (default)");
1358 if (ctl->smtpaddress)
1359 printf(" Host part of MAIL FROM line will be %s\n",
1362 if (ctl->server.protocol != P_ETRN)
1364 if (ctl->antispam != (struct idlist *)NULL)
1368 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);
1491 if (ctl->properties)
1492 printf(" Pass-through properties \"%s\".\n",
1493 visbuf(ctl->properties));
1497 /* fetchmail.c ends here */