hastd.c revision 220899
166458Sdfr/*-
266458Sdfr * Copyright (c) 2009-2010 The FreeBSD Foundation
366458Sdfr * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
466458Sdfr * All rights reserved.
566458Sdfr *
666458Sdfr * This software was developed by Pawel Jakub Dawidek under sponsorship from
766458Sdfr * the FreeBSD Foundation.
866458Sdfr *
966458Sdfr * Redistribution and use in source and binary forms, with or without
1066458Sdfr * modification, are permitted provided that the following conditions
1166458Sdfr * are met:
1266458Sdfr * 1. Redistributions of source code must retain the above copyright
1366458Sdfr *    notice, this list of conditions and the following disclaimer.
1466458Sdfr * 2. Redistributions in binary form must reproduce the above copyright
1566458Sdfr *    notice, this list of conditions and the following disclaimer in the
1666458Sdfr *    documentation and/or other materials provided with the distribution.
1766458Sdfr *
1866458Sdfr * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
1966458Sdfr * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2066458Sdfr * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2166458Sdfr * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
2266458Sdfr * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2366458Sdfr * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2466458Sdfr * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2566458Sdfr * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2666458Sdfr * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2766458Sdfr * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2866458Sdfr * SUCH DAMAGE.
2966458Sdfr */
3066458Sdfr
3166458Sdfr#include <sys/cdefs.h>
3266458Sdfr__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 220899 2011-04-20 18:49:12Z pjd $");
3366458Sdfr
3466458Sdfr#include <sys/param.h>
3566458Sdfr#include <sys/linker.h>
3666458Sdfr#include <sys/module.h>
3766458Sdfr#include <sys/stat.h>
3866458Sdfr#include <sys/wait.h>
3966458Sdfr
4066458Sdfr#include <err.h>
4166458Sdfr#include <errno.h>
4266458Sdfr#include <libutil.h>
4366458Sdfr#include <signal.h>
4466458Sdfr#include <stdbool.h>
4566458Sdfr#include <stdio.h>
4666458Sdfr#include <stdlib.h>
4766458Sdfr#include <string.h>
4866458Sdfr#include <sysexits.h>
4966458Sdfr#include <time.h>
50117126Sscottl#include <unistd.h>
51117126Sscottl
5266458Sdfr#include <activemap.h>
5366458Sdfr#include <pjdlog.h>
5466458Sdfr
5566458Sdfr#include "control.h"
5666458Sdfr#include "event.h"
5766458Sdfr#include "hast.h"
58146214Snyan#include "hast_proto.h"
5966458Sdfr#include "hastd.h"
6066458Sdfr#include "hooks.h"
6166458Sdfr#include "subr.h"
6266458Sdfr
6366458Sdfr/* Path to configuration file. */
6466458Sdfrconst char *cfgpath = HAST_CONFIG;
6566458Sdfr/* Hastd configuration. */
6666458Sdfrstatic struct hastd_config *cfg;
6766458Sdfr/* Was SIGINT or SIGTERM signal received? */
6866458Sdfrbool sigexit_received = false;
6966458Sdfr/* PID file handle. */
7066458Sdfrstruct pidfh *pfh;
7166458Sdfr
7266458Sdfr/* How often check for hooks running for too long. */
7366458Sdfr#define	REPORT_INTERVAL	5
7466458Sdfr
7566458Sdfrstatic void
76135262Sphkusage(void)
77135262Sphk{
7866458Sdfr
7966458Sdfr	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
8066458Sdfr}
8166458Sdfr
8266458Sdfrstatic void
8366458Sdfrg_gate_load(void)
8466458Sdfr{
8566458Sdfr
8666458Sdfr	if (modfind("g_gate") == -1) {
8766458Sdfr		/* Not present in kernel, try loading it. */
8866458Sdfr		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
8966458Sdfr			if (errno != EEXIST) {
9066458Sdfr				pjdlog_exit(EX_OSERR,
9166458Sdfr				    "Unable to load geom_gate module");
9266458Sdfr			}
9366458Sdfr		}
9466458Sdfr	}
95135262Sphk}
9666458Sdfr
9766458Sdfrvoid
98135262Sphkdescriptors_cleanup(struct hast_resource *res)
9966458Sdfr{
10066458Sdfr	struct hast_resource *tres;
10166458Sdfr
10266458Sdfr	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
10366458Sdfr		if (tres == res) {
10466458Sdfr			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
10566458Sdfr			    (res->hr_remotein == NULL &&
10666458Sdfr			     res->hr_remoteout == NULL));
10766458Sdfr			continue;
10866458Sdfr		}
109177215Simp		if (tres->hr_remotein != NULL)
110117126Sscottl			proto_close(tres->hr_remotein);
111117126Sscottl		if (tres->hr_remoteout != NULL)
11266458Sdfr			proto_close(tres->hr_remoteout);
113135262Sphk		if (tres->hr_ctrl != NULL)
11466458Sdfr			proto_close(tres->hr_ctrl);
11566458Sdfr		if (tres->hr_event != NULL)
11666458Sdfr			proto_close(tres->hr_event);
117135262Sphk		if (tres->hr_conn != NULL)
11866458Sdfr			proto_close(tres->hr_conn);
11966458Sdfr	}
120135262Sphk	if (cfg->hc_controlin != NULL)
12166458Sdfr		proto_close(cfg->hc_controlin);
12266458Sdfr	proto_close(cfg->hc_controlconn);
12366458Sdfr	proto_close(cfg->hc_listenconn);
12466458Sdfr	(void)pidfile_close(pfh);
12566458Sdfr	hook_fini();
12666458Sdfr	pjdlog_fini();
12766458Sdfr}
12866458Sdfr
12966458Sdfrstatic const char *
13066458Sdfrdtype2str(mode_t mode)
13166458Sdfr{
13266458Sdfr
13366458Sdfr	if (S_ISBLK(mode))
13466458Sdfr		return ("block device");
13566458Sdfr	else if (S_ISCHR(mode))
13666458Sdfr		return ("character device");
13766458Sdfr	else if (S_ISDIR(mode))
13866458Sdfr		return ("directory");
13966458Sdfr	else if (S_ISFIFO(mode))
14066458Sdfr		return ("pipe or FIFO");
14166458Sdfr	else if (S_ISLNK(mode))
14266458Sdfr		return ("symbolic link");
14366458Sdfr	else if (S_ISREG(mode))
14466458Sdfr		return ("regular file");
14566458Sdfr	else if (S_ISSOCK(mode))
14666458Sdfr		return ("socket");
14766458Sdfr	else if (S_ISWHT(mode))
14866458Sdfr		return ("whiteout");
14966458Sdfr	else
15066458Sdfr		return ("unknown");
15166458Sdfr}
15266458Sdfr
15366458Sdfrvoid
15466458Sdfrdescriptors_assert(const struct hast_resource *res, int pjdlogmode)
15566458Sdfr{
15666458Sdfr	char msg[256];
15766458Sdfr	struct stat sb;
15866458Sdfr	long maxfd;
15966458Sdfr	bool isopen;
16066458Sdfr	mode_t mode;
16166458Sdfr	int fd;
16266458Sdfr
16366458Sdfr	/*
16466458Sdfr	 * At this point descriptor to syslog socket is closed, so if we want
16566458Sdfr	 * to log assertion message, we have to first store it in 'msg' local
16666458Sdfr	 * buffer and then open syslog socket and log it.
16766458Sdfr	 */
16866458Sdfr	msg[0] = '\0';
16966458Sdfr
17066458Sdfr	maxfd = sysconf(_SC_OPEN_MAX);
17166458Sdfr	if (maxfd < 0) {
17266458Sdfr		pjdlog_init(pjdlogmode);
17366458Sdfr		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
17466458Sdfr		    role2str(res->hr_role));
17566458Sdfr		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
17666458Sdfr		pjdlog_fini();
17766458Sdfr		maxfd = 16384;
17866458Sdfr	}
17966458Sdfr	for (fd = 0; fd <= maxfd; fd++) {
18066458Sdfr		if (fstat(fd, &sb) == 0) {
18166458Sdfr			isopen = true;
18266458Sdfr			mode = sb.st_mode;
18366458Sdfr		} else if (errno == EBADF) {
18466458Sdfr			isopen = false;
18566458Sdfr			mode = 0;
18666458Sdfr		} else {
18766458Sdfr			(void)snprintf(msg, sizeof(msg),
18866458Sdfr			    "Unable to fstat descriptor %d: %s", fd,
18966458Sdfr			    strerror(errno));
19066458Sdfr			break;
19166458Sdfr		}
19266458Sdfr		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
19366458Sdfr		    fd == STDERR_FILENO) {
19466458Sdfr			if (!isopen) {
19566458Sdfr				(void)snprintf(msg, sizeof(msg),
19666458Sdfr				    "Descriptor %d (%s) is closed, but should be open.",
19766458Sdfr				    fd, (fd == STDIN_FILENO ? "stdin" :
19866458Sdfr				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
19966458Sdfr				break;
20066458Sdfr			}
20166458Sdfr		} else if (fd == proto_descriptor(res->hr_event)) {
20266458Sdfr			if (!isopen) {
20366458Sdfr				(void)snprintf(msg, sizeof(msg),
20466458Sdfr				    "Descriptor %d (event) is closed, but should be open.",
20566458Sdfr				    fd);
20666458Sdfr				break;
20766458Sdfr			}
20866458Sdfr			if (!S_ISSOCK(mode)) {
20966458Sdfr				(void)snprintf(msg, sizeof(msg),
21066458Sdfr				    "Descriptor %d (event) is %s, but should be %s.",
21166458Sdfr				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
21292676Speter				break;
21366458Sdfr			}
21492676Speter		} else if (fd == proto_descriptor(res->hr_ctrl)) {
21566458Sdfr			if (!isopen) {
21666458Sdfr				(void)snprintf(msg, sizeof(msg),
21766458Sdfr				    "Descriptor %d (ctrl) is closed, but should be open.",
21866458Sdfr				    fd);
21966458Sdfr				break;
22066458Sdfr			}
22166458Sdfr			if (!S_ISSOCK(mode)) {
22266458Sdfr				(void)snprintf(msg, sizeof(msg),
22366458Sdfr				    "Descriptor %d (ctrl) is %s, but should be %s.",
22466458Sdfr				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
22566458Sdfr				break;
22695710Speter			}
22766458Sdfr		} else if (res->hr_role == HAST_ROLE_PRIMARY &&
22866458Sdfr		    fd == proto_descriptor(res->hr_conn)) {
22966458Sdfr			if (!isopen) {
23066458Sdfr				(void)snprintf(msg, sizeof(msg),
23166458Sdfr				    "Descriptor %d (conn) is closed, but should be open.",
23266458Sdfr				    fd);
23366458Sdfr				break;
23466458Sdfr			}
23566458Sdfr			if (!S_ISSOCK(mode)) {
23666458Sdfr				(void)snprintf(msg, sizeof(msg),
23766458Sdfr				    "Descriptor %d (conn) is %s, but should be %s.",
23866458Sdfr				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
23966458Sdfr				break;
24066458Sdfr			}
24166458Sdfr		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
24266458Sdfr		    res->hr_conn != NULL &&
24366458Sdfr		    fd == proto_descriptor(res->hr_conn)) {
24466458Sdfr			if (isopen) {
24566458Sdfr				(void)snprintf(msg, sizeof(msg),
24666458Sdfr				    "Descriptor %d (conn) is open, but should be closed.",
24766458Sdfr				    fd);
24866458Sdfr				break;
24966458Sdfr			}
25066458Sdfr		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
25166458Sdfr		    fd == proto_descriptor(res->hr_remotein)) {
25266458Sdfr			if (!isopen) {
25366458Sdfr				(void)snprintf(msg, sizeof(msg),
25466458Sdfr				    "Descriptor %d (remote in) is closed, but should be open.",
25566458Sdfr				    fd);
25666458Sdfr				break;
25766458Sdfr			}
25866458Sdfr			if (!S_ISSOCK(mode)) {
25966458Sdfr				(void)snprintf(msg, sizeof(msg),
26066458Sdfr				    "Descriptor %d (remote in) is %s, but should be %s.",
26166458Sdfr				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
26266458Sdfr				break;
26366458Sdfr			}
26466458Sdfr		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
26566458Sdfr		    fd == proto_descriptor(res->hr_remoteout)) {
26666458Sdfr			if (!isopen) {
26766458Sdfr				(void)snprintf(msg, sizeof(msg),
26866458Sdfr				    "Descriptor %d (remote out) is closed, but should be open.",
26966458Sdfr				    fd);
27066458Sdfr				break;
27166458Sdfr			}
27266458Sdfr			if (!S_ISSOCK(mode)) {
27366458Sdfr				(void)snprintf(msg, sizeof(msg),
27466458Sdfr				    "Descriptor %d (remote out) is %s, but should be %s.",
27566458Sdfr				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
27666458Sdfr				break;
27766458Sdfr			}
27866458Sdfr		} else {
27966458Sdfr			if (isopen) {
28066458Sdfr				(void)snprintf(msg, sizeof(msg),
28166458Sdfr				    "Descriptor %d is open (%s), but should be closed.",
28266458Sdfr				    fd, dtype2str(mode));
28366458Sdfr				break;
28466458Sdfr			}
28566458Sdfr		}
28666458Sdfr	}
28766458Sdfr	if (msg[0] != '\0') {
28866458Sdfr		pjdlog_init(pjdlogmode);
28966458Sdfr		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
29066458Sdfr		    role2str(res->hr_role));
29166458Sdfr		PJDLOG_ABORT("%s", msg);
29266458Sdfr	}
29366458Sdfr}
29466458Sdfr
29566458Sdfrstatic void
29666458Sdfrchild_exit_log(unsigned int pid, int status)
29766458Sdfr{
29866458Sdfr
29966458Sdfr	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
30066458Sdfr		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
30166458Sdfr		    pid);
30266458Sdfr	} else if (WIFSIGNALED(status)) {
30366458Sdfr		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
30466458Sdfr		    pid, WTERMSIG(status));
30566458Sdfr	} else {
30666458Sdfr		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
30766458Sdfr		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
30866458Sdfr	}
30966458Sdfr}
31066458Sdfr
31166458Sdfrstatic void
31266458Sdfrchild_exit(void)
31366458Sdfr{
31466458Sdfr	struct hast_resource *res;
31566458Sdfr	int status;
31666458Sdfr	pid_t pid;
31766458Sdfr
31866458Sdfr	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
31966458Sdfr		/* Find resource related to the process that just exited. */
32066458Sdfr		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
32166458Sdfr			if (pid == res->hr_workerpid)
32266458Sdfr				break;
32366458Sdfr		}
32466458Sdfr		if (res == NULL) {
32566458Sdfr			/*
32666458Sdfr			 * This can happen when new connection arrives and we
32766458Sdfr			 * cancel child responsible for the old one or if this
32866458Sdfr			 * was hook which we executed.
32966458Sdfr			 */
33066458Sdfr			hook_check_one(pid, status);
33166458Sdfr			continue;
33266458Sdfr		}
33366458Sdfr		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
334171312Smarcel		    role2str(res->hr_role));
335135262Sphk		child_exit_log(pid, status);
33666458Sdfr		child_cleanup(res);
33766458Sdfr		if (res->hr_role == HAST_ROLE_PRIMARY) {
33866458Sdfr			/*
33966458Sdfr			 * Restart child process if it was killed by signal
34066458Sdfr			 * or exited because of temporary problem.
34166458Sdfr			 */
34266458Sdfr			if (WIFSIGNALED(status) ||
34366458Sdfr			    (WIFEXITED(status) &&
34466458Sdfr			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
34566458Sdfr				sleep(1);
34666458Sdfr				pjdlog_info("Restarting worker process.");
34766458Sdfr				hastd_primary(res);
34866458Sdfr			} else {
34966458Sdfr				res->hr_role = HAST_ROLE_INIT;
35066458Sdfr				pjdlog_info("Changing resource role back to %s.",
35166458Sdfr				    role2str(res->hr_role));
35266458Sdfr			}
35366458Sdfr		}
35466458Sdfr		pjdlog_prefix_set("%s", "");
35566458Sdfr	}
35666458Sdfr}
35766458Sdfr
35866458Sdfrstatic bool
35966458Sdfrresource_needs_restart(const struct hast_resource *res0,
36066458Sdfr    const struct hast_resource *res1)
36166458Sdfr{
36266458Sdfr
36366458Sdfr	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
36466458Sdfr
36566458Sdfr	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
36666458Sdfr		return (true);
36766458Sdfr	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
36866458Sdfr		return (true);
36966458Sdfr	if (res0->hr_role == HAST_ROLE_INIT ||
37066458Sdfr	    res0->hr_role == HAST_ROLE_SECONDARY) {
37166458Sdfr		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
37266458Sdfr			return (true);
37366458Sdfr		if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
37466458Sdfr			return (true);
37566458Sdfr		if (res0->hr_replication != res1->hr_replication)
37666458Sdfr			return (true);
37766458Sdfr		if (res0->hr_checksum != res1->hr_checksum)
37866458Sdfr			return (true);
37966458Sdfr		if (res0->hr_compression != res1->hr_compression)
38066458Sdfr			return (true);
38166458Sdfr		if (res0->hr_timeout != res1->hr_timeout)
38266458Sdfr			return (true);
38366458Sdfr		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
38466458Sdfr			return (true);
38566458Sdfr	}
38666458Sdfr	return (false);
38766458Sdfr}
38866458Sdfr
38966458Sdfrstatic bool
39066458Sdfrresource_needs_reload(const struct hast_resource *res0,
39166458Sdfr    const struct hast_resource *res1)
39266458Sdfr{
39366458Sdfr
39466458Sdfr	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
39566458Sdfr	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
39666458Sdfr	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
39766458Sdfr
39866458Sdfr	if (res0->hr_role != HAST_ROLE_PRIMARY)
39966458Sdfr		return (false);
40066458Sdfr
40166458Sdfr	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
40266458Sdfr		return (true);
40366458Sdfr	if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
40466458Sdfr		return (true);
40566458Sdfr	if (res0->hr_replication != res1->hr_replication)
40666458Sdfr		return (true);
40766458Sdfr	if (res0->hr_checksum != res1->hr_checksum)
40866458Sdfr		return (true);
40966458Sdfr	if (res0->hr_compression != res1->hr_compression)
41066458Sdfr		return (true);
41166458Sdfr	if (res0->hr_timeout != res1->hr_timeout)
41266458Sdfr		return (true);
41366458Sdfr	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
41466458Sdfr		return (true);
41566458Sdfr	return (false);
41666458Sdfr}
41766458Sdfr
41866458Sdfrstatic void
41966458Sdfrresource_reload(const struct hast_resource *res)
42066458Sdfr{
42166458Sdfr	struct nv *nvin, *nvout;
42266458Sdfr	int error;
42366458Sdfr
42466458Sdfr	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
42566458Sdfr
42666458Sdfr	nvout = nv_alloc();
42766458Sdfr	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
42866458Sdfr	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
42966458Sdfr	nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
43066458Sdfr	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
43166458Sdfr	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
43266458Sdfr	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
43366458Sdfr	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
43466458Sdfr	nv_add_string(nvout, res->hr_exec, "exec");
43566458Sdfr	if (nv_error(nvout) != 0) {
43666458Sdfr		nv_free(nvout);
43766458Sdfr		pjdlog_error("Unable to allocate header for reload message.");
43866458Sdfr		return;
43966458Sdfr	}
44066458Sdfr	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
44166458Sdfr		pjdlog_errno(LOG_ERR, "Unable to send reload message");
44266458Sdfr		nv_free(nvout);
44366458Sdfr		return;
44466458Sdfr	}
44566458Sdfr	nv_free(nvout);
44666458Sdfr
44766458Sdfr	/* Receive response. */
44866458Sdfr	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
44966458Sdfr		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
45066458Sdfr		return;
45166458Sdfr	}
45266458Sdfr	error = nv_get_int16(nvin, "error");
45366458Sdfr	nv_free(nvin);
45466458Sdfr	if (error != 0) {
45566458Sdfr		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
45666458Sdfr		return;
45766458Sdfr	}
45866458Sdfr}
45966458Sdfr
46066458Sdfrstatic void
46166458Sdfrhastd_reload(void)
46266458Sdfr{
46366458Sdfr	struct hastd_config *newcfg;
46466458Sdfr	struct hast_resource *nres, *cres, *tres;
46566458Sdfr	uint8_t role;
46666458Sdfr
46766458Sdfr	pjdlog_info("Reloading configuration...");
46866458Sdfr
46966458Sdfr	newcfg = yy_config_parse(cfgpath, false);
47066458Sdfr	if (newcfg == NULL)
47166458Sdfr		goto failed;
47266458Sdfr
47366458Sdfr	/*
47466458Sdfr	 * Check if control address has changed.
475141391Sphk	 */
476141391Sphk	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
477141391Sphk		if (proto_server(newcfg->hc_controladdr,
478141391Sphk		    &newcfg->hc_controlconn) < 0) {
479141391Sphk			pjdlog_errno(LOG_ERR,
480141391Sphk			    "Unable to listen on control address %s",
481141391Sphk			    newcfg->hc_controladdr);
482141391Sphk			goto failed;
483141391Sphk		}
484141391Sphk	}
485141391Sphk	/*
486141391Sphk	 * Check if listen address has changed.
487141391Sphk	 */
48866458Sdfr	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
48966458Sdfr		if (proto_server(newcfg->hc_listenaddr,
49066458Sdfr		    &newcfg->hc_listenconn) < 0) {
49166458Sdfr			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
49266458Sdfr			    newcfg->hc_listenaddr);
49366458Sdfr			goto failed;
49466458Sdfr		}
49566458Sdfr	}
49666458Sdfr	/*
49766458Sdfr	 * Only when both control and listen sockets are successfully
49866458Sdfr	 * initialized switch them to new configuration.
49966458Sdfr	 */
50066458Sdfr	if (newcfg->hc_controlconn != NULL) {
50166458Sdfr		pjdlog_info("Control socket changed from %s to %s.",
50266458Sdfr		    cfg->hc_controladdr, newcfg->hc_controladdr);
50366458Sdfr		proto_close(cfg->hc_controlconn);
50466458Sdfr		cfg->hc_controlconn = newcfg->hc_controlconn;
50566458Sdfr		newcfg->hc_controlconn = NULL;
50666458Sdfr		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
50766458Sdfr		    sizeof(cfg->hc_controladdr));
50866458Sdfr	}
509	if (newcfg->hc_listenconn != NULL) {
510		pjdlog_info("Listen socket changed from %s to %s.",
511		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
512		proto_close(cfg->hc_listenconn);
513		cfg->hc_listenconn = newcfg->hc_listenconn;
514		newcfg->hc_listenconn = NULL;
515		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
516		    sizeof(cfg->hc_listenaddr));
517	}
518
519	/*
520	 * Stop and remove resources that were removed from the configuration.
521	 */
522	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
523		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
524			if (strcmp(cres->hr_name, nres->hr_name) == 0)
525				break;
526		}
527		if (nres == NULL) {
528			control_set_role(cres, HAST_ROLE_INIT);
529			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
530			pjdlog_info("Resource %s removed.", cres->hr_name);
531			free(cres);
532		}
533	}
534	/*
535	 * Move new resources to the current configuration.
536	 */
537	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
538		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
539			if (strcmp(cres->hr_name, nres->hr_name) == 0)
540				break;
541		}
542		if (cres == NULL) {
543			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
544			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
545			pjdlog_info("Resource %s added.", nres->hr_name);
546		}
547	}
548	/*
549	 * Deal with modified resources.
550	 * Depending on what has changed exactly we might want to perform
551	 * different actions.
552	 *
553	 * We do full resource restart in the following situations:
554	 * Resource role is INIT or SECONDARY.
555	 * Resource role is PRIMARY and path to local component or provider
556	 * name has changed.
557	 * In case of PRIMARY, the worker process will be killed and restarted,
558	 * which also means removing /dev/hast/<name> provider and
559	 * recreating it.
560	 *
561	 * We do just reload (send SIGHUP to worker process) if we act as
562	 * PRIMARY, but only if remote address, replication mode, timeout or
563	 * execution path has changed. For those, there is no need to restart
564	 * worker process.
565	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
566	 * replication mode has changed or simply set new timeout if only
567	 * timeout has changed.
568	 */
569	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
570		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
571			if (strcmp(cres->hr_name, nres->hr_name) == 0)
572				break;
573		}
574		PJDLOG_ASSERT(cres != NULL);
575		if (resource_needs_restart(cres, nres)) {
576			pjdlog_info("Resource %s configuration was modified, restarting it.",
577			    cres->hr_name);
578			role = cres->hr_role;
579			control_set_role(cres, HAST_ROLE_INIT);
580			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
581			free(cres);
582			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
583			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
584			control_set_role(nres, role);
585		} else if (resource_needs_reload(cres, nres)) {
586			pjdlog_info("Resource %s configuration was modified, reloading it.",
587			    cres->hr_name);
588			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
589			    sizeof(cres->hr_remoteaddr));
590			strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
591			    sizeof(cres->hr_sourceaddr));
592			cres->hr_replication = nres->hr_replication;
593			cres->hr_checksum = nres->hr_checksum;
594			cres->hr_compression = nres->hr_compression;
595			cres->hr_timeout = nres->hr_timeout;
596			strlcpy(cres->hr_exec, nres->hr_exec,
597			    sizeof(cres->hr_exec));
598			if (cres->hr_workerpid != 0)
599				resource_reload(cres);
600		}
601	}
602
603	yy_config_free(newcfg);
604	pjdlog_info("Configuration reloaded successfully.");
605	return;
606failed:
607	if (newcfg != NULL) {
608		if (newcfg->hc_controlconn != NULL)
609			proto_close(newcfg->hc_controlconn);
610		if (newcfg->hc_listenconn != NULL)
611			proto_close(newcfg->hc_listenconn);
612		yy_config_free(newcfg);
613	}
614	pjdlog_warning("Configuration not reloaded.");
615}
616
617static void
618terminate_workers(void)
619{
620	struct hast_resource *res;
621
622	pjdlog_info("Termination signal received, exiting.");
623	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
624		if (res->hr_workerpid == 0)
625			continue;
626		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
627		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
628		if (kill(res->hr_workerpid, SIGTERM) == 0)
629			continue;
630		pjdlog_errno(LOG_WARNING,
631		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
632		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
633	}
634}
635
636static void
637listen_accept(void)
638{
639	struct hast_resource *res;
640	struct proto_conn *conn;
641	struct nv *nvin, *nvout, *nverr;
642	const char *resname;
643	const unsigned char *token;
644	char laddr[256], raddr[256];
645	size_t size;
646	pid_t pid;
647	int status;
648
649	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
650	pjdlog_debug(1, "Accepting connection to %s.", laddr);
651
652	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
653		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
654		return;
655	}
656
657	proto_local_address(conn, laddr, sizeof(laddr));
658	proto_remote_address(conn, raddr, sizeof(raddr));
659	pjdlog_info("Connection from %s to %s.", raddr, laddr);
660
661	/* Error in setting timeout is not critical, but why should it fail? */
662	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
663		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
664
665	nvin = nvout = nverr = NULL;
666
667	/*
668	 * Before receiving any data see if remote host have access to any
669	 * resource.
670	 */
671	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
672		if (proto_address_match(conn, res->hr_remoteaddr))
673			break;
674	}
675	if (res == NULL) {
676		pjdlog_error("Client %s isn't known.", raddr);
677		goto close;
678	}
679	/* Ok, remote host can access at least one resource. */
680
681	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
682		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
683		    raddr);
684		goto close;
685	}
686
687	resname = nv_get_string(nvin, "resource");
688	if (resname == NULL) {
689		pjdlog_error("No 'resource' field in the header received from %s.",
690		    raddr);
691		goto close;
692	}
693	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
694	token = nv_get_uint8_array(nvin, &size, "token");
695	/*
696	 * NULL token means that this is first conection.
697	 */
698	if (token != NULL && size != sizeof(res->hr_token)) {
699		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
700		    raddr, sizeof(res->hr_token), size);
701		goto close;
702	}
703
704	/*
705	 * From now on we want to send errors to the remote node.
706	 */
707	nverr = nv_alloc();
708
709	/* Find resource related to this connection. */
710	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
711		if (strcmp(resname, res->hr_name) == 0)
712			break;
713	}
714	/* Have we found the resource? */
715	if (res == NULL) {
716		pjdlog_error("No resource '%s' as requested by %s.",
717		    resname, raddr);
718		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
719		goto fail;
720	}
721
722	/* Now that we know resource name setup log prefix. */
723	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
724
725	/* Does the remote host have access to this resource? */
726	if (!proto_address_match(conn, res->hr_remoteaddr)) {
727		pjdlog_error("Client %s has no access to the resource.", raddr);
728		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
729		goto fail;
730	}
731	/* Is the resource marked as secondary? */
732	if (res->hr_role != HAST_ROLE_SECONDARY) {
733		pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
734		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
735		    raddr);
736		nv_add_stringf(nverr, "errmsg",
737		    "Remote node acts as %s for the resource and not as %s.",
738		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
739		if (res->hr_role == HAST_ROLE_PRIMARY) {
740			/*
741			 * If we act as primary request the other side to wait
742			 * for us a bit, as we might be finishing cleanups.
743			 */
744			nv_add_uint8(nverr, 1, "wait");
745		}
746		goto fail;
747	}
748	/* Does token (if exists) match? */
749	if (token != NULL && memcmp(token, res->hr_token,
750	    sizeof(res->hr_token)) != 0) {
751		pjdlog_error("Token received from %s doesn't match.", raddr);
752		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
753		goto fail;
754	}
755	/*
756	 * If there is no token, but we have half-open connection
757	 * (only remotein) or full connection (worker process is running)
758	 * we have to cancel those and accept the new connection.
759	 */
760	if (token == NULL) {
761		PJDLOG_ASSERT(res->hr_remoteout == NULL);
762		pjdlog_debug(1, "Initial connection from %s.", raddr);
763		if (res->hr_workerpid != 0) {
764			PJDLOG_ASSERT(res->hr_remotein == NULL);
765			pjdlog_debug(1,
766			    "Worker process exists (pid=%u), stopping it.",
767			    (unsigned int)res->hr_workerpid);
768			/* Stop child process. */
769			if (kill(res->hr_workerpid, SIGINT) < 0) {
770				pjdlog_errno(LOG_ERR,
771				    "Unable to stop worker process (pid=%u)",
772				    (unsigned int)res->hr_workerpid);
773				/*
774				 * Other than logging the problem we
775				 * ignore it - nothing smart to do.
776				 */
777			}
778			/* Wait for it to exit. */
779			else if ((pid = waitpid(res->hr_workerpid,
780			    &status, 0)) != res->hr_workerpid) {
781				/* We can only log the problem. */
782				pjdlog_errno(LOG_ERR,
783				    "Waiting for worker process (pid=%u) failed",
784				    (unsigned int)res->hr_workerpid);
785			} else {
786				child_exit_log(res->hr_workerpid, status);
787			}
788			child_cleanup(res);
789		} else if (res->hr_remotein != NULL) {
790			char oaddr[256];
791
792			proto_remote_address(res->hr_remotein, oaddr,
793			    sizeof(oaddr));
794			pjdlog_debug(1,
795			    "Canceling half-open connection from %s on connection from %s.",
796			    oaddr, raddr);
797			proto_close(res->hr_remotein);
798			res->hr_remotein = NULL;
799		}
800	}
801
802	/*
803	 * Checks and cleanups are done.
804	 */
805
806	if (token == NULL) {
807		arc4random_buf(res->hr_token, sizeof(res->hr_token));
808		nvout = nv_alloc();
809		nv_add_uint8_array(nvout, res->hr_token,
810		    sizeof(res->hr_token), "token");
811		if (nv_error(nvout) != 0) {
812			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
813			    "Unable to prepare return header for %s", raddr);
814			nv_add_stringf(nverr, "errmsg",
815			    "Remote node was unable to prepare return header: %s.",
816			    strerror(nv_error(nvout)));
817			goto fail;
818		}
819		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
820			int error = errno;
821
822			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
823			    raddr);
824			nv_add_stringf(nverr, "errmsg",
825			    "Remote node was unable to send response: %s.",
826			    strerror(error));
827			goto fail;
828		}
829		res->hr_remotein = conn;
830		pjdlog_debug(1, "Incoming connection from %s configured.",
831		    raddr);
832	} else {
833		res->hr_remoteout = conn;
834		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
835		hastd_secondary(res, nvin);
836	}
837	nv_free(nvin);
838	nv_free(nvout);
839	nv_free(nverr);
840	pjdlog_prefix_set("%s", "");
841	return;
842fail:
843	if (nv_error(nverr) != 0) {
844		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
845		    "Unable to prepare error header for %s", raddr);
846		goto close;
847	}
848	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
849		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
850		goto close;
851	}
852close:
853	if (nvin != NULL)
854		nv_free(nvin);
855	if (nvout != NULL)
856		nv_free(nvout);
857	if (nverr != NULL)
858		nv_free(nverr);
859	proto_close(conn);
860	pjdlog_prefix_set("%s", "");
861}
862
863static void
864connection_migrate(struct hast_resource *res)
865{
866	struct proto_conn *conn;
867	int16_t val = 0;
868
869	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
870
871	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
872
873	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
874		pjdlog_errno(LOG_WARNING,
875		    "Unable to receive connection command");
876		return;
877	}
878	if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
879	    res->hr_remoteaddr, &conn) < 0) {
880		val = errno;
881		pjdlog_errno(LOG_WARNING,
882		    "Unable to create outgoing connection to %s",
883		    res->hr_remoteaddr);
884		goto out;
885	}
886	if (proto_connect(conn, -1) < 0) {
887		val = errno;
888		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
889		    res->hr_remoteaddr);
890		proto_close(conn);
891		goto out;
892	}
893	val = 0;
894out:
895	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
896		pjdlog_errno(LOG_WARNING,
897		    "Unable to send reply to connection request");
898	}
899	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
900		pjdlog_errno(LOG_WARNING, "Unable to send connection");
901
902	pjdlog_prefix_set("%s", "");
903}
904
905static void
906check_signals(void)
907{
908	struct timespec sigtimeout;
909	sigset_t mask;
910	int signo;
911
912	sigtimeout.tv_sec = 0;
913	sigtimeout.tv_nsec = 0;
914
915	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
916	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
917	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
918	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
919	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
920
921	while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
922		switch (signo) {
923		case SIGINT:
924		case SIGTERM:
925			sigexit_received = true;
926			terminate_workers();
927			proto_close(cfg->hc_controlconn);
928			exit(EX_OK);
929			break;
930		case SIGCHLD:
931			child_exit();
932			break;
933		case SIGHUP:
934			hastd_reload();
935			break;
936		default:
937			PJDLOG_ABORT("Unexpected signal (%d).", signo);
938		}
939	}
940}
941
942static void
943main_loop(void)
944{
945	struct hast_resource *res;
946	struct timeval seltimeout;
947	int fd, maxfd, ret;
948	time_t lastcheck, now;
949	fd_set rfds;
950
951	lastcheck = time(NULL);
952	seltimeout.tv_sec = REPORT_INTERVAL;
953	seltimeout.tv_usec = 0;
954
955	pjdlog_info("Started successfully, running protocol version %d.",
956	    HAST_PROTO_VERSION);
957
958	for (;;) {
959		check_signals();
960
961		/* Setup descriptors for select(2). */
962		FD_ZERO(&rfds);
963		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
964		PJDLOG_ASSERT(fd >= 0);
965		FD_SET(fd, &rfds);
966		fd = proto_descriptor(cfg->hc_listenconn);
967		PJDLOG_ASSERT(fd >= 0);
968		FD_SET(fd, &rfds);
969		maxfd = fd > maxfd ? fd : maxfd;
970		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
971			if (res->hr_event == NULL)
972				continue;
973			fd = proto_descriptor(res->hr_event);
974			PJDLOG_ASSERT(fd >= 0);
975			FD_SET(fd, &rfds);
976			maxfd = fd > maxfd ? fd : maxfd;
977			if (res->hr_role == HAST_ROLE_PRIMARY) {
978				/* Only primary workers asks for connections. */
979				PJDLOG_ASSERT(res->hr_conn != NULL);
980				fd = proto_descriptor(res->hr_conn);
981				PJDLOG_ASSERT(fd >= 0);
982				FD_SET(fd, &rfds);
983				maxfd = fd > maxfd ? fd : maxfd;
984			} else {
985				PJDLOG_ASSERT(res->hr_conn == NULL);
986			}
987		}
988
989		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
990		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
991		now = time(NULL);
992		if (lastcheck + REPORT_INTERVAL <= now) {
993			hook_check();
994			lastcheck = now;
995		}
996		if (ret == 0) {
997			/*
998			 * select(2) timed out, so there should be no
999			 * descriptors to check.
1000			 */
1001			continue;
1002		} else if (ret == -1) {
1003			if (errno == EINTR)
1004				continue;
1005			KEEP_ERRNO((void)pidfile_remove(pfh));
1006			pjdlog_exit(EX_OSERR, "select() failed");
1007		}
1008
1009		/*
1010		 * Check for signals before we do anything to update our
1011		 * info about terminated workers in the meantime.
1012		 */
1013		check_signals();
1014
1015		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1016			control_handle(cfg);
1017		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
1018			listen_accept();
1019		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1020			if (res->hr_event == NULL)
1021				continue;
1022			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1023				if (event_recv(res) == 0)
1024					continue;
1025				/* The worker process exited? */
1026				proto_close(res->hr_event);
1027				res->hr_event = NULL;
1028				if (res->hr_conn != NULL) {
1029					proto_close(res->hr_conn);
1030					res->hr_conn = NULL;
1031				}
1032				continue;
1033			}
1034			if (res->hr_role == HAST_ROLE_PRIMARY) {
1035				PJDLOG_ASSERT(res->hr_conn != NULL);
1036				if (FD_ISSET(proto_descriptor(res->hr_conn),
1037				    &rfds)) {
1038					connection_migrate(res);
1039				}
1040			} else {
1041				PJDLOG_ASSERT(res->hr_conn == NULL);
1042			}
1043		}
1044	}
1045}
1046
1047static void
1048dummy_sighandler(int sig __unused)
1049{
1050	/* Nothing to do. */
1051}
1052
1053int
1054main(int argc, char *argv[])
1055{
1056	const char *pidfile;
1057	pid_t otherpid;
1058	bool foreground;
1059	int debuglevel;
1060	sigset_t mask;
1061
1062	foreground = false;
1063	debuglevel = 0;
1064	pidfile = HASTD_PIDFILE;
1065
1066	for (;;) {
1067		int ch;
1068
1069		ch = getopt(argc, argv, "c:dFhP:");
1070		if (ch == -1)
1071			break;
1072		switch (ch) {
1073		case 'c':
1074			cfgpath = optarg;
1075			break;
1076		case 'd':
1077			debuglevel++;
1078			break;
1079		case 'F':
1080			foreground = true;
1081			break;
1082		case 'P':
1083			pidfile = optarg;
1084			break;
1085		case 'h':
1086		default:
1087			usage();
1088		}
1089	}
1090	argc -= optind;
1091	argv += optind;
1092
1093	pjdlog_init(PJDLOG_MODE_STD);
1094	pjdlog_debug_set(debuglevel);
1095
1096	g_gate_load();
1097
1098	pfh = pidfile_open(pidfile, 0600, &otherpid);
1099	if (pfh == NULL) {
1100		if (errno == EEXIST) {
1101			pjdlog_exitx(EX_TEMPFAIL,
1102			    "Another hastd is already running, pid: %jd.",
1103			    (intmax_t)otherpid);
1104		}
1105		/* If we cannot create pidfile from other reasons, only warn. */
1106		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1107	}
1108
1109	cfg = yy_config_parse(cfgpath, true);
1110	PJDLOG_ASSERT(cfg != NULL);
1111
1112	/*
1113	 * Restore default actions for interesting signals in case parent
1114	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1115	 */
1116	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1117	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1118	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1119	/*
1120	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1121	 * so we can mask it.
1122	 */
1123	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1124
1125	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1126	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1127	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1128	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1129	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1130	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1131
1132	/* Listen on control address. */
1133	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1134		KEEP_ERRNO((void)pidfile_remove(pfh));
1135		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1136		    cfg->hc_controladdr);
1137	}
1138	/* Listen for remote connections. */
1139	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1140		KEEP_ERRNO((void)pidfile_remove(pfh));
1141		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1142		    cfg->hc_listenaddr);
1143	}
1144
1145	if (!foreground) {
1146		if (daemon(0, 0) < 0) {
1147			KEEP_ERRNO((void)pidfile_remove(pfh));
1148			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1149		}
1150
1151		/* Start logging to syslog. */
1152		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1153
1154		/* Write PID to a file. */
1155		if (pidfile_write(pfh) < 0) {
1156			pjdlog_errno(LOG_WARNING,
1157			    "Unable to write PID to a file");
1158		}
1159	}
1160
1161	hook_init();
1162
1163	main_loop();
1164
1165	exit(0);
1166}
1167