2 * fetchmail.c -- main driver module for fetchmail
4 * For license terms, see the file COPYING in this directory.
11 #if defined(STDC_HEADERS)
14 #if defined(HAVE_UNISTD_H)
17 #if defined(HAVE_ALLOCA_H)
25 #include <sys/types.h>
29 #ifdef HAVE_GETHOSTBYNAME
31 #endif /* HAVE_GETHOSTBYNAME */
33 #include "fetchmail.h"
37 #define DROPDEAD 6 /* maximum bad socket opens */
39 /* prototypes for internal functions */
40 static int load_params(int, char **, int);
41 static void dump_params (struct query *);
42 static int query_host(struct query *);
43 static char *visbuf(const char *);
45 /* controls the detail level of status/progress messages written to stderr */
46 int outlevel; /* see the O_.* constants above */
47 int yydebug; /* enable parse debugging */
49 /* daemon mode control */
50 int poll_interval; /* poll interval in seconds */
51 int nodetach; /* if TRUE, don't detach daemon process */
52 char *logfile; /* log file for daemon mode */
53 int quitmode; /* if --quit was set */
54 int check_only; /* if --probe was set */
55 int cmd_batchlimit; /* if --batchlimit was set */
56 char *cmd_logfile; /* if --logfile was set */
58 /* miscellaneous global controls */
59 char *rcfile; /* path name of rc file */
60 char *idfile; /* UID list file */
61 int versioninfo; /* emit only version info */
62 char *user; /* the name of the invoking user */
64 static char *lockfile; /* name of lockfile */
65 static int querystatus; /* status of query */
66 static int lastsig; /* last signal received */
68 static void termhook(); /* forward declaration of exit hook */
70 RETSIGTYPE donothing(sig) int sig; {signal(sig, donothing); lastsig = sig;}
72 static void unlockit(void)
73 /* must-do actions for exit (but we can't count on being able to do malloc) */
78 int main (int argc, char **argv)
81 int parsestatus, implicitmode;
82 char *home, *tmpdir, tmpbuf[BUFSIZ];
88 if ((user = getenv("USER")) == (char *)NULL)
89 user = getenv("LOGNAME");
91 if ((user == (char *)NULL) || (home = getenv("HOME")) == (char *)NULL)
93 if ((pw = getpwuid(getuid())) != NULL)
100 fprintf(stderr,"fetchmail: can't find your name and home directory!\n");
106 * Backward-compatibility hack. If we're called by the name of the
107 * ancestral popclient, look for .poprc. This will actually work
108 * for popclient files that don't use the removed keywords.
110 if (strcmp("popclient", argv[0]) == 0)
113 tmpdir = ".fetchmailrc";
115 rcfile = (char *) xmalloc(strlen(home)+strlen(tmpdir)+2);
116 strcpy(rcfile, home);
118 strcat(rcfile, tmpdir);
120 #define IDFILE_NAME ".fetchids"
121 idfile = (char *) xmalloc(strlen(home)+strlen(IDFILE_NAME)+2);
122 strcpy(idfile, home);
124 strcat(idfile, IDFILE_NAME);
128 if ((parsestatus = parsecmdline(argc,argv,&cmd_opts)) < 0)
132 printf("This is fetchmail release %s pl %s\n", RELEASE_ID, PATCHLEVEL);
134 /* avoid parsing the config file if all we're doing is killing a daemon */
136 implicitmode = load_params(argc, argv, optind);
138 /* set up to do lock protocol */
139 if ((tmpdir = getenv("TMPDIR")) == (char *)NULL)
141 strcpy(tmpbuf, tmpdir);
142 strcat(tmpbuf, "/fetchmail-");
143 strcat(tmpbuf, user);
145 /* perhaps we just want to check options? */
147 printf("Taking options from command line");
148 if (access(rcfile, 0))
151 printf(" and %s\n", rcfile);
152 if (outlevel == O_VERBOSE)
153 printf("Lockfile at %s\n", tmpbuf);
155 printf("SMTP message batch limit is %d.\n", batchlimit);
157 printf("No SMTP message batch limit.\n");
158 for (ctl = querylist; ctl; ctl = ctl->next) {
159 if (ctl->active && !(implicitmode && ctl->skip))
162 if (querylist == NULL)
163 (void) fprintf(stderr,
164 "No mailservers set up -- perhaps %s is missing?\n",
168 else if (!quitmode && querylist == NULL) {
169 (void) fputs("fetchmail: no mailservers have been specified.\n", stderr);
173 /* check for another fetchmail running concurrently */
175 if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
177 fprintf(stderr,"fetchmail: cannot allocate memory for lock name.\n");
181 (void) strcpy(lockfile, tmpbuf);
182 if ((lockfp = fopen(lockfile, "r")) != NULL )
184 bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
186 if (kill(pid, 0) == -1) {
187 fprintf(stderr,"fetchmail: removing stale lockfile\n");
195 /* perhaps user asked us to kill the other fetchmail */
200 fprintf(stderr,"fetchmail: no other fetchmail is running\n");
203 else if (kill(pid, SIGTERM) < 0)
205 fprintf(stderr,"fetchmail: error killing %s fetchmail at %d.\n",
206 bkgd ? "background" : "foreground", pid);
211 fprintf(stderr,"fetchmail: %s fetchmail at %d killed.\n",
212 bkgd ? "background" : "foreground", pid);
218 /* another fetchmail is running -- wake it up or die */
223 else if (!implicitmode)
226 "fetchmail: can't poll specified hosts with another fetchmail running at %d.\n",
233 "fetchmail: another foreground fetchmail is running at %d.\n",
237 else if (kill(pid, SIGHUP) == 0)
240 "fetchmail: background fetchmail at %d awakened.\n",
247 * Should never happen -- possible only if a background fetchmail
248 * croaks after the first kill probe above but before the SIGHUP
252 "fetchmail: elder sibling at %d died mysteriously.\n",
254 return(PS_UNDEFINED);
258 /* pick up interactively any passwords we need but don't have */
259 for (ctl = querylist; ctl; ctl = ctl->next)
260 if (ctl->active && !(implicitmode && ctl->skip) && !ctl->password[0])
262 if (ctl->authenticate == A_KERBEROS)
263 /* Server won't care what the password is, but there
264 must be some non-null string here. */
265 (void) strncpy(ctl->password,
266 ctl->remotename, PASSWORDLEN-1);
269 (void) sprintf(tmpbuf, "Enter password for %s@%s: ",
270 ctl->remotename, ctl->servernames->id);
271 (void) strncpy(ctl->password,
272 (char *)getpassword(tmpbuf),PASSWORDLEN-1);
277 * Maybe time to go to demon mode...
279 if (poll_interval && !nodetach)
280 daemonize(logfile, termhook);
282 /* beyond here we don't want more than one fetchmail running per user */
284 signal(SIGABRT, termhook);
285 signal(SIGINT, termhook);
286 signal(SIGTERM, termhook);
287 signal(SIGALRM, termhook);
288 signal(SIGPIPE, termhook);
289 signal(SIGQUIT, termhook);
292 * With this simple hack, we make it possible for a foreground
293 * fetchmail to wake up one in daemon mode. What we want is the
294 * side effect of interrupting any sleep that may be going on,
295 * forcing fetchmail to re-poll its hosts.
297 signal(SIGHUP, donothing);
299 /* here's the exclusion lock */
300 if ( (lockfp = fopen(lockfile,"w")) != NULL ) {
301 fprintf(lockfp,"%d",getpid());
303 fprintf(lockfp," %d", poll_interval);
309 * Query all hosts. If there's only one, the error return will
310 * reflect the status of that transaction.
313 #ifdef HAVE_RES_SEARCH
314 sethostent(TRUE); /* use TCP/IP for mailserver queries */
315 #endif /* HAVE_RES_SEARCH */
318 for (ctl = querylist; ctl; ctl = ctl->next)
320 if (ctl->active && !(implicitmode && ctl->skip))
322 #ifdef HAVE_GETHOSTBYNAME
324 * This functions partly as an optimization and partly
325 * as a probe to make sure our nameserver is still up.
326 * The multidrop case (especially) needs it.
328 if (ctl->authenticate == A_KERBEROS || MULTIDROP(ctl))
330 struct hostent *namerec;
332 /* compute the canonical name of the host */
334 namerec = gethostbyname(ctl->servernames->id);
335 if (namerec == (struct hostent *)NULL)
338 "fetchmail: skipping %s poll, ",
339 ctl->servernames->id);
342 perror("general error");
343 if (errno == ENETUNREACH)
344 break; /* go to sleep */
352 free(ctl->canonical_name);
353 ctl->canonical_name = xstrdup((char *)namerec->h_name);
356 #endif /* HAVE_GETHOSTBYNAME */
358 querystatus = query_host(ctl);
360 update_str_lists(ctl);
364 #ifdef HAVE_RES_SEARCH
365 endhostent(); /* release TCP/IP connection to nameserver */
366 #endif /* HAVE_RES_SEARCH */
369 * Close all SMTP delivery sockets. For optimum performance
370 * we'd like to hold them open til end of run, but (1) this
371 * loses if our poll interval is longer than the MTA's inactivity
372 * timeout, and (2) some MTAs (like smail) don't deliver after
373 * each message, but rather queue up mail and wait to actually
374 * deliver it until the input socket is closed.
376 for (ctl = querylist; ctl; ctl = ctl->next)
377 if (ctl->smtp_sockfp)
379 SMTP_quit(ctl->smtp_sockfp);
380 fclose(ctl->smtp_sockfp);
381 ctl->smtp_sockfp = (FILE *)NULL;
386 if (outlevel == O_VERBOSE)
391 fprintf(stderr, "fetchmail: sleeping at %s", ctime(&now));
395 * We can't use sleep(3) here because we need an alarm(3)
396 * equivalent in order to implement server nonresponse timeout.
397 * We'll just assume setitimer(2) is available since fetchmail
398 * has to have a BSDoid socket layer to work at all.
401 struct itimerval ntimeout;
403 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
404 ntimeout.it_value.tv_sec = poll_interval;
405 ntimeout.it_value.tv_usec = 0;
407 setitimer(ITIMER_REAL,&ntimeout,NULL);
408 signal(SIGALRM, donothing);
410 if (lastsig == SIGHUP)
411 (void) fputs("fetchmail: awakened by SIGHUP\n", stderr);
414 if (outlevel == O_VERBOSE)
419 fprintf(stderr, "fetchmail: awakened at %s", ctime(&now));
425 if (outlevel == O_VERBOSE)
426 fprintf(stderr,"fetchmail: normal termination, status %d\n",querystatus);
432 static int load_params(int argc, char **argv, int optind)
434 int implicitmode, st;
436 struct query def_opts, *ctl, *mp;
438 memset(&def_opts, '\0', sizeof(struct query));
440 def_opts.protocol = P_AUTO;
441 def_opts.timeout = CLIENT_TIMEOUT;
442 strcpy(def_opts.remotename, user);
443 strcpy(def_opts.smtphost, "localhost");
445 /* this builds the host list */
446 if (prc_parse_file(rcfile) != 0)
449 if ((implicitmode = (optind >= argc)))
451 for (ctl = querylist; ctl; ctl = ctl->next)
455 for (; optind < argc; optind++)
458 * If hostname corresponds to a host known from the rc file,
459 * simply declare it active. Otherwise synthesize a host
460 * record from command line and defaults
462 for (ctl = querylist; ctl; ctl = ctl->next)
463 if (str_in_list(&ctl->servernames, argv[optind]))
466 ctl = hostalloc(&cmd_opts);
467 save_str(&ctl->servernames, -1, argv[optind]);
473 /* if there's a defaults record, merge it and lose it */
474 if (querylist && strcmp(querylist->servernames->id, "defaults") == 0)
476 for (ctl = querylist; ctl; ctl = ctl->next)
477 optmerge(ctl, querylist);
478 querylist = querylist->next;
481 /* don't allow a defaults record after the first */
482 for (ctl = querylist; ctl; ctl = ctl->next)
483 if (ctl != querylist && strcmp(ctl->servernames->id, "defaults") == 0)
486 /* merge in wired defaults, do sanity checks and prepare internal fields */
487 for (ctl = querylist; ctl; ctl = ctl->next)
489 if (ctl->active && !(implicitmode && ctl->skip))
491 /* merge in defaults */
492 optmerge(ctl, &def_opts);
494 /* keep lusers from shooting themselves in the foot :-) */
495 if (poll_interval && ctl->limit)
497 fprintf(stderr,"fetchmail: you'd never see large messages!\n");
501 /* make sure delivery will default to a real local user */
502 if ((pw = getpwnam(user)) == (struct passwd *)NULL)
505 "fetchmail: can't set up default delivery to %s\n", user);
506 exit(PS_SYNTAX); /* has to be from bad rc file */
510 ctl->uid = pw->pw_uid; /* for local delivery via MDA */
511 if (!ctl->localnames) /* for local delivery via SMTP */
512 save_str(&ctl->localnames, -1, user);
515 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
516 /* can't handle multidrop mailboxes unless we can do DNS lookups */
517 if (ctl->localnames && ctl->localnames->next)
519 fputs("fetchmail: can't handle multidrop mailboxes without DNS\n",
523 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
526 * Assign SMTP leaders. We want to allow all query blocks
527 * sharing the same SMTP host to use the same SMTP connection.
528 * To accomplish this, we initialize each query block's leader
529 * field to point to the first block in the list with a matching
532 * In the typical case, there will be only one SMTP host (the
533 * client machine) and thus just one SMTP leader (and one listener
534 * process) through the entire poll cycle.
538 ctl->smtp_sockfp = (FILE *)NULL;
539 for (mp = querylist; mp && mp != ctl; mp = mp->next)
540 if (strcmp(mp->smtphost, ctl->smtphost) == 0)
542 ctl->lead_smtp = mp->lead_smtp;
545 ctl->lead_smtp = ctl;
549 /* similarly, compute server leaders for queries */
550 for (mp = querylist; mp && mp != ctl; mp = mp->next)
551 if (strcmp(mp->servernames->id, ctl->servernames->id) == 0)
553 ctl->lead_server = mp->lead_server;
556 ctl->lead_server = ctl;
562 (void) fprintf(stderr,
563 "%s configuration invalid, port number cannot be negative",
564 ctl->servernames->id);
568 /* expand MDA commands */
569 if (!check_only && ctl->mda[0])
573 /* punch nulls into the delimiting whitespace in the args */
574 for (argp = ctl->mda, ctl->mda_argcount = 1; *argp != '\0'; ctl->mda_argcount++)
576 ctl->mda_argv[ctl->mda_argcount] = argp;
577 while (!(*argp == '\0' || isspace(*argp)))
583 ctl->mda_argv[ctl->mda_argcount] = (char *)NULL;
585 ctl->mda_argv[0] = ctl->mda_argv[1];
586 if ((argp = strrchr(ctl->mda_argv[1], '/')) != (char *)NULL)
587 ctl->mda_argv[1] = argp + 1 ;
592 /* initialize UID handling */
593 if ((st = prc_filecheck(idfile)) != 0)
596 initialize_saved_lists(querylist, idfile);
598 /* if cmd_batchlimit was explicitly set, use it to override batchlimit */
599 if (cmd_batchlimit > -1)
600 batchlimit = cmd_batchlimit;
602 /* if cmd_logfile was explicitly set, use it to override logfile */
604 logfile = cmd_logfile;
606 return(implicitmode);
609 void termhook(int sig)
610 /* to be executed on normal or signal-induced termination */
615 fprintf(stderr, "terminated with signal %d\n", sig);
617 /* terminate all SMTP connections cleanly */
618 for (ctl = querylist; ctl; ctl = ctl->next)
619 if (ctl->lead_smtp == ctl && ctl->smtp_sockfp != (FILE *)NULL)
620 SMTP_quit(ctl->smtp_sockfp);
623 write_saved_lists(querylist, idfile);
628 static char *showproto(int proto)
629 /* protocol index to protocol name mapping */
633 case P_AUTO: return("auto"); break;
634 case P_POP2: return("POP2"); break;
635 case P_POP3: return("POP3"); break;
636 case P_IMAP: return("IMAP"); break;
637 case P_APOP: return("APOP"); break;
638 default: return("unknown?!?"); break;
643 * Sequence of protocols to try when autoprobing, most capable to least.
645 static const int autoprobe[] = {P_IMAP, P_POP3, P_POP2};
647 static int query_host(struct query *ctl)
648 /* perform fetch transaction with single host */
652 if (outlevel == O_VERBOSE)
657 fprintf(stderr, "Querying %s (protocol %s) at %s",
658 ctl->servernames->id, showproto(ctl->protocol), ctime(&now));
660 switch (ctl->protocol) {
662 for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
664 ctl->protocol = autoprobe[i];
665 if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL)
668 ctl->protocol = P_AUTO;
682 fprintf(stderr,"fetchmail: unsupported protocol selected.\n");
687 void dump_params (struct query *ctl)
688 /* display query parameters in English */
690 printf("Options for retrieving from %s@%s:\n",
691 ctl->remotename, visbuf(ctl->servernames->id));
692 #ifdef HAVE_GETHOSTBYNAME
693 if (ctl->canonical_name)
694 printf(" Canonical DNS name of server is %s.\n", ctl->canonical_name);
695 #endif /* HAVE_GETHOSTBYNAME */
696 if (ctl->servernames->next)
700 printf(" Predeclared mailserver aliases:");
701 for (idp = ctl->servernames->next; idp; idp = idp->next)
702 printf(" %s", idp->id);
705 if (ctl->skip || outlevel == O_VERBOSE)
706 printf(" This host will%s be queried when no host is specified.\n",
707 ctl->skip ? " not" : "");
708 if (ctl->password[0] == '\0')
709 printf(" Password will be prompted for.\n");
710 else if (outlevel == O_VERBOSE)
711 if (ctl->protocol == P_APOP)
712 printf(" APOP secret = '%s'.\n", visbuf(ctl->password));
714 printf(" Password = '%s'.\n", visbuf(ctl->password));
715 if (ctl->protocol == P_POP3
716 && ctl->port == KPOP_PORT
717 && ctl->authenticate == A_KERBEROS)
718 printf(" Protocol is KPOP");
720 printf(" Protocol is %s", showproto(ctl->protocol));
722 printf(" (using port %d)", ctl->port);
723 else if (outlevel == O_VERBOSE)
724 printf(" (using default port)");
727 if (ctl->authenticate == A_KERBEROS)
728 printf(" Kerberos authentication enabled.\n");
729 printf(" Server nonresponse timeout is %d seconds", ctl->timeout);
730 if (ctl->timeout == CLIENT_TIMEOUT)
731 printf(" (default).\n");
735 printf(" %s messages will be retrieved (--all %s).\n",
736 ctl->fetchall ? "All" : "Only new",
737 ctl->fetchall ? "on" : "off");
738 printf(" Fetched messages will%s be kept on the server (--keep %s).\n",
739 ctl->keep ? "" : " not",
740 ctl->keep ? "on" : "off");
741 printf(" Old messages will%s be flushed before message retrieval (--flush %s).\n",
742 ctl->flush ? "" : " not",
743 ctl->flush ? "on" : "off");
744 printf(" Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
745 ctl->norewrite ? "dis" : "en",
746 ctl->norewrite ? "on" : "off");
748 printf(" Message size limit is %d bytes\n", ctl->limit);
749 else if (outlevel == O_VERBOSE)
750 printf(" No message size limit\n");
755 printf(" Messages will be delivered with %s, args:",
756 visbuf(ctl->mda_argv[0]));
757 for (cp = ctl->mda_argv+1; *cp; cp++)
758 printf(" %s", visbuf(*cp));
762 printf(" Messages will be SMTP-forwarded to '%s'.\n",
763 visbuf(ctl->smtphost));
764 if (!ctl->localnames)
765 printf(" No localnames declared for this host.\n");
771 for (idp = ctl->localnames; idp; idp = idp->next)
774 printf(" %d local name(s) recognized%s.\n",
776 (count == 1 && !strcmp(ctl->localnames->id, user)) ? " (by default)" : "");
777 if (outlevel == O_VERBOSE)
779 for (idp = ctl->localnames; idp; idp = idp->next)
781 fprintf(stderr, "\t%s -> %s\n", idp->id, idp->val.id2);
783 fprintf(stderr, "\t%s\n", idp->id);
785 fputs("*\n", stderr);
789 if (ctl->protocol > P_POP2)
791 printf(" No UIDs saved from this host.\n");
797 for (idp = ctl->oldsaved; idp; idp = idp->next)
800 printf(" %d UIDs saved.\n", count);
801 if (outlevel == O_VERBOSE)
802 for (idp = ctl->oldsaved; idp; idp = idp->next)
803 fprintf(stderr, "\t%s\n", idp->id);
807 int openmailpipe (char **argv)
808 /* open a one-way pipe to a mail delivery agent */
813 if (outlevel == O_VERBOSE)
817 printf("fetchmail: about to deliver via MDA %s, args:",
819 for (cp = argv+1; *cp; cp++)
820 printf(" %s", visbuf(*cp));
824 if (pipe(pipefd) < 0) {
825 perror("fetchmail: openmailpipe: pipe");
828 if ((childpid = fork()) < 0) {
829 perror("fetchmail: openmailpipe: fork");
832 else if (childpid == 0) {
834 /* in child process space */
835 close(pipefd[1]); /* close the 'write' end of the pipe */
836 close(0); /* get rid of inherited stdin */
837 if (dup(pipefd[0]) != 0) {
838 fputs("fetchmail: openmailpipe: dup() failed\n",stderr);
842 execv(argv[0], argv + 1);
844 /* if we got here, an error occurred */
845 perror("fetchmail: openmailpipe: exec");
850 /* in the parent process space */
851 close(pipefd[0]); /* close the 'read' end of the pipe */
855 int closemailpipe (fd)
856 /* close the pipe to the mail delivery agent */
862 if ((err = close(fd)) != 0)
863 perror("fetchmail: closemailpipe: close failed");
865 childpid = wait(&status);
867 #if defined(WIFEXITED) && defined(WEXITSTATUS)
869 * Try to pass up an error if the MDA returned nonzero status,
870 * on the assumption that this means it was reporting failure.
872 if (WIFEXITED(status) == 0 || WEXITSTATUS(status) != 0)
874 perror("fetchmail: MDA exited abnormally or returned nonzero status");
882 /* helper functions for string interpretation and display */
884 #define CTRL(x) ((x) & 0x1f)
887 /* process standard C-style escape sequences in a string */
888 const char *cp; /* source string with escapes */
889 char *tp; /* target buffer for digested string */
895 if (*cp == '\\' && strchr("0123456789xX", cp[1]))
897 char *dp, *hex = "00112233445566778899aAbBcCdDeEfF";
900 if (*++cp == 'x' || *cp == 'X')
901 for (++cp; (dp = strchr(hex, *cp)) && (dcount++ < 2); cp++)
902 cval = (cval * 16) + (dp - hex) / 2;
904 while (strchr("01234567",*cp) != (char*)NULL && (dcount++ < 3))
905 cval = (cval * 8) + (*cp++ - '0');
907 while ((strchr("0123456789",*cp)!=(char*)NULL)&&(dcount++ < 3))
908 cval = (cval * 10) + (*cp++ - '0');
910 else if (*cp == '\\') /* C-style character escapes */
914 case '\\': cval = '\\'; break;
915 case 'n': cval = '\n'; break;
916 case 't': cval = '\t'; break;
917 case 'b': cval = '\b'; break;
918 case 'r': cval = '\r'; break;
923 else if (*cp == '^') /* expand control-character syntax */
935 static char *visbuf(const char *buf)
936 /* visibilize a given string */
938 static char vbuf[BUFSIZ];
943 if (isprint(*buf) || *buf == ' ')
945 else if (*buf == '\n')
947 *tp++ = '\\'; *tp++ = 'n';
950 else if (*buf == '\r')
952 *tp++ = '\\'; *tp++ = 'r';
955 else if (*buf == '\b')
957 *tp++ = '\\'; *tp++ = 'b';
962 *tp++ = '\\'; *tp++ = '^'; *tp++ = '@' + *buf;
967 (void) sprintf(tp, "\\0x%02x", *buf++);
975 /* fetchmail.c ends here */