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>
33 #ifdef HAVE_SYS_WAIT_H
37 #ifdef HAVE_GETHOSTBYNAME
39 #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 *fetchmailhost; /* the name of the host running fetchmail */
68 char *program_name; /* the name to prefix error messages with */
69 flag configdump; /* dump control blocks for configurator */
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(); /* forward declaration of exit hook */
85 * The function of this variable is to reduce the size of the window during
86 * which two SIGALRMS in rapid succession can hose the code. This is a
87 * bit of a kluge; the real right thing would use sigprocmask(), sigsuspend()
88 * and close the window entirely. But since the interval isn't normally
89 * going to be less than one second this is not a big issue.
91 #if defined(STDC_HEADERS)
92 static sig_atomic_t alarm_latch = FALSE;
94 /* assume int can be written in one atomic operation on non ANSI-C systems */
95 static int alarm_latch = FALSE;
98 RETSIGTYPE donothing(sig) int sig; {signal(sig, donothing); lastsig = sig;}
99 RETSIGTYPE gotsigalrm(sig) int sig; {signal(sig, donothing); lastsig = sig; alarm_latch = TRUE;}
102 static void unlockit(int n, void *p)
104 static void unlockit(void)
106 /* must-do actions for exit (but we can't count on being able to do malloc) */
112 /* Various EMX-specific definitions */
114 void itimerthread(void* dummy) {
115 if (outlevel == O_VERBOSE)
116 fprintf(stderr, "fetchmail: thread sleeping for %d sec.\n", poll_interval);
118 _sleep2(poll_interval*1000);
119 kill((getpid()), SIGALRM);
124 int main (int argc, char **argv)
126 int st, bkgd = FALSE;
127 int parsestatus, implicitmode = FALSE;
130 netrc_entry *netrc_list;
131 char *netrc_file, *tmpbuf;
134 envquery(argc, argv);
136 #define IDFILE_NAME ".fetchids"
137 run.idfile = (char *) xmalloc(strlen(home)+strlen(IDFILE_NAME)+2);
138 strcpy(run.idfile, home);
139 strcat(run.idfile, "/");
140 strcat(run.idfile, IDFILE_NAME);
144 if ((parsestatus = parsecmdline(argc,argv, &cmd_run, &cmd_opts)) < 0)
147 /* this hint to stdio should help messages come out in the right order */
148 setvbuf(stdout, NULL, _IOLBF, MSGBUFSIZE);
152 printf("This is fetchmail release %s", RELEASE_ID);
155 #endif /* POP2_ENABLE */
158 #endif /* POP3_ENABLE */
161 #endif /* IMAP_ENABLE */
167 #endif /* RPA_ENABLE */
170 #endif /* ETRN_ENABLE */
179 #endif /* NET_SECURITY */
182 /* this is an attempt to help remote debugging */
186 /* avoid parsing the config file if all we're doing is killing a daemon */
187 if (!(quitmode && argc == 2))
188 implicitmode = load_params(argc, argv, optind);
190 /* set up to do lock protocol */
191 #define FETCHMAIL_PIDFILE "fetchmail.pid"
192 tmpbuf = xmalloc(strlen(home) + strlen(FETCHMAIL_PIDFILE) + 3);
194 sprintf(tmpbuf, "%s/%s", PID_DIR, FETCHMAIL_PIDFILE);
196 strcpy(tmpbuf, home);
197 strcat(tmpbuf, "/.");
198 strcat(tmpbuf, FETCHMAIL_PIDFILE);
200 #undef FETCHMAIL_PIDFILE
202 /* perhaps we just want to check options? */
205 printf("Taking options from command line");
206 if (access(rcfile, 0))
209 printf(" and %s\n", rcfile);
210 if (outlevel == O_VERBOSE)
211 printf("Lockfile at %s\n", tmpbuf);
213 if (querylist == NULL)
214 (void) fprintf(stderr,
215 "No mailservers set up -- perhaps %s is missing?\n", rcfile);
217 dump_params(&run, querylist, implicitmode);
221 /* dump options as a Python dictionary, for configurator use */
224 dump_config(&run, querylist);
228 /* check for another fetchmail running concurrently */
230 if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
232 fprintf(stderr,"fetchmail: cannot allocate memory for lock name.\n");
236 (void) strcpy(lockfile, tmpbuf);
237 if ((lockfp = fopen(lockfile, "r")) != NULL )
239 bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
241 if (kill(pid, 0) == -1) {
242 fprintf(stderr,"fetchmail: removing stale lockfile\n");
250 /* if no mail servers listed and nothing in background, we're done */
251 if (!(quitmode && argc == 2) && pid == -1 && querylist == NULL) {
252 (void)fputs("fetchmail: no mailservers have been specified.\n",stderr);
256 /* perhaps user asked us to kill the other fetchmail */
261 fprintf(stderr,"fetchmail: no other fetchmail is running\n");
265 else if (kill(pid, SIGTERM) < 0)
267 fprintf(stderr,"fetchmail: error killing %s fetchmail at %d; bailing out.\n",
268 bkgd ? "background" : "foreground", pid);
273 fprintf(stderr,"fetchmail: %s fetchmail at %d killed.\n",
274 bkgd ? "background" : "foreground", pid);
283 /* another fetchmail is running -- wake it up or die */
289 "fetchmail: can't check mail while another fetchmail to same host is running.\n");
292 else if (!implicitmode)
295 "fetchmail: can't poll specified hosts with another fetchmail running at %d.\n",
302 "fetchmail: another foreground fetchmail is running at %d.\n",
309 "fetchmail: can't accept options while a background fetchmail is running.\n");
312 else if (kill(pid, SIGUSR1) == 0)
315 "fetchmail: background fetchmail at %d awakened.\n",
322 * Should never happen -- possible only if a background fetchmail
323 * croaks after the first kill probe above but before the
324 * SIGUSR1/SIGHUP transmission.
327 "fetchmail: elder sibling at %d died mysteriously.\n",
329 return(PS_UNDEFINED);
333 /* parse the ~/.netrc file (if present) for future password lookups. */
334 netrc_file = (char *) xmalloc (strlen (home) + 8);
335 strcpy (netrc_file, home);
336 strcat (netrc_file, "/.netrc");
337 netrc_list = parse_netrc(netrc_file);
339 /* pick up interactively any passwords we need but don't have */
340 for (ctl = querylist; ctl; ctl = ctl->next)
341 if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
343 if (ctl->server.preauthenticate == A_KERBEROS_V4 ||
344 ctl->server.preauthenticate == A_KERBEROS_V5 ||
346 ctl->server.protocol == P_IMAP_GSS ||
348 ctl->server.protocol == P_IMAP_K4)
349 /* Server won't care what the password is, but there
350 must be some non-null string here. */
351 ctl->password = ctl->remotename;
354 /* look up the host and account in the .netrc file. */
355 netrc_entry *p = search_netrc(netrc_list,ctl->server.pollname);
356 while (p && strcmp(p->account, ctl->remotename))
357 p = search_netrc(p->next, ctl->remotename);
359 /* if we find a matching entry with a password, use it */
360 if (p && p->password)
361 ctl->password = xstrdup(p->password);
364 if (ctl->server.protocol != P_ETRN && ctl->server.protocol != P_IMAP_K4
366 && ctl->server.protocol != P_IMAP_GSS
371 #define PASSWORD_PROMPT "Enter password for %s@%s: "
372 tmpbuf = xmalloc(strlen(PASSWORD_PROMPT) +
373 strlen(ctl->remotename) +
374 strlen(ctl->server.pollname) + 1);
375 (void) sprintf(tmpbuf, PASSWORD_PROMPT,
376 ctl->remotename, ctl->server.pollname);
377 ctl->password = xstrdup((char *)getpassword(tmpbuf));
378 #undef PASSWORD_PROMPT
382 /* we don't need tmpbuf anymore */
384 tmpbuf = NULL; /* firewall code */
387 * Maybe time to go to demon mode...
389 #if defined(HAVE_SYSLOG)
392 openlog(program_name, LOG_PID, LOG_MAIL);
397 error_init(run.poll_interval == 0 && !run.logfile);
399 if (run.poll_interval)
402 daemonize(run.logfile, termhook);
403 error( 0, 0, "starting fetchmail %s daemon ", RELEASE_ID);
406 * We'll set up a handler for these when we're sleeping,
407 * but ignore them otherwise so as not to interrupt a poll.
409 signal(SIGUSR1, SIG_IGN);
410 if (run.poll_interval && !getuid())
411 signal(SIGHUP, SIG_IGN);
414 /* beyond here we don't want more than one fetchmail running per user */
416 signal(SIGABRT, termhook);
417 signal(SIGINT, termhook);
418 signal(SIGTERM, termhook);
419 signal(SIGALRM, termhook);
420 signal(SIGPIPE, termhook);
421 signal(SIGQUIT, termhook);
423 /* here's the exclusion lock */
424 if ((lockfp = fopen(lockfile,"w")) != NULL) {
425 fprintf(lockfp,"%d",getpid());
426 if (run.poll_interval)
427 fprintf(lockfp," %d", run.poll_interval);
434 on_exit(unlockit, (char *)NULL);
439 * Query all hosts. If there's only one, the error return will
440 * reflect the status of that transaction.
443 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
445 * This was an efficiency hack that backfired. The theory
446 * was that using TCP/IP for DNS queries would get us better
447 * reliability and shave off some per-UDP-packet costs.
448 * Unfortunately it interacted badly with diald, which effectively
449 * filters out DNS queries over TCP/IP for reasons having to do
450 * with some obscure kernel problem involving bootstrapping of
451 * dynamically-addressed links. I don't understand this mess
452 * and don't want to, so it's "See ya!" to this hack.
454 sethostent(TRUE); /* use TCP/IP for mailserver queries */
455 #endif /* HAVE_RES_SEARCH */
458 for (ctl = querylist; ctl; ctl = ctl->next)
460 if (ctl->active && !(implicitmode && ctl->server.skip))
462 /* check skip interval first so that it counts all polls */
463 if (run.poll_interval && ctl->server.interval)
465 if (ctl->server.poll_count++ % ctl->server.interval)
467 if (outlevel == O_VERBOSE)
469 "fetchmail: interval not reached, not querying %s\n",
470 ctl->server.pollname);
475 #if defined(linux) && !INET6
476 /* interface_approve() does its own error logging */
477 if (!interface_approve(&ctl->server))
479 #endif /* defined(linux) && !INET6 */
481 querystatus = query_host(ctl);
483 if (querystatus == PS_SUCCESS)
488 update_str_lists(ctl);
490 /* Save UID list to prevent re-fetch in case fetchmail
491 recover from crash */
492 if (!check_only && outlevel == O_VERBOSE)
494 write_saved_lists(querylist, run.idfile);
495 if (outlevel == O_VERBOSE)
496 error(0, 0, "saved UID List");
498 #endif /* POP3_ENABLE */
500 else if (!check_only &&
501 ((querystatus!=PS_NOMAIL) || (outlevel==O_VERBOSE)))
502 error(0, 0, "Query status=%d", querystatus);
504 #if defined(linux) && !INET6
505 if (ctl->server.monitor)
508 * Allow some time for the link to quiesce. One
509 * second is usually sufficient, three is safe.
510 * Note: this delay is important - don't remove!
513 interface_note_activity(&ctl->server);
515 #endif /* defined(linux) && !INET6 */
519 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
520 endhostent(); /* release TCP/IP connection to nameserver */
521 #endif /* HAVE_RES_SEARCH */
524 * Close all SMTP delivery sockets. For optimum performance
525 * we'd like to hold them open til end of run, but (1) this
526 * loses if our poll interval is longer than the MTA's inactivity
527 * timeout, and (2) some MTAs (like smail) don't deliver after
528 * each message, but rather queue up mail and wait to actually
529 * deliver it until the input socket is closed.
531 for (ctl = querylist; ctl; ctl = ctl->next)
532 if (ctl->smtp_socket != -1)
534 SMTP_quit(ctl->smtp_socket);
535 close(ctl->smtp_socket);
536 ctl->smtp_socket = -1;
540 * OK, we've polled. Now sleep.
542 if (run.poll_interval)
544 if (outlevel == O_VERBOSE)
549 fprintf(stderr, "fetchmail: sleeping at %s", ctime(&now));
553 * With this simple hack, we make it possible for a foreground
554 * fetchmail to wake up one in daemon mode. What we want is the
555 * side effect of interrupting any sleep that may be going on,
556 * forcing fetchmail to re-poll its hosts. The second line is
557 * for people who think all system daemons wake up on SIGHUP.
559 signal(SIGUSR1, donothing);
561 signal(SIGHUP, donothing);
564 * We can't use sleep(3) here because we need an alarm(3)
565 * equivalent in order to implement server nonresponse timeout.
566 * We'll just assume setitimer(2) is available since fetchmail
567 * has to have a BSDoid socket layer to work at all.
571 #ifdef SLEEP_WITH_ALARM /* not normally on */
573 * This code stopped working under glibc-2, apparently due
574 * to the change in signal(2) semantics. (The siginterrupt
575 * line, added later, should fix this problem.) John Stracke
576 * <francis@netscape.com> wrote:
578 * The problem seems to be that, after hitting the interval
579 * timer while talking to the server, the process no longer
580 * responds to SIGALRM. I put in printf()s to see when it
581 * reached the pause() for the poll interval, and I checked
582 * the return from setitimer(), and everything seemed to be
583 * working fine, except that the pause() just ignored SIGALRM.
584 * I thought maybe the itimer wasn't being fired, so I hit
585 * it with a SIGALRM from the command line, and it ignored
586 * that, too. SIGUSR1 woke it up just fine, and it proceeded
587 * to repoll--but, when the dummy server didn't respond, it
588 * never timed out, and SIGALRM wouldn't make it.
590 * (continued below...)
592 struct itimerval ntimeout;
594 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
595 ntimeout.it_value.tv_sec = poll_interval;
596 ntimeout.it_value.tv_usec = 0;
598 siginterrupt(SIGALRM, 1);
600 signal(SIGALRM, gotsigalrm); /* first trap signals */
601 setitimer(ITIMER_REAL,&ntimeout,NULL); /* then start timer */
602 /* there is a very small window between the next two lines */
605 signal(SIGALRM, SIG_IGN);
608 * So the workaround I used is to make it sleep by using
609 * select() instead of setitimer()/pause(). select() is
610 * perfectly happy being called with a timeout and
611 * no file descriptors; it just sleeps until it hits the
612 * timeout. The only concern I had was that it might
613 * implement its timeout with SIGALRM--there are some
614 * Unices where this is done, because select() is a library
615 * function--but apparently not.
617 struct timeval timeout;
619 timeout.tv_sec = run.poll_interval;
622 select(0,0,0,0, &timeout);
626 signal(SIGALRM, gotsigalrm);
627 _beginthread(itimerthread, NULL, 32768, NULL);
628 /* see similar code above */
631 signal(SIGALRM, SIG_IGN);
633 if (lastsig == SIGUSR1
634 || ((run.poll_interval && !getuid()) && lastsig == SIGHUP))
636 #ifdef SYS_SIGLIST_DECLARED
637 error(0, 0, "awakened by %s", sys_siglist[lastsig]);
639 error(0, 0, "awakened by signal %d", lastsig);
644 /* now lock out interrupts again */
645 signal(SIGUSR1, SIG_IGN);
647 signal(SIGHUP, SIG_IGN);
649 if (outlevel == O_VERBOSE)
654 fprintf(stderr, "fetchmail: awakened at %s", ctime(&now));
660 if (outlevel == O_VERBOSE)
661 fprintf(stderr,"fetchmail: normal termination, status %d\n",
662 successes ? PS_SUCCESS : querystatus);
665 exit(successes ? PS_SUCCESS : querystatus);
668 static void optmerge(struct query *h2, struct query *h1, int force)
669 /* merge two options records */
672 * If force is off, modify h2 fields only when they're empty (treat h1
673 * as defaults). If force is on, modify each h2 field whenever h1
674 * is nonempty (treat h1 as an override).
676 #define LIST_MERGE(dstl, srcl) if (force ? !!srcl : !dstl) \
677 free_str_list(&dstl), \
678 append_str_list(&dstl, &srcl)
679 LIST_MERGE(h2->server.localdomains, h1->server.localdomains);
680 LIST_MERGE(h2->localnames, h1->localnames);
681 LIST_MERGE(h2->mailboxes, h1->mailboxes);
682 LIST_MERGE(h2->smtphunt, h1->smtphunt);
683 LIST_MERGE(h2->antispam, h1->antispam);
686 #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld
687 FLAG_MERGE(server.via);
688 FLAG_MERGE(server.protocol);
690 FLAG_MERGE(server.service);
691 FLAG_MERGE(server.netsec);
693 FLAG_MERGE(server.port);
695 FLAG_MERGE(server.interval);
696 FLAG_MERGE(server.preauthenticate);
697 FLAG_MERGE(server.timeout);
698 FLAG_MERGE(server.envelope);
699 FLAG_MERGE(server.envskip);
700 FLAG_MERGE(server.qvirtual);
701 FLAG_MERGE(server.skip);
702 FLAG_MERGE(server.dns);
703 FLAG_MERGE(server.checkalias);
704 FLAG_MERGE(server.uidl);
707 FLAG_MERGE(server.interface);
708 FLAG_MERGE(server.monitor);
709 FLAG_MERGE(server.interface_pair);
712 FLAG_MERGE(wildcard);
713 FLAG_MERGE(remotename);
714 FLAG_MERGE(password);
716 FLAG_MERGE(smtpaddress);
717 FLAG_MERGE(preconnect);
721 FLAG_MERGE(fetchall);
725 FLAG_MERGE(pass8bits);
726 FLAG_MERGE(dropstatus);
727 FLAG_MERGE(mimedecode);
729 FLAG_MERGE(fetchlimit);
730 FLAG_MERGE(batchlimit);
735 static int load_params(int argc, char **argv, int optind)
737 int implicitmode, st;
739 struct query def_opts, *ctl;
741 memset(&def_opts, '\0', sizeof(struct query));
742 def_opts.smtp_socket = -1;
743 def_opts.smtpaddress = (char *)0;
744 save_str(&def_opts.antispam, (char *)NULL, 0)->val.status.num = 571;
745 save_str(&def_opts.antispam, (char *)NULL, 0)->val.status.num = 550;
746 save_str(&def_opts.antispam, (char *)NULL, 0)->val.status.num = 501;
748 def_opts.server.protocol = P_AUTO;
749 def_opts.server.timeout = CLIENT_TIMEOUT;
750 def_opts.remotename = user;
751 def_opts.expunge = 1;
753 /* this builds the host list */
754 if (prc_parse_file(rcfile, !versioninfo) != 0)
757 if ((implicitmode = (optind >= argc)))
759 for (ctl = querylist; ctl; ctl = ctl->next)
763 for (; optind < argc; optind++)
765 flag predeclared = FALSE;
768 * If hostname corresponds to a host known from the rc file,
769 * simply declare it active. Otherwise synthesize a host
770 * record from command line and defaults
772 for (ctl = querylist; ctl; ctl = ctl->next)
773 if (!strcmp(ctl->server.pollname, argv[optind])
774 || str_in_list(&ctl->server.akalist, argv[optind], TRUE))
783 * Allocate and link record without copying in
784 * command-line args; we'll do that with the optmerge
787 ctl = hostalloc((struct query *)NULL);
789 ctl->server.pollname = xstrdup(argv[optind]);
791 ctl->server.lead_server = (struct hostdata *)NULL;
796 * If there's a defaults record, merge it and lose it.
798 if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
800 for (ctl = querylist->next; ctl; ctl = ctl->next)
801 optmerge(ctl, querylist, FALSE);
802 querylist = querylist->next;
805 /* don't allow a defaults record after the first */
806 for (ctl = querylist; ctl; ctl = ctl->next)
807 if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
810 /* merge in wired defaults, do sanity checks and prepare internal fields */
811 for (ctl = querylist; ctl; ctl = ctl->next)
813 if (configdump || (ctl->active && !(implicitmode && ctl->server.skip)))
815 /* merge in defaults */
816 optmerge(ctl, &def_opts, FALSE);
818 /* force command-line options */
819 optmerge(ctl, &cmd_opts, TRUE);
821 /* make sure we have a nonempty host list to forward to */
824 save_str(&ctl->smtphunt, fetchmailhost, FALSE);
825 /* for non ETRN try to deliver mails to localhost if
826 * fetchmailhost fails
828 if (ctl->server.protocol != P_ETRN) {
829 save_str(&ctl->smtphunt, "localhost", FALSE);
833 /* keep lusers from shooting themselves in the foot :-) */
834 if (run.poll_interval && ctl->limit)
836 fprintf(stderr,"fetchmail: you'd never see large messages!\n");
840 /* if `user' doesn't name a real local user, try to run as root */
841 if ((pw = getpwnam(user)) == (struct passwd *)NULL)
844 ctl->uid = pw->pw_uid; /* for local delivery via MDA */
845 if (!ctl->localnames) /* for local delivery via SMTP */
846 save_str_pair(&ctl->localnames, user, NULL);
848 /* this code enables flags to be turned off */
849 #define DEFAULT(flag, dflt) if (flag == FLAG_TRUE)\
851 else if (flag == FLAG_FALSE)\
855 DEFAULT(ctl->keep, FALSE);
856 DEFAULT(ctl->fetchall, FALSE);
857 DEFAULT(ctl->flush, FALSE);
858 DEFAULT(ctl->rewrite, TRUE);
859 DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL));
860 DEFAULT(ctl->forcecr, FALSE);
861 DEFAULT(ctl->pass8bits, FALSE);
862 DEFAULT(ctl->dropstatus, FALSE);
863 DEFAULT(ctl->mimedecode, FALSE);
864 DEFAULT(ctl->server.dns, TRUE);
865 DEFAULT(ctl->server.uidl, FALSE);
866 DEFAULT(ctl->server.checkalias, FALSE);
869 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
870 /* can't handle multidrop mailboxes unless we can do DNS lookups */
871 if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
873 ctl->server.dns = FALSE;
874 fprintf(stderr, "fetchmail: warning: no DNS available to check multidrop fetches from %s\n", ctl->server.pollname);
876 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
880 * Compute the true name of the mailserver host.
881 * There are two clashing cases here:
883 * (1) The poll name is a label, possibly on one of several
884 * poll configurations for the same host. In this case
885 * the `via' option will be present and give the true name.
887 * (2) The poll name is the true one, the via name is
888 * localhost. This is going to be typical for ssh-using
891 * We're going to assume the via name is true unless it's
894 if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
895 ctl->server.queryname = xstrdup(ctl->server.via);
897 ctl->server.queryname = xstrdup(ctl->server.pollname);
900 * We may have to canonicalize the server truename for later use.
901 * Do this just once for each lead server, if necessary, in order
902 * to minimize DNS round trips.
904 if (ctl->server.lead_server)
905 ctl->server.truename = xstrdup(ctl->server.lead_server->truename);
906 #ifdef HAVE_GETHOSTBYNAME
907 else if (ctl->server.preauthenticate==A_KERBEROS_V4 ||
908 ctl->server.preauthenticate==A_KERBEROS_V5 ||
909 (ctl->server.dns && MULTIDROP(ctl)))
911 struct hostent *namerec;
913 /* compute the canonical name of the host */
915 namerec = gethostbyname(ctl->server.queryname);
916 if (namerec == (struct hostent *)NULL)
919 "couldn't find canonical DNS name of %s",
920 ctl->server.pollname);
924 ctl->server.truename=xstrdup((char *)namerec->h_name);
926 #endif /* HAVE_GETHOSTBYNAME */
928 ctl->server.truename = xstrdup(ctl->server.queryname);
930 /* if no folders were specified, set up the null one as default */
932 save_str(&ctl->mailboxes, (char *)NULL, 0);
934 /* maybe user overrode timeout on command line? */
935 if (ctl->server.timeout == -1)
936 ctl->server.timeout = CLIENT_TIMEOUT;
940 if (ctl->server.port < 0)
942 (void) fprintf(stderr,
943 "%s configuration invalid, port number cannot be negative",
944 ctl->server.pollname);
947 if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
949 (void) fprintf(stderr,
950 "%s configuration invalid, RPOP requires a privileged port",
951 ctl->server.pollname);
958 /* here's where we override globals */
960 run.logfile = cmd_run.logfile;
962 run.idfile = cmd_run.idfile;
963 if (cmd_run.poll_interval >= 0)
964 run.poll_interval = cmd_run.poll_interval;
965 if (cmd_run.invisible)
966 run.invisible = cmd_run.invisible;
967 if (cmd_run.use_syslog)
968 run.use_syslog = (cmd_run.use_syslog == FLAG_TRUE);
970 /* check and daemon options are not compatible */
971 if (check_only && run.poll_interval)
972 run.poll_interval = 0;
975 /* initialize UID handling */
976 if (!versioninfo && (st = prc_filecheck(run.idfile, !versioninfo)) != 0)
979 initialize_saved_lists(querylist, run.idfile);
980 #endif /* POP3_ENABLE */
983 * If the user didn't set a last-resort user to get misaddressed
984 * multidrop mail, set an appropriate default here.
987 if (getuid()) /* ordinary user */
988 run.postmaster = user;
990 run.postmaster = "postmaster";
992 return(implicitmode);
995 void termhook(int sig)
996 /* to be executed on normal or signal-induced termination */
1001 * Sending SMTP QUIT on signal is theoretically nice, but led to a
1002 * subtle bug. If fetchmail was terminated by signal while it was
1003 * shipping message text, it would hang forever waiting for a
1004 * command acknowledge. In theory we could enable the QUIT
1005 * only outside of the message send. In practice, we don't
1006 * care. All mailservers hang up on a dropped TCP/IP connection
1011 error(0, 0, "terminated with signal %d", sig);
1013 /* terminate all SMTP connections cleanly */
1014 for (ctl = querylist; ctl; ctl = ctl->next)
1015 if (ctl->smtp_socket != -1)
1016 SMTP_quit(ctl->smtp_socket);
1020 write_saved_lists(querylist, run.idfile);
1021 #endif /* POP3_ENABLE */
1024 * Craig Metz, the RFC1938 one-time-password guy, points out:
1025 * "Remember that most kernels don't zero pages before handing them to the
1026 * next process and many kernels share pages between user and kernel space.
1027 * You'd be very surprised what you can find from a short program to do a
1028 * malloc() and then dump the contents of the pages you got. By zeroing
1029 * the secrets at end of run (earlier if you can), you make sure the next
1030 * guy can't get the password/pass phrase."
1032 * Right you are, Craig!
1034 for (ctl = querylist; ctl; ctl = ctl->next)
1036 memset(ctl->password, '\0', strlen(ctl->password));
1038 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
1042 exit(successes ? PS_SUCCESS : querystatus);
1046 * Sequence of protocols to try when autoprobing, most capable to least.
1048 static const int autoprobe[] =
1052 #endif /* IMAP_ENABLE */
1055 #endif /* POP3_ENABLE */
1058 #endif /* POP2_ENABLE */
1061 static int query_host(struct query *ctl)
1062 /* perform fetch transaction with single host */
1066 if (outlevel == O_VERBOSE)
1071 fprintf(stderr, "fetchmail: %s querying %s (protocol %s) at %s",
1073 ctl->server.pollname, showproto(ctl->server.protocol), ctime(&now));
1075 switch (ctl->server.protocol) {
1077 for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
1079 ctl->server.protocol = autoprobe[i];
1080 if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
1083 ctl->server.protocol = P_AUTO;
1088 return(doPOP2(ctl));
1090 fprintf(stderr, "POP2 support is not configured.\n");
1091 return(PS_PROTOCOL);
1092 #endif /* POP2_ENABLE */
1098 return(doPOP3(ctl));
1100 fprintf(stderr, "POP3 support is not configured.\n");
1101 return(PS_PROTOCOL);
1102 #endif /* POP3_ENABLE */
1110 return(doIMAP(ctl));
1112 fprintf(stderr, "IMAP support is not configured.\n");
1113 return(PS_PROTOCOL);
1114 #endif /* IMAP_ENABLE */
1118 fprintf(stderr, "ETRN support is not configured.\n");
1119 return(PS_PROTOCOL);
1121 #ifdef HAVE_GETHOSTBYNAME
1122 return(doETRN(ctl));
1124 fprintf(stderr, "Cannot support ETRN without gethostbyname(2).\n");
1125 return(PS_PROTOCOL);
1126 #endif /* HAVE_GETHOSTBYNAME */
1127 #endif /* ETRN_ENABLE */
1129 error(0, 0, "unsupported protocol selected.");
1130 return(PS_PROTOCOL);
1134 void dump_params (struct runctl *runp, struct query *querylist, flag implicit)
1135 /* display query parameters in English */
1139 if (runp->poll_interval)
1140 printf("Poll interval is %d seconds\n", runp->poll_interval);
1142 printf("Logfile is %s\n", runp->logfile);
1143 if (strcmp(runp->idfile, IDFILE_NAME))
1144 printf("Idfile is %s\n", runp->idfile);
1145 #if defined(HAVE_SYSLOG)
1146 if (runp->use_syslog)
1147 printf("Progress messages will be logged via syslog\n");
1149 if (runp->invisible)
1150 printf("Fetchmail will masquerade and will not generate Received\n");
1151 if (runp->postmaster)
1152 printf("Fetchmail will forward misaddressed multidrop messages to %s.\n",
1155 for (ctl = querylist; ctl; ctl = ctl->next)
1157 if (!ctl->active || (implicit && ctl->server.skip))
1160 printf("Options for retrieving from %s@%s:\n",
1161 ctl->remotename, visbuf(ctl->server.pollname));
1163 if (ctl->server.via && (ctl->server.protocol != P_ETRN))
1164 printf(" Mail will be retrieved via %s\n", ctl->server.via);
1166 if (ctl->server.interval)
1167 printf(" Poll of this server will occur every %d intervals.\n",
1168 ctl->server.interval);
1169 if (ctl->server.truename)
1170 printf(" True name of server is %s.\n", ctl->server.truename);
1171 if (ctl->server.skip || outlevel == O_VERBOSE)
1172 printf(" This host will%s be queried when no host is specified.\n",
1173 ctl->server.skip ? " not" : "");
1175 * Don't poll for password when there is one or when using the ETRN
1176 * or IMAP-GSS protocol
1178 if (!ctl->password && (ctl->server.protocol != P_ETRN)
1180 && (ctl->server.protocol != P_IMAP_GSS)
1183 printf(" Password will be prompted for.\n");
1184 else if (outlevel == O_VERBOSE)
1185 if (ctl->server.protocol == P_APOP)
1186 printf(" APOP secret = '%s'.\n", visbuf(ctl->password));
1187 else if (ctl->server.protocol == P_RPOP)
1188 printf(" RPOP id = '%s'.\n", visbuf(ctl->password));
1190 printf(" Password = '%s'.\n", visbuf(ctl->password));
1191 if (ctl->server.protocol == P_POP3
1193 && !strcmp(ctl->server.service, KPOP_PORT)
1195 && ctl->server.port == KPOP_PORT
1197 && (ctl->server.preauthenticate == A_KERBEROS_V4 ||
1198 ctl->server.preauthenticate == A_KERBEROS_V5))
1199 printf(" Protocol is KPOP");
1201 printf(" Protocol is %s", showproto(ctl->server.protocol));
1203 if (ctl->server.service)
1204 printf(" (using service %s)", ctl->server.service);
1205 if (ctl->server.netsec)
1206 printf(" (using network security options %s)", ctl->server.netsec);
1208 if (ctl->server.port)
1209 printf(" (using port %d)", ctl->server.port);
1211 else if (outlevel == O_VERBOSE)
1212 printf(" (using default port)");
1213 if (ctl->server.uidl && (ctl->server.protocol != P_ETRN))
1214 printf(" (forcing UIDL use)");
1217 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1218 printf(" Kerberos V4 preauthentication enabled.\n");
1219 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1220 printf(" Kerberos V5 preauthentication enabled.\n");
1221 if (ctl->server.timeout > 0)
1222 printf(" Server nonresponse timeout is %d seconds", ctl->server.timeout);
1223 if (ctl->server.timeout == CLIENT_TIMEOUT)
1224 printf(" (default).\n");
1228 if (ctl->server.protocol != P_ETRN) {
1229 if (!ctl->mailboxes->id)
1230 printf(" Default mailbox selected.\n");
1235 printf(" Selected mailboxes are:");
1236 for (idp = ctl->mailboxes; idp; idp = idp->next)
1237 printf(" %s", idp->id);
1240 printf(" %s messages will be retrieved (--all %s).\n",
1241 ctl->fetchall ? "All" : "Only new",
1242 ctl->fetchall ? "on" : "off");
1243 printf(" Fetched messages will%s be kept on the server (--keep %s).\n",
1244 ctl->keep ? "" : " not",
1245 ctl->keep ? "on" : "off");
1246 printf(" Old messages will%s be flushed before message retrieval (--flush %s).\n",
1247 ctl->flush ? "" : " not",
1248 ctl->flush ? "on" : "off");
1249 printf(" Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
1250 ctl->rewrite ? "en" : "dis",
1251 ctl->rewrite ? "off" : "on");
1252 printf(" Carriage-return stripping is %sabled (stripcr %s).\n",
1253 ctl->stripcr ? "en" : "dis",
1254 ctl->stripcr ? "on" : "off");
1255 printf(" Carriage-return forcing is %sabled (forcecr %s).\n",
1256 ctl->forcecr ? "en" : "dis",
1257 ctl->forcecr ? "on" : "off");
1258 printf(" Interpretation of Content-Transfer-Encoding is %sabled (pass8bits %s).\n",
1259 ctl->pass8bits ? "dis" : "en",
1260 ctl->pass8bits ? "on" : "off");
1261 printf(" MIME decoding is %sabled (mimedecode %s).\n",
1262 ctl->mimedecode ? "en" : "dis",
1263 ctl->mimedecode ? "on" : "off");
1264 printf(" Nonempty Status lines will be %s (dropstatus %s)\n",
1265 ctl->dropstatus ? "discarded" : "kept",
1266 ctl->dropstatus ? "on" : "off");
1267 if (NUM_NONZERO(ctl->limit))
1268 printf(" Message size limit is %d bytes (--limit %d).\n",
1269 ctl->limit, ctl->limit);
1270 else if (outlevel == O_VERBOSE)
1271 printf(" No message size limit (--limit 0).\n");
1272 if (NUM_NONZERO(ctl->fetchlimit))
1273 printf(" Received-message limit is %d (--fetchlimit %d).\n",
1274 ctl->fetchlimit, ctl->fetchlimit);
1275 else if (outlevel == O_VERBOSE)
1276 printf(" No received-message limit (--fetchlimit 0).\n");
1277 if (NUM_NONZERO(ctl->batchlimit))
1278 printf(" SMTP message batch limit is %d.\n", ctl->batchlimit);
1279 else if (outlevel == O_VERBOSE)
1280 printf(" No SMTP message batch limit (--batchlimit 0).\n");
1281 if (ctl->server.protocol == P_IMAP)
1282 if (NUM_NONZERO(ctl->expunge))
1283 printf(" Deletion interval between expunges is %d (--expunge %d).\n", ctl->expunge, ctl->expunge);
1284 else if (outlevel == O_VERBOSE)
1285 printf(" No expunges (--expunge 0).\n");
1287 if (ctl->mda && (ctl->server.protocol != P_ETRN))
1288 printf(" Messages will be delivered with '%s.'\n", visbuf(ctl->mda));
1293 printf(" Messages will be SMTP-forwarded to:");
1294 for (idp = ctl->smtphunt; idp; idp = idp->next)
1296 printf(" %s", idp->id);
1297 if (!idp->val.status.mark)
1298 printf(" (default)");
1301 if (ctl->smtpaddress)
1302 printf(" Host part of MAIL FROM line will be %s\n",
1305 if (ctl->server.protocol != P_ETRN)
1307 if (ctl->antispam != (struct idlist *)NULL)
1311 printf(" Recognized listener spam block responses are:",
1313 for (idp = ctl->antispam; idp; idp = idp->next)
1314 printf(" %d", idp->val.status.num);
1317 else if (outlevel == O_VERBOSE)
1318 printf(" Spam-blocking disabled\n");
1320 if (ctl->preconnect)
1321 printf(" Server connection will be brought up with '%s.'\n",
1322 visbuf(ctl->preconnect));
1323 else if (outlevel == O_VERBOSE)
1324 printf(" No pre-connection command.\n");
1325 if (ctl->postconnect)
1326 printf(" Server connection will be taken down with '%s.'\n",
1327 visbuf(ctl->postconnect));
1328 else if (outlevel == O_VERBOSE)
1329 printf(" No post-connection command.\n");
1330 if (ctl->server.protocol != P_ETRN) {
1331 if (!ctl->localnames)
1332 printf(" No localnames declared for this host.\n");
1338 for (idp = ctl->localnames; idp; idp = idp->next)
1341 if (count > 1 || ctl->wildcard)
1342 printf(" Multi-drop mode: ");
1344 printf(" Single-drop mode: ");
1346 printf("%d local name(s) recognized.\n", count);
1347 if (outlevel == O_VERBOSE)
1349 for (idp = ctl->localnames; idp; idp = idp->next)
1351 printf("\t%s -> %s\n", idp->id, idp->val.id2);
1353 printf("\t%s\n", idp->id);
1355 fputs("\t*\n", stdout);
1358 if (count > 1 || ctl->wildcard)
1360 printf(" DNS lookup for multidrop addresses is %sabled.\n",
1361 ctl->server.dns ? "en" : "dis");
1362 if (ctl->server.dns)
1364 printf(" Server aliases will be compared with multidrop addresses by ");
1365 if (ctl->server.checkalias)
1366 printf("IP address.\n");
1370 if (ctl->server.envelope == STRING_DISABLED)
1371 printf(" Envelope-address routing is disabled\n");
1374 printf(" Envelope header is assumed to be: %s\n",
1375 ctl->server.envelope ? ctl->server.envelope:"Received");
1376 if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1377 printf(" Number of envelope header to be parsed: %d\n",
1378 ctl->server.envskip);
1379 if (ctl->server.qvirtual)
1380 printf(" Prefix %s will be removed from user id\n",
1381 ctl->server.qvirtual);
1382 else if (outlevel >= O_VERBOSE)
1383 printf(" No prefix stripping\n");
1386 if (ctl->server.akalist)
1390 printf(" Predeclared mailserver aliases:");
1391 for (idp = ctl->server.akalist; idp; idp = idp->next)
1392 printf(" %s", idp->id);
1395 if (ctl->server.localdomains)
1399 printf(" Local domains:");
1400 for (idp = ctl->server.localdomains; idp; idp = idp->next)
1401 printf(" %s", idp->id);
1408 if (ctl->server.interface)
1409 printf(" Connection must be through interface %s.\n", ctl->server.interface);
1410 else if (outlevel == O_VERBOSE)
1411 printf(" No interface requirement specified.\n");
1412 if (ctl->server.monitor)
1413 printf(" Polling loop will monitor %s.\n", ctl->server.monitor);
1414 else if (outlevel == O_VERBOSE)
1415 printf(" No monitor interface specified.\n");
1418 if (ctl->server.protocol > P_POP2 && (ctl->server.protocol != P_ETRN))
1420 printf(" No UIDs saved from this host.\n");
1426 for (idp = ctl->oldsaved; idp; idp = idp->next)
1429 printf(" %d UIDs saved.\n", count);
1430 if (outlevel == O_VERBOSE)
1431 for (idp = ctl->oldsaved; idp; idp = idp->next)
1432 fprintf(stderr, "\t%s\n", idp->id);
1437 /* fetchmail.c ends here */