hastd.c revision 218373
1132718Skan/*-
272562Sobrien * Copyright (c) 2009-2010 The FreeBSD Foundation
3169689Skan * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4169689Skan * All rights reserved.
550397Sobrien *
6132718Skan * This software was developed by Pawel Jakub Dawidek under sponsorship from
750397Sobrien * the FreeBSD Foundation.
850397Sobrien *
9132718Skan * Redistribution and use in source and binary forms, with or without
1050397Sobrien * modification, are permitted provided that the following conditions
11132718Skan * are met:
1250397Sobrien * 1. Redistributions of source code must retain the above copyright
1350397Sobrien *    notice, this list of conditions and the following disclaimer.
1450397Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1550397Sobrien *    notice, this list of conditions and the following disclaimer in the
16132718Skan *    documentation and/or other materials provided with the distribution.
1750397Sobrien *
1850397Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
1950397Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2050397Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2150397Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22132718Skan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23169689Skan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24169689Skan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2550397Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2650397Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2750397Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28132718Skan * SUCH DAMAGE.
29132718Skan */
3050397Sobrien
3150397Sobrien#include <sys/cdefs.h>
3250397Sobrien__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 218373 2011-02-06 14:06:37Z pjd $");
3350397Sobrien
3450397Sobrien#include <sys/param.h>
3550397Sobrien#include <sys/linker.h>
36169689Skan#include <sys/module.h>
3750397Sobrien#include <sys/stat.h>
3850397Sobrien#include <sys/wait.h>
3950397Sobrien
4050397Sobrien#include <err.h>
4190075Sobrien#include <errno.h>
4250397Sobrien#include <libutil.h>
4390075Sobrien#include <signal.h>
4450397Sobrien#include <stdbool.h>
4550397Sobrien#include <stdio.h>
4690075Sobrien#include <stdlib.h>
4790075Sobrien#include <string.h>
4890075Sobrien#include <sysexits.h>
4990075Sobrien#include <unistd.h>
5090075Sobrien
51132718Skan#include <activemap.h>
52169689Skan#include <pjdlog.h>
53169689Skan
5450397Sobrien#include "control.h"
55169689Skan#include "event.h"
56169689Skan#include "hast.h"
57169689Skan#include "hast_proto.h"
58169689Skan#include "hastd.h"
59169689Skan#include "hooks.h"
60169689Skan#include "subr.h"
61169689Skan
62169689Skan/* Path to configuration file. */
63169689Skanconst char *cfgpath = HAST_CONFIG;
64169689Skan/* Hastd configuration. */
65169689Skanstatic struct hastd_config *cfg;
66169689Skan/* Was SIGINT or SIGTERM signal received? */
67169689Skanbool sigexit_received = false;
68169689Skan/* PID file handle. */
69169689Skanstruct pidfh *pfh;
70169689Skan
71169689Skan/* How often check for hooks running for too long. */
72169689Skan#define	REPORT_INTERVAL	5
73169689Skan
74169689Skanstatic void
75169689Skanusage(void)
76169689Skan{
77169689Skan
78169689Skan	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
7950397Sobrien}
80169689Skan
81169689Skanstatic void
82169689Skang_gate_load(void)
83169689Skan{
84169689Skan
85169689Skan	if (modfind("g_gate") == -1) {
86169689Skan		/* Not present in kernel, try loading it. */
87169689Skan		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
88169689Skan			if (errno != EEXIST) {
89169689Skan				pjdlog_exit(EX_OSERR,
90169689Skan				    "Unable to load geom_gate module");
91169689Skan			}
92169689Skan		}
93169689Skan	}
94169689Skan}
95169689Skan
96169689Skanvoid
97169689Skandescriptors_cleanup(struct hast_resource *res)
98169689Skan{
99169689Skan	struct hast_resource *tres;
100169689Skan
101169689Skan	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
102169689Skan		if (tres == res) {
10350397Sobrien			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
104169689Skan			    (res->hr_remotein == NULL &&
105169689Skan			     res->hr_remoteout == NULL));
106169689Skan			continue;
107169689Skan		}
108169689Skan		if (tres->hr_remotein != NULL)
109169689Skan			proto_close(tres->hr_remotein);
110169689Skan		if (tres->hr_remoteout != NULL)
111169689Skan			proto_close(tres->hr_remoteout);
112169689Skan		if (tres->hr_ctrl != NULL)
113169689Skan			proto_close(tres->hr_ctrl);
114169689Skan		if (tres->hr_event != NULL)
115169689Skan			proto_close(tres->hr_event);
116169689Skan		if (tres->hr_conn != NULL)
117169689Skan			proto_close(tres->hr_conn);
118169689Skan	}
119169689Skan	if (cfg->hc_controlin != NULL)
120169689Skan		proto_close(cfg->hc_controlin);
121169689Skan	proto_close(cfg->hc_controlconn);
122169689Skan	proto_close(cfg->hc_listenconn);
123169689Skan	(void)pidfile_close(pfh);
124169689Skan	hook_fini();
125169689Skan	pjdlog_fini();
126169689Skan}
127169689Skan
128169689Skanstatic const char *
129169689Skandtype2str(mode_t mode)
130169689Skan{
131169689Skan
132169689Skan	if (S_ISBLK(mode))
133169689Skan		return ("block device");
134169689Skan	else if (S_ISCHR(mode))
135169689Skan		return ("character device");
136169689Skan	else if (S_ISDIR(mode))
137169689Skan		return ("directory");
138169689Skan	else if (S_ISFIFO(mode))
139169689Skan		return ("pipe or FIFO");
140169689Skan	else if (S_ISLNK(mode))
141169689Skan		return ("symbolic link");
142169689Skan	else if (S_ISREG(mode))
143169689Skan		return ("regular file");
144169689Skan	else if (S_ISSOCK(mode))
145169689Skan		return ("socket");
146169689Skan	else if (S_ISWHT(mode))
147169689Skan		return ("whiteout");
148169689Skan	else
149169689Skan		return ("unknown");
150169689Skan}
151169689Skan
152169689Skanvoid
153169689Skandescriptors_assert(const struct hast_resource *res, int pjdlogmode)
154169689Skan{
155169689Skan	char msg[256];
156169689Skan	struct stat sb;
157169689Skan	long maxfd;
158169689Skan	bool isopen;
159169689Skan	mode_t mode;
160169689Skan	int fd;
161169689Skan
162169689Skan	/*
163169689Skan	 * At this point descriptor to syslog socket is closed, so if we want
164169689Skan	 * to log assertion message, we have to first store it in 'msg' local
165169689Skan	 * buffer and then open syslog socket and log it.
166169689Skan	 */
167169689Skan	msg[0] = '\0';
168169689Skan
169169689Skan	maxfd = sysconf(_SC_OPEN_MAX);
170169689Skan	if (maxfd < 0) {
171169689Skan		pjdlog_init(pjdlogmode);
172169689Skan		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
173169689Skan		    role2str(res->hr_role));
174169689Skan		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
175169689Skan		pjdlog_fini();
176169689Skan		maxfd = 16384;
177169689Skan	}
178169689Skan	for (fd = 0; fd <= maxfd; fd++) {
179169689Skan		if (fstat(fd, &sb) == 0) {
180169689Skan			isopen = true;
181169689Skan			mode = sb.st_mode;
182169689Skan		} else if (errno == EBADF) {
183169689Skan			isopen = false;
184169689Skan			mode = 0;
185169689Skan		} else {
186169689Skan			isopen = true;	/* silence gcc */
187169689Skan			mode = 0;	/* silence gcc */
188169689Skan			snprintf(msg, sizeof(msg),
189169689Skan			    "Unable to fstat descriptor %d: %s", fd,
190169689Skan			    strerror(errno));
191169689Skan		}
192169689Skan		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
193169689Skan		    fd == STDERR_FILENO) {
194169689Skan			if (!isopen) {
195169689Skan				snprintf(msg, sizeof(msg),
196169689Skan				    "Descriptor %d (%s) is closed, but should be open.",
197169689Skan				    fd, (fd == STDIN_FILENO ? "stdin" :
198169689Skan				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
199169689Skan				break;
200169689Skan			}
201169689Skan		} else if (fd == proto_descriptor(res->hr_event)) {
202169689Skan			if (!isopen) {
203169689Skan				snprintf(msg, sizeof(msg),
204169689Skan				    "Descriptor %d (event) is closed, but should be open.",
205169689Skan				    fd);
206169689Skan				break;
207169689Skan			}
208169689Skan			if (!S_ISSOCK(mode)) {
209169689Skan				snprintf(msg, sizeof(msg),
210169689Skan				    "Descriptor %d (event) is %s, but should be %s.",
211169689Skan				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
212169689Skan				break;
213169689Skan			}
214169689Skan		} else if (fd == proto_descriptor(res->hr_ctrl)) {
215169689Skan			if (!isopen) {
216169689Skan				snprintf(msg, sizeof(msg),
217169689Skan				    "Descriptor %d (ctrl) is closed, but should be open.",
218169689Skan				    fd);
219169689Skan				break;
220169689Skan			}
221169689Skan			if (!S_ISSOCK(mode)) {
222169689Skan				snprintf(msg, sizeof(msg),
223169689Skan				    "Descriptor %d (ctrl) is %s, but should be %s.",
224169689Skan				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
225169689Skan				break;
226169689Skan			}
227169689Skan		} else if (fd == proto_descriptor(res->hr_conn)) {
228169689Skan			if (!isopen) {
229169689Skan				snprintf(msg, sizeof(msg),
230169689Skan				    "Descriptor %d (conn) is closed, but should be open.",
231169689Skan				    fd);
232169689Skan				break;
233169689Skan			}
234169689Skan			if (!S_ISSOCK(mode)) {
235169689Skan				snprintf(msg, sizeof(msg),
236169689Skan				    "Descriptor %d (conn) is %s, but should be %s.",
23750397Sobrien				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
23850397Sobrien				break;
23950397Sobrien			}
240169689Skan		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
241169689Skan		    fd == proto_descriptor(res->hr_remotein)) {
242169689Skan			if (!isopen) {
24350397Sobrien				snprintf(msg, sizeof(msg),
24450397Sobrien				    "Descriptor %d (remote in) is closed, but should be open.",
245132718Skan				    fd);
246132718Skan				break;
24750397Sobrien			}
24896263Sobrien			if (!S_ISSOCK(mode)) {
24996263Sobrien				snprintf(msg, sizeof(msg),
25090075Sobrien				    "Descriptor %d (remote in) is %s, but should be %s.",
25190075Sobrien				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
252169689Skan				break;
253169689Skan			}
254169689Skan		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
255169689Skan		    fd == proto_descriptor(res->hr_remoteout)) {
256169689Skan			if (!isopen) {
257169689Skan				snprintf(msg, sizeof(msg),
25850397Sobrien				    "Descriptor %d (remote out) is closed, but should be open.",
25950397Sobrien				    fd);
260169689Skan				break;
26150397Sobrien			}
26296263Sobrien			if (!S_ISSOCK(mode)) {
26396263Sobrien				snprintf(msg, sizeof(msg),
26496263Sobrien				    "Descriptor %d (remote out) is %s, but should be %s.",
26596263Sobrien				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
26650397Sobrien				break;
26750397Sobrien			}
26850397Sobrien		} else {
26950397Sobrien			if (isopen) {
27050397Sobrien				snprintf(msg, sizeof(msg),
27150397Sobrien				    "Descriptor %d is open (%s), but should be closed.",
27250397Sobrien				    fd, dtype2str(mode));
27350397Sobrien				break;
27450397Sobrien			}
27550397Sobrien		}
27650397Sobrien	}
27750397Sobrien	if (msg[0] != '\0') {
27850397Sobrien		pjdlog_init(pjdlogmode);
27950397Sobrien		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
28050397Sobrien		    role2str(res->hr_role));
28190075Sobrien		PJDLOG_ABORT("%s", msg);
28290075Sobrien	}
28390075Sobrien}
28490075Sobrien
28590075Sobrienstatic void
28690075Sobrienchild_exit_log(unsigned int pid, int status)
28790075Sobrien{
28890075Sobrien
28990075Sobrien	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
29090075Sobrien		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
29190075Sobrien		    pid);
29290075Sobrien	} else if (WIFSIGNALED(status)) {
29390075Sobrien		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
29490075Sobrien		    pid, WTERMSIG(status));
29590075Sobrien	} else {
29690075Sobrien		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
29790075Sobrien		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
29890075Sobrien	}
299132718Skan}
300132718Skan
301132718Skanstatic void
302132718Skanchild_exit(void)
303169689Skan{
304169689Skan	struct hast_resource *res;
305169689Skan	int status;
306169689Skan	pid_t pid;
307169689Skan
308169689Skan	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
309169689Skan		/* Find resource related to the process that just exited. */
310169689Skan		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
311169689Skan			if (pid == res->hr_workerpid)
312132718Skan				break;
313132718Skan		}
314169689Skan		if (res == NULL) {
315169689Skan			/*
31650397Sobrien			 * This can happen when new connection arrives and we
317169689Skan			 * cancel child responsible for the old one or if this
318169689Skan			 * was hook which we executed.
319169689Skan			 */
320169689Skan			hook_check_one(pid, status);
321169689Skan			continue;
322132718Skan		}
32350397Sobrien		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
324169689Skan		    role2str(res->hr_role));
325169689Skan		child_exit_log(pid, status);
326169689Skan		child_cleanup(res);
327169689Skan		if (res->hr_role == HAST_ROLE_PRIMARY) {
328132718Skan			/*
329132718Skan			 * Restart child process if it was killed by signal
330132718Skan			 * or exited because of temporary problem.
331132718Skan			 */
33250397Sobrien			if (WIFSIGNALED(status) ||
333132718Skan			    (WIFEXITED(status) &&
334132718Skan			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
33552284Sobrien				sleep(1);
336132718Skan				pjdlog_info("Restarting worker process.");
337132718Skan				hastd_primary(res);
338132718Skan			} else {
339169689Skan				res->hr_role = HAST_ROLE_INIT;
340132718Skan				pjdlog_info("Changing resource role back to %s.",
341132718Skan				    role2str(res->hr_role));
342132718Skan			}
343169689Skan		}
344169689Skan		pjdlog_prefix_set("%s", "");
345169689Skan	}
346169689Skan}
347169689Skan
348169689Skanstatic bool
34990075Sobrienresource_needs_restart(const struct hast_resource *res0,
350169689Skan    const struct hast_resource *res1)
35190075Sobrien{
35252284Sobrien
353132718Skan	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
354132718Skan
355132718Skan	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
356132718Skan		return (true);
35796263Sobrien	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
358132718Skan		return (true);
359132718Skan	if (res0->hr_role == HAST_ROLE_INIT ||
360132718Skan	    res0->hr_role == HAST_ROLE_SECONDARY) {
361132718Skan		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
362132718Skan			return (true);
363117395Skan		if (res0->hr_replication != res1->hr_replication)
364132718Skan			return (true);
365132718Skan		if (res0->hr_timeout != res1->hr_timeout)
366169689Skan			return (true);
367169689Skan		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
368169689Skan			return (true);
369169689Skan	}
370169689Skan	return (false);
371169689Skan}
372132718Skan
373132718Skanstatic bool
374146895Skanresource_needs_reload(const struct hast_resource *res0,
375146895Skan    const struct hast_resource *res1)
376132718Skan{
377132718Skan
378132718Skan	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
379132718Skan	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
380132718Skan	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
381132718Skan
382132718Skan	if (res0->hr_role != HAST_ROLE_PRIMARY)
383169689Skan		return (false);
384169689Skan
385169689Skan	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
386169689Skan		return (true);
387169689Skan	if (res0->hr_replication != res1->hr_replication)
388169689Skan		return (true);
389169689Skan	if (res0->hr_timeout != res1->hr_timeout)
390169689Skan		return (true);
391169689Skan	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
392169689Skan		return (true);
393169689Skan	return (false);
394169689Skan}
395169689Skan
396169689Skanstatic void
397169689Skanresource_reload(const struct hast_resource *res)
398169689Skan{
399169689Skan	struct nv *nvin, *nvout;
400169689Skan	int error;
401169689Skan
40250397Sobrien	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
40350397Sobrien
40450397Sobrien	nvout = nv_alloc();
40550397Sobrien	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
40650397Sobrien	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
40750397Sobrien	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
40890075Sobrien	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
40950397Sobrien	nv_add_string(nvout, res->hr_exec, "exec");
41050397Sobrien	if (nv_error(nvout) != 0) {
41150397Sobrien		nv_free(nvout);
41250397Sobrien		pjdlog_error("Unable to allocate header for reload message.");
41350397Sobrien		return;
41450397Sobrien	}
41550397Sobrien	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
41650397Sobrien		pjdlog_errno(LOG_ERR, "Unable to send reload message");
41750397Sobrien		nv_free(nvout);
41850397Sobrien		return;
41950397Sobrien	}
42050397Sobrien	nv_free(nvout);
421169689Skan
422169689Skan	/* Receive response. */
423169689Skan	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
424169689Skan		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
42590075Sobrien		return;
42650397Sobrien	}
42790075Sobrien	error = nv_get_int16(nvin, "error");
42890075Sobrien	nv_free(nvin);
42990075Sobrien	if (error != 0) {
43090075Sobrien		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
43190075Sobrien		return;
43290075Sobrien	}
43390075Sobrien}
43490075Sobrien
43590075Sobrienstatic void
43690075Sobrienhastd_reload(void)
43790075Sobrien{
43890075Sobrien	struct hastd_config *newcfg;
43990075Sobrien	struct hast_resource *nres, *cres, *tres;
44090075Sobrien	uint8_t role;
44190075Sobrien
44290075Sobrien	pjdlog_info("Reloading configuration...");
44390075Sobrien
44490075Sobrien	newcfg = yy_config_parse(cfgpath, false);
44590075Sobrien	if (newcfg == NULL)
44690075Sobrien		goto failed;
44790075Sobrien
448169689Skan	/*
44990075Sobrien	 * Check if control address has changed.
450169689Skan	 */
45190075Sobrien	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
45290075Sobrien		if (proto_server(newcfg->hc_controladdr,
45390075Sobrien		    &newcfg->hc_controlconn) < 0) {
45490075Sobrien			pjdlog_errno(LOG_ERR,
45590075Sobrien			    "Unable to listen on control address %s",
45690075Sobrien			    newcfg->hc_controladdr);
45790075Sobrien			goto failed;
458117395Skan		}
459117395Skan	}
46090075Sobrien	/*
461132718Skan	 * Check if listen address has changed.
462132718Skan	 */
463117395Skan	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
464132718Skan		if (proto_server(newcfg->hc_listenaddr,
465132718Skan		    &newcfg->hc_listenconn) < 0) {
466169689Skan			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
467169689Skan			    newcfg->hc_listenaddr);
468132718Skan			goto failed;
469169689Skan		}
470169689Skan	}
471169689Skan	/*
472169689Skan	 * Only when both control and listen sockets are successfully
473169689Skan	 * initialized switch them to new configuration.
474169689Skan	 */
475132718Skan	if (newcfg->hc_controlconn != NULL) {
476132718Skan		pjdlog_info("Control socket changed from %s to %s.",
477132718Skan		    cfg->hc_controladdr, newcfg->hc_controladdr);
478169689Skan		proto_close(cfg->hc_controlconn);
479132718Skan		cfg->hc_controlconn = newcfg->hc_controlconn;
480132718Skan		newcfg->hc_controlconn = NULL;
481132718Skan		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
482117395Skan		    sizeof(cfg->hc_controladdr));
483117395Skan	}
484117395Skan	if (newcfg->hc_listenconn != NULL) {
485146895Skan		pjdlog_info("Listen socket changed from %s to %s.",
486117395Skan		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
487132718Skan		proto_close(cfg->hc_listenconn);
488132718Skan		cfg->hc_listenconn = newcfg->hc_listenconn;
489132718Skan		newcfg->hc_listenconn = NULL;
490132718Skan		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
491132718Skan		    sizeof(cfg->hc_listenaddr));
492169689Skan	}
493169689Skan
494169689Skan	/*
495169689Skan	 * Stop and remove resources that were removed from the configuration.
496169689Skan	 */
497169689Skan	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
498169689Skan		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
499169689Skan			if (strcmp(cres->hr_name, nres->hr_name) == 0)
500169689Skan				break;
501169689Skan		}
502169689Skan		if (nres == NULL) {
503169689Skan			control_set_role(cres, HAST_ROLE_INIT);
504169689Skan			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
505169689Skan			pjdlog_info("Resource %s removed.", cres->hr_name);
506169689Skan			free(cres);
507169689Skan		}
508169689Skan	}
509169689Skan	/*
510169689Skan	 * Move new resources to the current configuration.
511169689Skan	 */
512169689Skan	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
513169689Skan		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
514169689Skan			if (strcmp(cres->hr_name, nres->hr_name) == 0)
515169689Skan				break;
516169689Skan		}
517169689Skan		if (cres == NULL) {
518169689Skan			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
519169689Skan			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
520169689Skan			pjdlog_info("Resource %s added.", nres->hr_name);
521169689Skan		}
522169689Skan	}
523169689Skan	/*
524169689Skan	 * Deal with modified resources.
525169689Skan	 * Depending on what has changed exactly we might want to perform
526169689Skan	 * different actions.
527169689Skan	 *
528169689Skan	 * We do full resource restart in the following situations:
529169689Skan	 * Resource role is INIT or SECONDARY.
530169689Skan	 * Resource role is PRIMARY and path to local component or provider
531169689Skan	 * name has changed.
532169689Skan	 * In case of PRIMARY, the worker process will be killed and restarted,
533169689Skan	 * which also means removing /dev/hast/<name> provider and
534169689Skan	 * recreating it.
535169689Skan	 *
536169689Skan	 * We do just reload (send SIGHUP to worker process) if we act as
537169689Skan	 * PRIMARY, but only if remote address, replication mode, timeout or
538169689Skan	 * execution path has changed. For those, there is no need to restart
539169689Skan	 * worker process.
540169689Skan	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
541169689Skan	 * replication mode has changed or simply set new timeout if only
542169689Skan	 * timeout has changed.
543169689Skan	 */
544169689Skan	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
545169689Skan		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
546169689Skan			if (strcmp(cres->hr_name, nres->hr_name) == 0)
547169689Skan				break;
548169689Skan		}
549169689Skan		PJDLOG_ASSERT(cres != NULL);
550169689Skan		if (resource_needs_restart(cres, nres)) {
551169689Skan			pjdlog_info("Resource %s configuration was modified, restarting it.",
552169689Skan			    cres->hr_name);
553169689Skan			role = cres->hr_role;
554169689Skan			control_set_role(cres, HAST_ROLE_INIT);
555169689Skan			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
556169689Skan			free(cres);
557169689Skan			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
558169689Skan			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
559169689Skan			control_set_role(nres, role);
560169689Skan		} else if (resource_needs_reload(cres, nres)) {
561169689Skan			pjdlog_info("Resource %s configuration was modified, reloading it.",
562169689Skan			    cres->hr_name);
56390075Sobrien			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
564169689Skan			    sizeof(cres->hr_remoteaddr));
565169689Skan			cres->hr_replication = nres->hr_replication;
566169689Skan			cres->hr_timeout = nres->hr_timeout;
567169689Skan			strlcpy(cres->hr_exec, nres->hr_exec,
568169689Skan			    sizeof(cres->hr_exec));
569169689Skan			if (cres->hr_workerpid != 0)
570169689Skan				resource_reload(cres);
571169689Skan		}
572169689Skan	}
573169689Skan
574169689Skan	yy_config_free(newcfg);
575169689Skan	pjdlog_info("Configuration reloaded successfully.");
576169689Skan	return;
577169689Skanfailed:
578169689Skan	if (newcfg != NULL) {
579169689Skan		if (newcfg->hc_controlconn != NULL)
580169689Skan			proto_close(newcfg->hc_controlconn);
581169689Skan		if (newcfg->hc_listenconn != NULL)
582169689Skan			proto_close(newcfg->hc_listenconn);
583169689Skan		yy_config_free(newcfg);
584169689Skan	}
585169689Skan	pjdlog_warning("Configuration not reloaded.");
586169689Skan}
587169689Skan
588169689Skanstatic void
589169689Skanterminate_workers(void)
59050397Sobrien{
59150397Sobrien	struct hast_resource *res;
59250397Sobrien
59350397Sobrien	pjdlog_info("Termination signal received, exiting.");
594132718Skan	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
59550397Sobrien		if (res->hr_workerpid == 0)
59650397Sobrien			continue;
59790075Sobrien		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
59890075Sobrien		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
59990075Sobrien		if (kill(res->hr_workerpid, SIGTERM) == 0)
60050397Sobrien			continue;
60150397Sobrien		pjdlog_errno(LOG_WARNING,
60250397Sobrien		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
60350397Sobrien		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
60450397Sobrien	}
60550397Sobrien}
60650397Sobrien
60790075Sobrienstatic void
60850397Sobrienlisten_accept(void)
60950397Sobrien{
61090075Sobrien	struct hast_resource *res;
61190075Sobrien	struct proto_conn *conn;
61290075Sobrien	struct nv *nvin, *nvout, *nverr;
61350397Sobrien	const char *resname;
61450397Sobrien	const unsigned char *token;
61550397Sobrien	char laddr[256], raddr[256];
61650397Sobrien	size_t size;
61750397Sobrien	pid_t pid;
61852284Sobrien	int status;
61952284Sobrien
62050397Sobrien	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
62150397Sobrien	pjdlog_debug(1, "Accepting connection to %s.", laddr);
62250397Sobrien
623117395Skan	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
624169689Skan		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
62550397Sobrien		return;
62650397Sobrien	}
62790075Sobrien
62850397Sobrien	proto_local_address(conn, laddr, sizeof(laddr));
62950397Sobrien	proto_remote_address(conn, raddr, sizeof(raddr));
63090075Sobrien	pjdlog_info("Connection from %s to %s.", raddr, laddr);
63190075Sobrien
63290075Sobrien	/* Error in setting timeout is not critical, but why should it fail? */
63390075Sobrien	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
63490075Sobrien		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
63550397Sobrien
63650397Sobrien	nvin = nvout = nverr = NULL;
63750397Sobrien
63850397Sobrien	/*
63950397Sobrien	 * Before receiving any data see if remote host have access to any
64050397Sobrien	 * resource.
64150397Sobrien	 */
64250397Sobrien	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
64350397Sobrien		if (proto_address_match(conn, res->hr_remoteaddr))
64450397Sobrien			break;
64552284Sobrien	}
64690075Sobrien	if (res == NULL) {
64790075Sobrien		pjdlog_error("Client %s isn't known.", raddr);
64850397Sobrien		goto close;
64950397Sobrien	}
65050397Sobrien	/* Ok, remote host can access at least one resource. */
65150397Sobrien
65290075Sobrien	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
65390075Sobrien		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
65490075Sobrien		    raddr);
65590075Sobrien		goto close;
65690075Sobrien	}
657117395Skan
658117395Skan	resname = nv_get_string(nvin, "resource");
659117395Skan	if (resname == NULL) {
660169689Skan		pjdlog_error("No 'resource' field in the header received from %s.",
661169689Skan		    raddr);
66250397Sobrien		goto close;
66350397Sobrien	}
66490075Sobrien	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
66590075Sobrien	token = nv_get_uint8_array(nvin, &size, "token");
66650397Sobrien	/*
66752284Sobrien	 * NULL token means that this is first conection.
66850397Sobrien	 */
66950397Sobrien	if (token != NULL && size != sizeof(res->hr_token)) {
67050397Sobrien		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
67190075Sobrien		    raddr, sizeof(res->hr_token), size);
67290075Sobrien		goto close;
67350397Sobrien	}
67450397Sobrien
67590075Sobrien	/*
67690075Sobrien	 * From now on we want to send errors to the remote node.
67752284Sobrien	 */
67890075Sobrien	nverr = nv_alloc();
67990075Sobrien
68052284Sobrien	/* Find resource related to this connection. */
68152284Sobrien	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
68250397Sobrien		if (strcmp(resname, res->hr_name) == 0)
68350397Sobrien			break;
68452284Sobrien	}
68552284Sobrien	/* Have we found the resource? */
68652284Sobrien	if (res == NULL) {
68752284Sobrien		pjdlog_error("No resource '%s' as requested by %s.",
68852284Sobrien		    resname, raddr);
68952284Sobrien		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
69050397Sobrien		goto fail;
69150397Sobrien	}
69250397Sobrien
69350397Sobrien	/* Now that we know resource name setup log prefix. */
69450397Sobrien	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
69550397Sobrien
69650397Sobrien	/* Does the remote host have access to this resource? */
69750397Sobrien	if (!proto_address_match(conn, res->hr_remoteaddr)) {
69850397Sobrien		pjdlog_error("Client %s has no access to the resource.", raddr);
69950397Sobrien		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
70050397Sobrien		goto fail;
70150397Sobrien	}
70250397Sobrien	/* Is the resource marked as secondary? */
70350397Sobrien	if (res->hr_role != HAST_ROLE_SECONDARY) {
70450397Sobrien		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
70550397Sobrien		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
706171825Skan		    raddr);
70750397Sobrien		nv_add_stringf(nverr, "errmsg",
70850397Sobrien		    "Remote node acts as %s for the resource and not as %s.",
70950397Sobrien		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
71050397Sobrien		goto fail;
71150397Sobrien	}
712169689Skan	/* Does token (if exists) match? */
71350397Sobrien	if (token != NULL && memcmp(token, res->hr_token,
71450397Sobrien	    sizeof(res->hr_token)) != 0) {
71550397Sobrien		pjdlog_error("Token received from %s doesn't match.", raddr);
71650397Sobrien		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
71750397Sobrien		goto fail;
71850397Sobrien	}
71950397Sobrien	/*
72050397Sobrien	 * If there is no token, but we have half-open connection
72150397Sobrien	 * (only remotein) or full connection (worker process is running)
72250397Sobrien	 * we have to cancel those and accept the new connection.
72350397Sobrien	 */
72450397Sobrien	if (token == NULL) {
72550397Sobrien		PJDLOG_ASSERT(res->hr_remoteout == NULL);
72650397Sobrien		pjdlog_debug(1, "Initial connection from %s.", raddr);
72750397Sobrien		if (res->hr_workerpid != 0) {
72850397Sobrien			PJDLOG_ASSERT(res->hr_remotein == NULL);
72950397Sobrien			pjdlog_debug(1,
73050397Sobrien			    "Worker process exists (pid=%u), stopping it.",
73150397Sobrien			    (unsigned int)res->hr_workerpid);
73250397Sobrien			/* Stop child process. */
73350397Sobrien			if (kill(res->hr_workerpid, SIGINT) < 0) {
73450397Sobrien				pjdlog_errno(LOG_ERR,
73550397Sobrien				    "Unable to stop worker process (pid=%u)",
73650397Sobrien				    (unsigned int)res->hr_workerpid);
73750397Sobrien				/*
73850397Sobrien				 * Other than logging the problem we
739169689Skan				 * ignore it - nothing smart to do.
740169689Skan				 */
741169689Skan			}
74250397Sobrien			/* Wait for it to exit. */
74390075Sobrien			else if ((pid = waitpid(res->hr_workerpid,
74490075Sobrien			    &status, 0)) != res->hr_workerpid) {
74590075Sobrien				/* We can only log the problem. */
74690075Sobrien				pjdlog_errno(LOG_ERR,
74790075Sobrien				    "Waiting for worker process (pid=%u) failed",
74890075Sobrien				    (unsigned int)res->hr_workerpid);
74990075Sobrien			} else {
75090075Sobrien				child_exit_log(res->hr_workerpid, status);
75190075Sobrien			}
75290075Sobrien			child_cleanup(res);
75390075Sobrien		} else if (res->hr_remotein != NULL) {
75490075Sobrien			char oaddr[256];
75590075Sobrien
75650397Sobrien			proto_remote_address(res->hr_remotein, oaddr,
75750397Sobrien			    sizeof(oaddr));
75850397Sobrien			pjdlog_debug(1,
75950397Sobrien			    "Canceling half-open connection from %s on connection from %s.",
76052284Sobrien			    oaddr, raddr);
76152284Sobrien			proto_close(res->hr_remotein);
76250397Sobrien			res->hr_remotein = NULL;
76350397Sobrien		}
76450397Sobrien	}
76550397Sobrien
76650397Sobrien	/*
76752284Sobrien	 * Checks and cleanups are done.
76890075Sobrien	 */
769117395Skan
770117395Skan	if (token == NULL) {
771169689Skan		arc4random_buf(res->hr_token, sizeof(res->hr_token));
772169689Skan		nvout = nv_alloc();
77390075Sobrien		nv_add_uint8_array(nvout, res->hr_token,
77450397Sobrien		    sizeof(res->hr_token), "token");
77550397Sobrien		if (nv_error(nvout) != 0) {
77650397Sobrien			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
77750397Sobrien			    "Unable to prepare return header for %s", raddr);
77850397Sobrien			nv_add_stringf(nverr, "errmsg",
77990075Sobrien			    "Remote node was unable to prepare return header: %s.",
78090075Sobrien			    strerror(nv_error(nvout)));
78190075Sobrien			goto fail;
78290075Sobrien		}
78350397Sobrien		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
78450397Sobrien			int error = errno;
785132718Skan
786169689Skan			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
787169689Skan			    raddr);
788169689Skan			nv_add_stringf(nverr, "errmsg",
789169689Skan			    "Remote node was unable to send response: %s.",
790132718Skan			    strerror(error));
791132718Skan			goto fail;
792169689Skan		}
793169689Skan		res->hr_remotein = conn;
794169689Skan		pjdlog_debug(1, "Incoming connection from %s configured.",
795169689Skan		    raddr);
796169689Skan	} else {
797169689Skan		res->hr_remoteout = conn;
798169689Skan		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
799169689Skan		hastd_secondary(res, nvin);
800169689Skan	}
801169689Skan	nv_free(nvin);
802169689Skan	nv_free(nvout);
803169689Skan	nv_free(nverr);
804169689Skan	pjdlog_prefix_set("%s", "");
805169689Skan	return;
806169689Skanfail:
807169689Skan	if (nv_error(nverr) != 0) {
808169689Skan		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
809169689Skan		    "Unable to prepare error header for %s", raddr);
810169689Skan		goto close;
811169689Skan	}
812169689Skan	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
813169689Skan		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
814169689Skan		goto close;
815169689Skan	}
816169689Skanclose:
817169689Skan	if (nvin != NULL)
818169689Skan		nv_free(nvin);
819169689Skan	if (nvout != NULL)
820169689Skan		nv_free(nvout);
821169689Skan	if (nverr != NULL)
822169689Skan		nv_free(nverr);
823169689Skan	proto_close(conn);
824169689Skan	pjdlog_prefix_set("%s", "");
825169689Skan}
826169689Skan
827169689Skanstatic void
828169689Skanconnection_migrate(struct hast_resource *res)
829169689Skan{
83050397Sobrien	struct proto_conn *conn;
83150397Sobrien	int16_t val = 0;
832169689Skan
833169689Skan	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
834169689Skan		pjdlog_errno(LOG_WARNING,
835169689Skan		    "Unable to receive connection command");
836169689Skan		return;
837169689Skan	}
838169689Skan	if (proto_client(res->hr_remoteaddr, &conn) < 0) {
839169689Skan		val = errno;
840169689Skan		pjdlog_errno(LOG_WARNING,
841169689Skan		    "Unable to create outgoing connection to %s",
84250397Sobrien		    res->hr_remoteaddr);
84350397Sobrien		goto out;
84450397Sobrien	}
84550397Sobrien	if (proto_connect(conn, -1) < 0) {
84650397Sobrien		val = errno;
84750397Sobrien		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
848132718Skan		    res->hr_remoteaddr);
84950397Sobrien		proto_close(conn);
85050397Sobrien		goto out;
85150397Sobrien	}
85250397Sobrien	val = 0;
85350397Sobrienout:
85490075Sobrien	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
85590075Sobrien		pjdlog_errno(LOG_WARNING,
85690075Sobrien		    "Unable to send reply to connection request");
85790075Sobrien	}
85890075Sobrien	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
859132718Skan		pjdlog_errno(LOG_WARNING, "Unable to send connection");
86090075Sobrien}
86190075Sobrien
86290075Sobrienstatic void
86390075Sobrienmain_loop(void)
86490075Sobrien{
86590075Sobrien	struct hast_resource *res;
86690075Sobrien	struct timeval seltimeout;
86790075Sobrien	struct timespec sigtimeout;
868169689Skan	int fd, maxfd, ret, signo;
86990075Sobrien	sigset_t mask;
87090075Sobrien	fd_set rfds;
87190075Sobrien
87250397Sobrien	seltimeout.tv_sec = REPORT_INTERVAL;
87350397Sobrien	seltimeout.tv_usec = 0;
87490075Sobrien	sigtimeout.tv_sec = 0;
87590075Sobrien	sigtimeout.tv_nsec = 0;
87690075Sobrien
87790075Sobrien	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
87890075Sobrien	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
879132718Skan	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
88090075Sobrien	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
88190075Sobrien	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
88290075Sobrien
88390075Sobrien	pjdlog_info("Started successfully, running protocol version %d.",
88490075Sobrien	    HAST_PROTO_VERSION);
88590075Sobrien
88690075Sobrien	for (;;) {
88790075Sobrien		while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
888169689Skan			switch (signo) {
88990075Sobrien			case SIGINT:
89090075Sobrien			case SIGTERM:
89190075Sobrien				sigexit_received = true;
89290075Sobrien				terminate_workers();
89390075Sobrien				proto_close(cfg->hc_controlconn);
89490075Sobrien				exit(EX_OK);
89590075Sobrien				break;
89690075Sobrien			case SIGCHLD:
89790075Sobrien				child_exit();
89890075Sobrien				break;
899132718Skan			case SIGHUP:
90090075Sobrien				hastd_reload();
90190075Sobrien				break;
90290075Sobrien			default:
90390075Sobrien				PJDLOG_ABORT("Unexpected signal (%d).", signo);
90490075Sobrien			}
90590075Sobrien		}
90690075Sobrien
90790075Sobrien		/* Setup descriptors for select(2). */
90890075Sobrien		FD_ZERO(&rfds);
90990075Sobrien		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
91090075Sobrien		PJDLOG_ASSERT(fd >= 0);
911169689Skan		FD_SET(fd, &rfds);
91290075Sobrien		fd = proto_descriptor(cfg->hc_listenconn);
91390075Sobrien		PJDLOG_ASSERT(fd >= 0);
91490075Sobrien		FD_SET(fd, &rfds);
91590075Sobrien		maxfd = fd > maxfd ? fd : maxfd;
91690075Sobrien		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
917169689Skan			if (res->hr_event == NULL)
91850397Sobrien				continue;
919169689Skan			PJDLOG_ASSERT(res->hr_conn != NULL);
920169689Skan			fd = proto_descriptor(res->hr_event);
92150397Sobrien			PJDLOG_ASSERT(fd >= 0);
922169689Skan			FD_SET(fd, &rfds);
923169689Skan			maxfd = fd > maxfd ? fd : maxfd;
924169689Skan			if (res->hr_role == HAST_ROLE_PRIMARY) {
925169689Skan				/* Only primary workers asks for connections. */
926169689Skan				fd = proto_descriptor(res->hr_conn);
927169689Skan				PJDLOG_ASSERT(fd >= 0);
92850397Sobrien				FD_SET(fd, &rfds);
929169689Skan				maxfd = fd > maxfd ? fd : maxfd;
930169689Skan			}
931169689Skan		}
932169689Skan
933169689Skan		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
934169689Skan		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
93550397Sobrien		if (ret == 0)
936169689Skan			hook_check();
937169689Skan		else if (ret == -1) {
938169689Skan			if (errno == EINTR)
939169689Skan				continue;
940169689Skan			KEEP_ERRNO((void)pidfile_remove(pfh));
941169689Skan			pjdlog_exit(EX_OSERR, "select() failed");
942169689Skan		}
943169689Skan
94450397Sobrien		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
945169689Skan			control_handle(cfg);
946169689Skan		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
947169689Skan			listen_accept();
948169689Skan		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
949169689Skan			if (res->hr_event == NULL)
95050397Sobrien				continue;
951169689Skan			PJDLOG_ASSERT(res->hr_conn != NULL);
95250397Sobrien			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
953169689Skan				if (event_recv(res) == 0)
954169689Skan					continue;
955169689Skan				/* The worker process exited? */
956169689Skan				proto_close(res->hr_event);
957169689Skan				res->hr_event = NULL;
958169689Skan				proto_close(res->hr_conn);
959169689Skan				res->hr_conn = NULL;
960169689Skan				continue;
961169689Skan			}
962169689Skan			if (res->hr_role == HAST_ROLE_PRIMARY &&
963169689Skan			    FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) {
964169689Skan				connection_migrate(res);
965169689Skan			}
966169689Skan		}
96796263Sobrien	}
968169689Skan}
969169689Skan
970169689Skanstatic void
971169689Skandummy_sighandler(int sig __unused)
972169689Skan{
97396263Sobrien	/* Nothing to do. */
974169689Skan}
975169689Skan
976169689Skanint
977169689Skanmain(int argc, char *argv[])
978169689Skan{
979169689Skan	const char *pidfile;
98096263Sobrien	pid_t otherpid;
981169689Skan	bool foreground;
982169689Skan	int debuglevel;
983169689Skan	sigset_t mask;
984169689Skan
985169689Skan	foreground = false;
986169689Skan	debuglevel = 0;
987169689Skan	pidfile = HASTD_PIDFILE;
988169689Skan
989169689Skan	for (;;) {
99050397Sobrien		int ch;
99150397Sobrien
992169689Skan		ch = getopt(argc, argv, "c:dFhP:");
993169689Skan		if (ch == -1)
994169689Skan			break;
995169689Skan		switch (ch) {
996169689Skan		case 'c':
997169689Skan			cfgpath = optarg;
998169689Skan			break;
99950397Sobrien		case 'd':
1000169689Skan			debuglevel++;
1001169689Skan			break;
1002169689Skan		case 'F':
1003169689Skan			foreground = true;
1004169689Skan			break;
1005132718Skan		case 'P':
1006169689Skan			pidfile = optarg;
1007169689Skan			break;
1008169689Skan		case 'h':
1009169689Skan		default:
101050397Sobrien			usage();
1011169689Skan		}
1012169689Skan	}
1013169689Skan	argc -= optind;
1014169689Skan	argv += optind;
1015169689Skan
1016169689Skan	pjdlog_init(PJDLOG_MODE_STD);
1017169689Skan	pjdlog_debug_set(debuglevel);
1018169689Skan
101950397Sobrien	g_gate_load();
1020169689Skan
1021169689Skan	pfh = pidfile_open(pidfile, 0600, &otherpid);
1022169689Skan	if (pfh == NULL) {
1023169689Skan		if (errno == EEXIST) {
102450397Sobrien			pjdlog_exitx(EX_TEMPFAIL,
102550397Sobrien			    "Another hastd is already running, pid: %jd.",
1026169689Skan			    (intmax_t)otherpid);
1027169689Skan		}
1028169689Skan		/* If we cannot create pidfile from other reasons, only warn. */
1029169689Skan		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1030169689Skan	}
103150397Sobrien
1032169689Skan	cfg = yy_config_parse(cfgpath, true);
103350397Sobrien	PJDLOG_ASSERT(cfg != NULL);
1034169689Skan
1035169689Skan	/*
1036169689Skan	 * Restore default actions for interesting signals in case parent
103750397Sobrien	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1038169689Skan	 */
1039169689Skan	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1040169689Skan	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1041169689Skan	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
104250397Sobrien	/*
1043169689Skan	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1044169689Skan	 * so we can mask it.
1045169689Skan	 */
1046169689Skan	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1047169689Skan
1048169689Skan	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1049169689Skan	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
105050397Sobrien	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
105150397Sobrien	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1052169689Skan	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
105350397Sobrien	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
105450397Sobrien
1055169689Skan	/* Listen on control address. */
1056169689Skan	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1057169689Skan		KEEP_ERRNO((void)pidfile_remove(pfh));
105850397Sobrien		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
105952284Sobrien		    cfg->hc_controladdr);
1060132718Skan	}
106152284Sobrien	/* Listen for remote connections. */
106252284Sobrien	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
106352284Sobrien		KEEP_ERRNO((void)pidfile_remove(pfh));
106452284Sobrien		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
106552284Sobrien		    cfg->hc_listenaddr);
106652284Sobrien	}
106752284Sobrien
106852284Sobrien	if (!foreground) {
106952284Sobrien		if (daemon(0, 0) < 0) {
107052284Sobrien			KEEP_ERRNO((void)pidfile_remove(pfh));
107152284Sobrien			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1072169689Skan		}
1073169689Skan
1074169689Skan		/* Start logging to syslog. */
107552284Sobrien		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
107652284Sobrien
107752284Sobrien		/* Write PID to a file. */
1078169689Skan		if (pidfile_write(pfh) < 0) {
1079169689Skan			pjdlog_errno(LOG_WARNING,
1080169689Skan			    "Unable to write PID to a file");
108190075Sobrien		}
108252284Sobrien	}
108352284Sobrien
108490075Sobrien	hook_init();
108552284Sobrien
108652284Sobrien	main_loop();
108752284Sobrien
108852284Sobrien	exit(0);
108952284Sobrien}
109090075Sobrien