hastd.c revision 218373
1204076Spjd/*-
2204076Spjd * Copyright (c) 2009-2010 The FreeBSD Foundation
3218041Spjd * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4204076Spjd * All rights reserved.
5204076Spjd *
6204076Spjd * This software was developed by Pawel Jakub Dawidek under sponsorship from
7204076Spjd * the FreeBSD Foundation.
8204076Spjd *
9204076Spjd * Redistribution and use in source and binary forms, with or without
10204076Spjd * modification, are permitted provided that the following conditions
11204076Spjd * are met:
12204076Spjd * 1. Redistributions of source code must retain the above copyright
13204076Spjd *    notice, this list of conditions and the following disclaimer.
14204076Spjd * 2. Redistributions in binary form must reproduce the above copyright
15204076Spjd *    notice, this list of conditions and the following disclaimer in the
16204076Spjd *    documentation and/or other materials provided with the distribution.
17204076Spjd *
18204076Spjd * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19204076Spjd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20204076Spjd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21204076Spjd * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22204076Spjd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23204076Spjd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24204076Spjd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25204076Spjd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26204076Spjd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27204076Spjd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28204076Spjd * SUCH DAMAGE.
29204076Spjd */
30204076Spjd
31204076Spjd#include <sys/cdefs.h>
32204076Spjd__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 218373 2011-02-06 14:06:37Z pjd $");
33204076Spjd
34204076Spjd#include <sys/param.h>
35204076Spjd#include <sys/linker.h>
36204076Spjd#include <sys/module.h>
37218044Spjd#include <sys/stat.h>
38204076Spjd#include <sys/wait.h>
39204076Spjd
40204076Spjd#include <err.h>
41204076Spjd#include <errno.h>
42204076Spjd#include <libutil.h>
43204076Spjd#include <signal.h>
44204076Spjd#include <stdbool.h>
45204076Spjd#include <stdio.h>
46204076Spjd#include <stdlib.h>
47204076Spjd#include <string.h>
48204076Spjd#include <sysexits.h>
49204076Spjd#include <unistd.h>
50204076Spjd
51204076Spjd#include <activemap.h>
52204076Spjd#include <pjdlog.h>
53204076Spjd
54204076Spjd#include "control.h"
55212038Spjd#include "event.h"
56204076Spjd#include "hast.h"
57204076Spjd#include "hast_proto.h"
58204076Spjd#include "hastd.h"
59211977Spjd#include "hooks.h"
60204076Spjd#include "subr.h"
61204076Spjd
62204076Spjd/* Path to configuration file. */
63210886Spjdconst char *cfgpath = HAST_CONFIG;
64204076Spjd/* Hastd configuration. */
65204076Spjdstatic struct hastd_config *cfg;
66204076Spjd/* Was SIGINT or SIGTERM signal received? */
67204076Spjdbool sigexit_received = false;
68204076Spjd/* PID file handle. */
69204076Spjdstruct pidfh *pfh;
70204076Spjd
71211977Spjd/* How often check for hooks running for too long. */
72213430Spjd#define	REPORT_INTERVAL	5
73211977Spjd
74204076Spjdstatic void
75204076Spjdusage(void)
76204076Spjd{
77204076Spjd
78204076Spjd	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
79204076Spjd}
80204076Spjd
81204076Spjdstatic void
82204076Spjdg_gate_load(void)
83204076Spjd{
84204076Spjd
85204076Spjd	if (modfind("g_gate") == -1) {
86204076Spjd		/* Not present in kernel, try loading it. */
87204076Spjd		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
88204076Spjd			if (errno != EEXIST) {
89204076Spjd				pjdlog_exit(EX_OSERR,
90204076Spjd				    "Unable to load geom_gate module");
91204076Spjd			}
92204076Spjd		}
93204076Spjd	}
94204076Spjd}
95204076Spjd
96218041Spjdvoid
97218041Spjddescriptors_cleanup(struct hast_resource *res)
98218041Spjd{
99218041Spjd	struct hast_resource *tres;
100218041Spjd
101218041Spjd	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
102218041Spjd		if (tres == res) {
103218041Spjd			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
104218041Spjd			    (res->hr_remotein == NULL &&
105218041Spjd			     res->hr_remoteout == NULL));
106218041Spjd			continue;
107218041Spjd		}
108218041Spjd		if (tres->hr_remotein != NULL)
109218041Spjd			proto_close(tres->hr_remotein);
110218041Spjd		if (tres->hr_remoteout != NULL)
111218041Spjd			proto_close(tres->hr_remoteout);
112218370Spjd		if (tres->hr_ctrl != NULL)
113218370Spjd			proto_close(tres->hr_ctrl);
114218370Spjd		if (tres->hr_event != NULL)
115218370Spjd			proto_close(tres->hr_event);
116218370Spjd		if (tres->hr_conn != NULL)
117218370Spjd			proto_close(tres->hr_conn);
118218041Spjd	}
119218041Spjd	if (cfg->hc_controlin != NULL)
120218041Spjd		proto_close(cfg->hc_controlin);
121218041Spjd	proto_close(cfg->hc_controlconn);
122218041Spjd	proto_close(cfg->hc_listenconn);
123218041Spjd	(void)pidfile_close(pfh);
124218041Spjd	hook_fini();
125218041Spjd	pjdlog_fini();
126218041Spjd}
127218041Spjd
128218044Spjdstatic const char *
129218044Spjddtype2str(mode_t mode)
130218044Spjd{
131218044Spjd
132218044Spjd	if (S_ISBLK(mode))
133218044Spjd		return ("block device");
134218044Spjd	else if (S_ISCHR(mode))
135218044Spjd		return ("character device");
136218044Spjd	else if (S_ISDIR(mode))
137218044Spjd		return ("directory");
138218044Spjd	else if (S_ISFIFO(mode))
139218044Spjd		return ("pipe or FIFO");
140218044Spjd	else if (S_ISLNK(mode))
141218044Spjd		return ("symbolic link");
142218044Spjd	else if (S_ISREG(mode))
143218044Spjd		return ("regular file");
144218044Spjd	else if (S_ISSOCK(mode))
145218044Spjd		return ("socket");
146218044Spjd	else if (S_ISWHT(mode))
147218044Spjd		return ("whiteout");
148218044Spjd	else
149218044Spjd		return ("unknown");
150218044Spjd}
151218044Spjd
152218044Spjdvoid
153218044Spjddescriptors_assert(const struct hast_resource *res, int pjdlogmode)
154218044Spjd{
155218044Spjd	char msg[256];
156218044Spjd	struct stat sb;
157218044Spjd	long maxfd;
158218044Spjd	bool isopen;
159218044Spjd	mode_t mode;
160218044Spjd	int fd;
161218044Spjd
162218044Spjd	/*
163218044Spjd	 * At this point descriptor to syslog socket is closed, so if we want
164218044Spjd	 * to log assertion message, we have to first store it in 'msg' local
165218044Spjd	 * buffer and then open syslog socket and log it.
166218044Spjd	 */
167218044Spjd	msg[0] = '\0';
168218044Spjd
169218044Spjd	maxfd = sysconf(_SC_OPEN_MAX);
170218044Spjd	if (maxfd < 0) {
171218373Spjd		pjdlog_init(pjdlogmode);
172218373Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
173218373Spjd		    role2str(res->hr_role));
174218044Spjd		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
175218373Spjd		pjdlog_fini();
176218044Spjd		maxfd = 16384;
177218044Spjd	}
178218044Spjd	for (fd = 0; fd <= maxfd; fd++) {
179218044Spjd		if (fstat(fd, &sb) == 0) {
180218044Spjd			isopen = true;
181218044Spjd			mode = sb.st_mode;
182218044Spjd		} else if (errno == EBADF) {
183218044Spjd			isopen = false;
184218044Spjd			mode = 0;
185218044Spjd		} else {
186218044Spjd			isopen = true;	/* silence gcc */
187218044Spjd			mode = 0;	/* silence gcc */
188218044Spjd			snprintf(msg, sizeof(msg),
189218044Spjd			    "Unable to fstat descriptor %d: %s", fd,
190218044Spjd			    strerror(errno));
191218044Spjd		}
192218044Spjd		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
193218044Spjd		    fd == STDERR_FILENO) {
194218044Spjd			if (!isopen) {
195218044Spjd				snprintf(msg, sizeof(msg),
196218044Spjd				    "Descriptor %d (%s) is closed, but should be open.",
197218044Spjd				    fd, (fd == STDIN_FILENO ? "stdin" :
198218044Spjd				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
199218044Spjd				break;
200218044Spjd			}
201218044Spjd		} else if (fd == proto_descriptor(res->hr_event)) {
202218044Spjd			if (!isopen) {
203218044Spjd				snprintf(msg, sizeof(msg),
204218044Spjd				    "Descriptor %d (event) is closed, but should be open.",
205218044Spjd				    fd);
206218044Spjd				break;
207218044Spjd			}
208218044Spjd			if (!S_ISSOCK(mode)) {
209218044Spjd				snprintf(msg, sizeof(msg),
210218044Spjd				    "Descriptor %d (event) is %s, but should be %s.",
211218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
212218044Spjd				break;
213218044Spjd			}
214218044Spjd		} else if (fd == proto_descriptor(res->hr_ctrl)) {
215218044Spjd			if (!isopen) {
216218044Spjd				snprintf(msg, sizeof(msg),
217218044Spjd				    "Descriptor %d (ctrl) is closed, but should be open.",
218218044Spjd				    fd);
219218044Spjd				break;
220218044Spjd			}
221218044Spjd			if (!S_ISSOCK(mode)) {
222218044Spjd				snprintf(msg, sizeof(msg),
223218044Spjd				    "Descriptor %d (ctrl) is %s, but should be %s.",
224218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
225218044Spjd				break;
226218044Spjd			}
227218218Spjd		} else if (fd == proto_descriptor(res->hr_conn)) {
228218218Spjd			if (!isopen) {
229218218Spjd				snprintf(msg, sizeof(msg),
230218218Spjd				    "Descriptor %d (conn) is closed, but should be open.",
231218218Spjd				    fd);
232218218Spjd				break;
233218218Spjd			}
234218218Spjd			if (!S_ISSOCK(mode)) {
235218218Spjd				snprintf(msg, sizeof(msg),
236218218Spjd				    "Descriptor %d (conn) is %s, but should be %s.",
237218218Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
238218218Spjd				break;
239218218Spjd			}
240218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
241218044Spjd		    fd == proto_descriptor(res->hr_remotein)) {
242218044Spjd			if (!isopen) {
243218044Spjd				snprintf(msg, sizeof(msg),
244218044Spjd				    "Descriptor %d (remote in) is closed, but should be open.",
245218044Spjd				    fd);
246218044Spjd				break;
247218044Spjd			}
248218044Spjd			if (!S_ISSOCK(mode)) {
249218044Spjd				snprintf(msg, sizeof(msg),
250218044Spjd				    "Descriptor %d (remote in) is %s, but should be %s.",
251218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
252218044Spjd				break;
253218044Spjd			}
254218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
255218044Spjd		    fd == proto_descriptor(res->hr_remoteout)) {
256218044Spjd			if (!isopen) {
257218044Spjd				snprintf(msg, sizeof(msg),
258218044Spjd				    "Descriptor %d (remote out) is closed, but should be open.",
259218044Spjd				    fd);
260218044Spjd				break;
261218044Spjd			}
262218044Spjd			if (!S_ISSOCK(mode)) {
263218044Spjd				snprintf(msg, sizeof(msg),
264218044Spjd				    "Descriptor %d (remote out) is %s, but should be %s.",
265218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
266218044Spjd				break;
267218044Spjd			}
268218044Spjd		} else {
269218044Spjd			if (isopen) {
270218044Spjd				snprintf(msg, sizeof(msg),
271218044Spjd				    "Descriptor %d is open (%s), but should be closed.",
272218044Spjd				    fd, dtype2str(mode));
273218044Spjd				break;
274218044Spjd			}
275218044Spjd		}
276218044Spjd	}
277218044Spjd	if (msg[0] != '\0') {
278218044Spjd		pjdlog_init(pjdlogmode);
279218044Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
280218044Spjd		    role2str(res->hr_role));
281218044Spjd		PJDLOG_ABORT("%s", msg);
282218044Spjd	}
283218044Spjd}
284218044Spjd
285204076Spjdstatic void
286207372Spjdchild_exit_log(unsigned int pid, int status)
287207372Spjd{
288207372Spjd
289207372Spjd	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
290207372Spjd		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
291207372Spjd		    pid);
292207372Spjd	} else if (WIFSIGNALED(status)) {
293207372Spjd		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
294207372Spjd		    pid, WTERMSIG(status));
295207372Spjd	} else {
296207372Spjd		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
297207372Spjd		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
298207372Spjd	}
299207372Spjd}
300207372Spjd
301207372Spjdstatic void
302204076Spjdchild_exit(void)
303204076Spjd{
304204076Spjd	struct hast_resource *res;
305204076Spjd	int status;
306204076Spjd	pid_t pid;
307204076Spjd
308204076Spjd	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
309204076Spjd		/* Find resource related to the process that just exited. */
310204076Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
311204076Spjd			if (pid == res->hr_workerpid)
312204076Spjd				break;
313204076Spjd		}
314204076Spjd		if (res == NULL) {
315204076Spjd			/*
316204076Spjd			 * This can happen when new connection arrives and we
317211977Spjd			 * cancel child responsible for the old one or if this
318211977Spjd			 * was hook which we executed.
319204076Spjd			 */
320211977Spjd			hook_check_one(pid, status);
321204076Spjd			continue;
322204076Spjd		}
323204076Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
324204076Spjd		    role2str(res->hr_role));
325207372Spjd		child_exit_log(pid, status);
326213006Spjd		child_cleanup(res);
327204076Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
328207372Spjd			/*
329207372Spjd			 * Restart child process if it was killed by signal
330207372Spjd			 * or exited because of temporary problem.
331207372Spjd			 */
332207372Spjd			if (WIFSIGNALED(status) ||
333207372Spjd			    (WIFEXITED(status) &&
334207372Spjd			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
335207348Spjd				sleep(1);
336207348Spjd				pjdlog_info("Restarting worker process.");
337207348Spjd				hastd_primary(res);
338207348Spjd			} else {
339207348Spjd				res->hr_role = HAST_ROLE_INIT;
340207348Spjd				pjdlog_info("Changing resource role back to %s.",
341207348Spjd				    role2str(res->hr_role));
342207348Spjd			}
343204076Spjd		}
344204076Spjd		pjdlog_prefix_set("%s", "");
345204076Spjd	}
346204076Spjd}
347204076Spjd
348210886Spjdstatic bool
349210886Spjdresource_needs_restart(const struct hast_resource *res0,
350210886Spjd    const struct hast_resource *res1)
351210886Spjd{
352210886Spjd
353218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
354210886Spjd
355210886Spjd	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
356210886Spjd		return (true);
357210886Spjd	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
358210886Spjd		return (true);
359210886Spjd	if (res0->hr_role == HAST_ROLE_INIT ||
360210886Spjd	    res0->hr_role == HAST_ROLE_SECONDARY) {
361210886Spjd		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
362210886Spjd			return (true);
363210886Spjd		if (res0->hr_replication != res1->hr_replication)
364210886Spjd			return (true);
365210886Spjd		if (res0->hr_timeout != res1->hr_timeout)
366210886Spjd			return (true);
367211886Spjd		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
368211886Spjd			return (true);
369210886Spjd	}
370210886Spjd	return (false);
371210886Spjd}
372210886Spjd
373210886Spjdstatic bool
374210886Spjdresource_needs_reload(const struct hast_resource *res0,
375210886Spjd    const struct hast_resource *res1)
376210886Spjd{
377210886Spjd
378218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
379218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
380218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
381210886Spjd
382210886Spjd	if (res0->hr_role != HAST_ROLE_PRIMARY)
383210886Spjd		return (false);
384210886Spjd
385210886Spjd	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
386210886Spjd		return (true);
387210886Spjd	if (res0->hr_replication != res1->hr_replication)
388210886Spjd		return (true);
389210886Spjd	if (res0->hr_timeout != res1->hr_timeout)
390210886Spjd		return (true);
391211886Spjd	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
392211886Spjd		return (true);
393210886Spjd	return (false);
394210886Spjd}
395210886Spjd
396204076Spjdstatic void
397217784Spjdresource_reload(const struct hast_resource *res)
398217784Spjd{
399217784Spjd	struct nv *nvin, *nvout;
400217784Spjd	int error;
401217784Spjd
402218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
403217784Spjd
404217784Spjd	nvout = nv_alloc();
405217784Spjd	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
406217784Spjd	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
407217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
408217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
409217784Spjd	nv_add_string(nvout, res->hr_exec, "exec");
410217784Spjd	if (nv_error(nvout) != 0) {
411217784Spjd		nv_free(nvout);
412217784Spjd		pjdlog_error("Unable to allocate header for reload message.");
413217784Spjd		return;
414217784Spjd	}
415217784Spjd	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
416217784Spjd		pjdlog_errno(LOG_ERR, "Unable to send reload message");
417217784Spjd		nv_free(nvout);
418217784Spjd		return;
419217784Spjd	}
420217784Spjd	nv_free(nvout);
421217784Spjd
422217784Spjd	/* Receive response. */
423217784Spjd	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
424217784Spjd		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
425217784Spjd		return;
426217784Spjd	}
427217784Spjd	error = nv_get_int16(nvin, "error");
428217784Spjd	nv_free(nvin);
429217784Spjd	if (error != 0) {
430217784Spjd		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
431217784Spjd		return;
432217784Spjd	}
433217784Spjd}
434217784Spjd
435217784Spjdstatic void
436204076Spjdhastd_reload(void)
437204076Spjd{
438210886Spjd	struct hastd_config *newcfg;
439210886Spjd	struct hast_resource *nres, *cres, *tres;
440210886Spjd	uint8_t role;
441204076Spjd
442210886Spjd	pjdlog_info("Reloading configuration...");
443210886Spjd
444210886Spjd	newcfg = yy_config_parse(cfgpath, false);
445210886Spjd	if (newcfg == NULL)
446210886Spjd		goto failed;
447210886Spjd
448210886Spjd	/*
449210886Spjd	 * Check if control address has changed.
450210886Spjd	 */
451210886Spjd	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
452210886Spjd		if (proto_server(newcfg->hc_controladdr,
453210886Spjd		    &newcfg->hc_controlconn) < 0) {
454210886Spjd			pjdlog_errno(LOG_ERR,
455210886Spjd			    "Unable to listen on control address %s",
456210886Spjd			    newcfg->hc_controladdr);
457210886Spjd			goto failed;
458210886Spjd		}
459210886Spjd	}
460210886Spjd	/*
461210886Spjd	 * Check if listen address has changed.
462210886Spjd	 */
463210886Spjd	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
464210886Spjd		if (proto_server(newcfg->hc_listenaddr,
465210886Spjd		    &newcfg->hc_listenconn) < 0) {
466210886Spjd			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
467210886Spjd			    newcfg->hc_listenaddr);
468210886Spjd			goto failed;
469210886Spjd		}
470210886Spjd	}
471210886Spjd	/*
472210886Spjd	 * Only when both control and listen sockets are successfully
473210886Spjd	 * initialized switch them to new configuration.
474210886Spjd	 */
475210886Spjd	if (newcfg->hc_controlconn != NULL) {
476210886Spjd		pjdlog_info("Control socket changed from %s to %s.",
477210886Spjd		    cfg->hc_controladdr, newcfg->hc_controladdr);
478210886Spjd		proto_close(cfg->hc_controlconn);
479210886Spjd		cfg->hc_controlconn = newcfg->hc_controlconn;
480210886Spjd		newcfg->hc_controlconn = NULL;
481210886Spjd		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
482210886Spjd		    sizeof(cfg->hc_controladdr));
483210886Spjd	}
484210886Spjd	if (newcfg->hc_listenconn != NULL) {
485210886Spjd		pjdlog_info("Listen socket changed from %s to %s.",
486210886Spjd		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
487210886Spjd		proto_close(cfg->hc_listenconn);
488210886Spjd		cfg->hc_listenconn = newcfg->hc_listenconn;
489210886Spjd		newcfg->hc_listenconn = NULL;
490210886Spjd		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
491210886Spjd		    sizeof(cfg->hc_listenaddr));
492210886Spjd	}
493210886Spjd
494210886Spjd	/*
495210886Spjd	 * Stop and remove resources that were removed from the configuration.
496210886Spjd	 */
497210886Spjd	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
498210886Spjd		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
499210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
500210886Spjd				break;
501210886Spjd		}
502210886Spjd		if (nres == NULL) {
503210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
504210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
505210886Spjd			pjdlog_info("Resource %s removed.", cres->hr_name);
506210886Spjd			free(cres);
507210886Spjd		}
508210886Spjd	}
509210886Spjd	/*
510210886Spjd	 * Move new resources to the current configuration.
511210886Spjd	 */
512210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
513210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
514210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
515210886Spjd				break;
516210886Spjd		}
517210886Spjd		if (cres == NULL) {
518210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
519210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
520210886Spjd			pjdlog_info("Resource %s added.", nres->hr_name);
521210886Spjd		}
522210886Spjd	}
523210886Spjd	/*
524210886Spjd	 * Deal with modified resources.
525210886Spjd	 * Depending on what has changed exactly we might want to perform
526210886Spjd	 * different actions.
527210886Spjd	 *
528210886Spjd	 * We do full resource restart in the following situations:
529210886Spjd	 * Resource role is INIT or SECONDARY.
530210886Spjd	 * Resource role is PRIMARY and path to local component or provider
531210886Spjd	 * name has changed.
532210886Spjd	 * In case of PRIMARY, the worker process will be killed and restarted,
533210886Spjd	 * which also means removing /dev/hast/<name> provider and
534210886Spjd	 * recreating it.
535210886Spjd	 *
536210886Spjd	 * We do just reload (send SIGHUP to worker process) if we act as
537217729Spjd	 * PRIMARY, but only if remote address, replication mode, timeout or
538217729Spjd	 * execution path has changed. For those, there is no need to restart
539217729Spjd	 * worker process.
540210886Spjd	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
541210886Spjd	 * replication mode has changed or simply set new timeout if only
542210886Spjd	 * timeout has changed.
543210886Spjd	 */
544210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
545210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
546210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
547210886Spjd				break;
548210886Spjd		}
549218138Spjd		PJDLOG_ASSERT(cres != NULL);
550210886Spjd		if (resource_needs_restart(cres, nres)) {
551210886Spjd			pjdlog_info("Resource %s configuration was modified, restarting it.",
552210886Spjd			    cres->hr_name);
553210886Spjd			role = cres->hr_role;
554210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
555210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
556210886Spjd			free(cres);
557210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
558210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
559210886Spjd			control_set_role(nres, role);
560210886Spjd		} else if (resource_needs_reload(cres, nres)) {
561210886Spjd			pjdlog_info("Resource %s configuration was modified, reloading it.",
562210886Spjd			    cres->hr_name);
563210886Spjd			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
564210886Spjd			    sizeof(cres->hr_remoteaddr));
565210886Spjd			cres->hr_replication = nres->hr_replication;
566210886Spjd			cres->hr_timeout = nres->hr_timeout;
567217729Spjd			strlcpy(cres->hr_exec, nres->hr_exec,
568217729Spjd			    sizeof(cres->hr_exec));
569217784Spjd			if (cres->hr_workerpid != 0)
570217784Spjd				resource_reload(cres);
571210886Spjd		}
572210886Spjd	}
573210886Spjd
574210886Spjd	yy_config_free(newcfg);
575210886Spjd	pjdlog_info("Configuration reloaded successfully.");
576210886Spjd	return;
577210886Spjdfailed:
578210886Spjd	if (newcfg != NULL) {
579210886Spjd		if (newcfg->hc_controlconn != NULL)
580210886Spjd			proto_close(newcfg->hc_controlconn);
581210886Spjd		if (newcfg->hc_listenconn != NULL)
582210886Spjd			proto_close(newcfg->hc_listenconn);
583210886Spjd		yy_config_free(newcfg);
584210886Spjd	}
585210886Spjd	pjdlog_warning("Configuration not reloaded.");
586204076Spjd}
587204076Spjd
588204076Spjdstatic void
589211899Spjdterminate_workers(void)
590211899Spjd{
591211899Spjd	struct hast_resource *res;
592211899Spjd
593211899Spjd	pjdlog_info("Termination signal received, exiting.");
594211899Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
595211899Spjd		if (res->hr_workerpid == 0)
596211899Spjd			continue;
597211899Spjd		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
598211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
599211899Spjd		if (kill(res->hr_workerpid, SIGTERM) == 0)
600211899Spjd			continue;
601211899Spjd		pjdlog_errno(LOG_WARNING,
602211899Spjd		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
603211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
604211899Spjd	}
605211899Spjd}
606211899Spjd
607211899Spjdstatic void
608204076Spjdlisten_accept(void)
609204076Spjd{
610204076Spjd	struct hast_resource *res;
611204076Spjd	struct proto_conn *conn;
612204076Spjd	struct nv *nvin, *nvout, *nverr;
613204076Spjd	const char *resname;
614204076Spjd	const unsigned char *token;
615204076Spjd	char laddr[256], raddr[256];
616204076Spjd	size_t size;
617204076Spjd	pid_t pid;
618204076Spjd	int status;
619204076Spjd
620204076Spjd	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
621204076Spjd	pjdlog_debug(1, "Accepting connection to %s.", laddr);
622204076Spjd
623204076Spjd	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
624204076Spjd		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
625204076Spjd		return;
626204076Spjd	}
627204076Spjd
628204076Spjd	proto_local_address(conn, laddr, sizeof(laddr));
629204076Spjd	proto_remote_address(conn, raddr, sizeof(raddr));
630209185Spjd	pjdlog_info("Connection from %s to %s.", raddr, laddr);
631204076Spjd
632207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
633207371Spjd	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
634207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
635207371Spjd
636204076Spjd	nvin = nvout = nverr = NULL;
637204076Spjd
638204076Spjd	/*
639204076Spjd	 * Before receiving any data see if remote host have access to any
640204076Spjd	 * resource.
641204076Spjd	 */
642204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
643204076Spjd		if (proto_address_match(conn, res->hr_remoteaddr))
644204076Spjd			break;
645204076Spjd	}
646204076Spjd	if (res == NULL) {
647204076Spjd		pjdlog_error("Client %s isn't known.", raddr);
648204076Spjd		goto close;
649204076Spjd	}
650204076Spjd	/* Ok, remote host can access at least one resource. */
651204076Spjd
652204076Spjd	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
653204076Spjd		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
654204076Spjd		    raddr);
655204076Spjd		goto close;
656204076Spjd	}
657204076Spjd
658204076Spjd	resname = nv_get_string(nvin, "resource");
659204076Spjd	if (resname == NULL) {
660204076Spjd		pjdlog_error("No 'resource' field in the header received from %s.",
661204076Spjd		    raddr);
662204076Spjd		goto close;
663204076Spjd	}
664204076Spjd	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
665204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
666204076Spjd	/*
667204076Spjd	 * NULL token means that this is first conection.
668204076Spjd	 */
669204076Spjd	if (token != NULL && size != sizeof(res->hr_token)) {
670204076Spjd		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
671204076Spjd		    raddr, sizeof(res->hr_token), size);
672204076Spjd		goto close;
673204076Spjd	}
674204076Spjd
675204076Spjd	/*
676204076Spjd	 * From now on we want to send errors to the remote node.
677204076Spjd	 */
678204076Spjd	nverr = nv_alloc();
679204076Spjd
680204076Spjd	/* Find resource related to this connection. */
681204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
682204076Spjd		if (strcmp(resname, res->hr_name) == 0)
683204076Spjd			break;
684204076Spjd	}
685204076Spjd	/* Have we found the resource? */
686204076Spjd	if (res == NULL) {
687204076Spjd		pjdlog_error("No resource '%s' as requested by %s.",
688204076Spjd		    resname, raddr);
689204076Spjd		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
690204076Spjd		goto fail;
691204076Spjd	}
692204076Spjd
693204076Spjd	/* Now that we know resource name setup log prefix. */
694204076Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
695204076Spjd
696204076Spjd	/* Does the remote host have access to this resource? */
697204076Spjd	if (!proto_address_match(conn, res->hr_remoteaddr)) {
698204076Spjd		pjdlog_error("Client %s has no access to the resource.", raddr);
699204076Spjd		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
700204076Spjd		goto fail;
701204076Spjd	}
702204076Spjd	/* Is the resource marked as secondary? */
703204076Spjd	if (res->hr_role != HAST_ROLE_SECONDARY) {
704204076Spjd		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
705204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
706204076Spjd		    raddr);
707204076Spjd		nv_add_stringf(nverr, "errmsg",
708204076Spjd		    "Remote node acts as %s for the resource and not as %s.",
709204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
710204076Spjd		goto fail;
711204076Spjd	}
712204076Spjd	/* Does token (if exists) match? */
713204076Spjd	if (token != NULL && memcmp(token, res->hr_token,
714204076Spjd	    sizeof(res->hr_token)) != 0) {
715204076Spjd		pjdlog_error("Token received from %s doesn't match.", raddr);
716209185Spjd		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
717204076Spjd		goto fail;
718204076Spjd	}
719204076Spjd	/*
720204076Spjd	 * If there is no token, but we have half-open connection
721204076Spjd	 * (only remotein) or full connection (worker process is running)
722204076Spjd	 * we have to cancel those and accept the new connection.
723204076Spjd	 */
724204076Spjd	if (token == NULL) {
725218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
726204076Spjd		pjdlog_debug(1, "Initial connection from %s.", raddr);
727204076Spjd		if (res->hr_workerpid != 0) {
728218138Spjd			PJDLOG_ASSERT(res->hr_remotein == NULL);
729204076Spjd			pjdlog_debug(1,
730204076Spjd			    "Worker process exists (pid=%u), stopping it.",
731204076Spjd			    (unsigned int)res->hr_workerpid);
732204076Spjd			/* Stop child process. */
733204076Spjd			if (kill(res->hr_workerpid, SIGINT) < 0) {
734204076Spjd				pjdlog_errno(LOG_ERR,
735204076Spjd				    "Unable to stop worker process (pid=%u)",
736204076Spjd				    (unsigned int)res->hr_workerpid);
737204076Spjd				/*
738204076Spjd				 * Other than logging the problem we
739204076Spjd				 * ignore it - nothing smart to do.
740204076Spjd				 */
741204076Spjd			}
742204076Spjd			/* Wait for it to exit. */
743204076Spjd			else if ((pid = waitpid(res->hr_workerpid,
744204076Spjd			    &status, 0)) != res->hr_workerpid) {
745207372Spjd				/* We can only log the problem. */
746204076Spjd				pjdlog_errno(LOG_ERR,
747204076Spjd				    "Waiting for worker process (pid=%u) failed",
748204076Spjd				    (unsigned int)res->hr_workerpid);
749204076Spjd			} else {
750207372Spjd				child_exit_log(res->hr_workerpid, status);
751204076Spjd			}
752213006Spjd			child_cleanup(res);
753204076Spjd		} else if (res->hr_remotein != NULL) {
754204076Spjd			char oaddr[256];
755204076Spjd
756213981Spjd			proto_remote_address(res->hr_remotein, oaddr,
757213981Spjd			    sizeof(oaddr));
758204076Spjd			pjdlog_debug(1,
759204076Spjd			    "Canceling half-open connection from %s on connection from %s.",
760204076Spjd			    oaddr, raddr);
761204076Spjd			proto_close(res->hr_remotein);
762204076Spjd			res->hr_remotein = NULL;
763204076Spjd		}
764204076Spjd	}
765204076Spjd
766204076Spjd	/*
767204076Spjd	 * Checks and cleanups are done.
768204076Spjd	 */
769204076Spjd
770204076Spjd	if (token == NULL) {
771204076Spjd		arc4random_buf(res->hr_token, sizeof(res->hr_token));
772204076Spjd		nvout = nv_alloc();
773204076Spjd		nv_add_uint8_array(nvout, res->hr_token,
774204076Spjd		    sizeof(res->hr_token), "token");
775204076Spjd		if (nv_error(nvout) != 0) {
776204076Spjd			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
777204076Spjd			    "Unable to prepare return header for %s", raddr);
778204076Spjd			nv_add_stringf(nverr, "errmsg",
779204076Spjd			    "Remote node was unable to prepare return header: %s.",
780204076Spjd			    strerror(nv_error(nvout)));
781204076Spjd			goto fail;
782204076Spjd		}
783204076Spjd		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
784204076Spjd			int error = errno;
785204076Spjd
786204076Spjd			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
787204076Spjd			    raddr);
788204076Spjd			nv_add_stringf(nverr, "errmsg",
789204076Spjd			    "Remote node was unable to send response: %s.",
790204076Spjd			    strerror(error));
791204076Spjd			goto fail;
792204076Spjd		}
793204076Spjd		res->hr_remotein = conn;
794204076Spjd		pjdlog_debug(1, "Incoming connection from %s configured.",
795204076Spjd		    raddr);
796204076Spjd	} else {
797204076Spjd		res->hr_remoteout = conn;
798204076Spjd		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
799204076Spjd		hastd_secondary(res, nvin);
800204076Spjd	}
801204076Spjd	nv_free(nvin);
802204076Spjd	nv_free(nvout);
803204076Spjd	nv_free(nverr);
804204076Spjd	pjdlog_prefix_set("%s", "");
805204076Spjd	return;
806204076Spjdfail:
807204076Spjd	if (nv_error(nverr) != 0) {
808204076Spjd		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
809204076Spjd		    "Unable to prepare error header for %s", raddr);
810204076Spjd		goto close;
811204076Spjd	}
812204076Spjd	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
813204076Spjd		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
814204076Spjd		goto close;
815204076Spjd	}
816204076Spjdclose:
817204076Spjd	if (nvin != NULL)
818204076Spjd		nv_free(nvin);
819204076Spjd	if (nvout != NULL)
820204076Spjd		nv_free(nvout);
821204076Spjd	if (nverr != NULL)
822204076Spjd		nv_free(nverr);
823204076Spjd	proto_close(conn);
824204076Spjd	pjdlog_prefix_set("%s", "");
825204076Spjd}
826204076Spjd
827204076Spjdstatic void
828218218Spjdconnection_migrate(struct hast_resource *res)
829218218Spjd{
830218218Spjd	struct proto_conn *conn;
831218218Spjd	int16_t val = 0;
832218218Spjd
833218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
834218218Spjd		pjdlog_errno(LOG_WARNING,
835218218Spjd		    "Unable to receive connection command");
836218218Spjd		return;
837218218Spjd	}
838218218Spjd	if (proto_client(res->hr_remoteaddr, &conn) < 0) {
839218218Spjd		val = errno;
840218218Spjd		pjdlog_errno(LOG_WARNING,
841218218Spjd		    "Unable to create outgoing connection to %s",
842218218Spjd		    res->hr_remoteaddr);
843218218Spjd		goto out;
844218218Spjd	}
845218218Spjd	if (proto_connect(conn, -1) < 0) {
846218218Spjd		val = errno;
847218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
848218218Spjd		    res->hr_remoteaddr);
849218218Spjd		proto_close(conn);
850218218Spjd		goto out;
851218218Spjd	}
852218218Spjd	val = 0;
853218218Spjdout:
854218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
855218218Spjd		pjdlog_errno(LOG_WARNING,
856218218Spjd		    "Unable to send reply to connection request");
857218218Spjd	}
858218218Spjd	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
859218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to send connection");
860218218Spjd}
861218218Spjd
862218218Spjdstatic void
863204076Spjdmain_loop(void)
864204076Spjd{
865212038Spjd	struct hast_resource *res;
866213009Spjd	struct timeval seltimeout;
867213009Spjd	struct timespec sigtimeout;
868213009Spjd	int fd, maxfd, ret, signo;
869213009Spjd	sigset_t mask;
870212037Spjd	fd_set rfds;
871204076Spjd
872213009Spjd	seltimeout.tv_sec = REPORT_INTERVAL;
873213009Spjd	seltimeout.tv_usec = 0;
874213009Spjd	sigtimeout.tv_sec = 0;
875213009Spjd	sigtimeout.tv_nsec = 0;
876211977Spjd
877213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
878213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
879213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
880213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
881213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
882213009Spjd
883216477Spjd	pjdlog_info("Started successfully, running protocol version %d.",
884216477Spjd	    HAST_PROTO_VERSION);
885216477Spjd
886204076Spjd	for (;;) {
887213009Spjd		while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
888213009Spjd			switch (signo) {
889213009Spjd			case SIGINT:
890213009Spjd			case SIGTERM:
891213009Spjd				sigexit_received = true;
892213009Spjd				terminate_workers();
893217967Spjd				proto_close(cfg->hc_controlconn);
894213009Spjd				exit(EX_OK);
895213009Spjd				break;
896213009Spjd			case SIGCHLD:
897213009Spjd				child_exit();
898213009Spjd				break;
899213009Spjd			case SIGHUP:
900213009Spjd				hastd_reload();
901213009Spjd				break;
902213009Spjd			default:
903218138Spjd				PJDLOG_ABORT("Unexpected signal (%d).", signo);
904213009Spjd			}
905211899Spjd		}
906204076Spjd
907209177Spjd		/* Setup descriptors for select(2). */
908204076Spjd		FD_ZERO(&rfds);
909212038Spjd		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
910218138Spjd		PJDLOG_ASSERT(fd >= 0);
911212038Spjd		FD_SET(fd, &rfds);
912212038Spjd		fd = proto_descriptor(cfg->hc_listenconn);
913218138Spjd		PJDLOG_ASSERT(fd >= 0);
914212038Spjd		FD_SET(fd, &rfds);
915212038Spjd		maxfd = fd > maxfd ? fd : maxfd;
916212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
917212038Spjd			if (res->hr_event == NULL)
918212038Spjd				continue;
919218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
920212038Spjd			fd = proto_descriptor(res->hr_event);
921218138Spjd			PJDLOG_ASSERT(fd >= 0);
922212038Spjd			FD_SET(fd, &rfds);
923212038Spjd			maxfd = fd > maxfd ? fd : maxfd;
924218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
925218218Spjd				/* Only primary workers asks for connections. */
926218218Spjd				fd = proto_descriptor(res->hr_conn);
927218218Spjd				PJDLOG_ASSERT(fd >= 0);
928218218Spjd				FD_SET(fd, &rfds);
929218218Spjd				maxfd = fd > maxfd ? fd : maxfd;
930218218Spjd			}
931212038Spjd		}
932204076Spjd
933218138Spjd		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
934213009Spjd		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
935211977Spjd		if (ret == 0)
936213429Spjd			hook_check();
937211977Spjd		else if (ret == -1) {
938204076Spjd			if (errno == EINTR)
939204076Spjd				continue;
940204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
941204076Spjd			pjdlog_exit(EX_OSERR, "select() failed");
942204076Spjd		}
943204076Spjd
944212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
945204076Spjd			control_handle(cfg);
946212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
947204076Spjd			listen_accept();
948212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
949212038Spjd			if (res->hr_event == NULL)
950212038Spjd				continue;
951218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
952212038Spjd			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
953212038Spjd				if (event_recv(res) == 0)
954212038Spjd					continue;
955212038Spjd				/* The worker process exited? */
956212038Spjd				proto_close(res->hr_event);
957212038Spjd				res->hr_event = NULL;
958218218Spjd				proto_close(res->hr_conn);
959218218Spjd				res->hr_conn = NULL;
960218218Spjd				continue;
961212038Spjd			}
962218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY &&
963218218Spjd			    FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) {
964218218Spjd				connection_migrate(res);
965218218Spjd			}
966212038Spjd		}
967204076Spjd	}
968204076Spjd}
969204076Spjd
970213428Spjdstatic void
971213428Spjddummy_sighandler(int sig __unused)
972213428Spjd{
973213428Spjd	/* Nothing to do. */
974213428Spjd}
975213428Spjd
976204076Spjdint
977204076Spjdmain(int argc, char *argv[])
978204076Spjd{
979204076Spjd	const char *pidfile;
980204076Spjd	pid_t otherpid;
981204076Spjd	bool foreground;
982204076Spjd	int debuglevel;
983213009Spjd	sigset_t mask;
984204076Spjd
985204076Spjd	foreground = false;
986204076Spjd	debuglevel = 0;
987204076Spjd	pidfile = HASTD_PIDFILE;
988204076Spjd
989204076Spjd	for (;;) {
990204076Spjd		int ch;
991204076Spjd
992204076Spjd		ch = getopt(argc, argv, "c:dFhP:");
993204076Spjd		if (ch == -1)
994204076Spjd			break;
995204076Spjd		switch (ch) {
996204076Spjd		case 'c':
997204076Spjd			cfgpath = optarg;
998204076Spjd			break;
999204076Spjd		case 'd':
1000204076Spjd			debuglevel++;
1001204076Spjd			break;
1002204076Spjd		case 'F':
1003204076Spjd			foreground = true;
1004204076Spjd			break;
1005204076Spjd		case 'P':
1006204076Spjd			pidfile = optarg;
1007204076Spjd			break;
1008204076Spjd		case 'h':
1009204076Spjd		default:
1010204076Spjd			usage();
1011204076Spjd		}
1012204076Spjd	}
1013204076Spjd	argc -= optind;
1014204076Spjd	argv += optind;
1015204076Spjd
1016217965Spjd	pjdlog_init(PJDLOG_MODE_STD);
1017204076Spjd	pjdlog_debug_set(debuglevel);
1018204076Spjd
1019214273Spjd	g_gate_load();
1020214273Spjd
1021204076Spjd	pfh = pidfile_open(pidfile, 0600, &otherpid);
1022204076Spjd	if (pfh == NULL) {
1023204076Spjd		if (errno == EEXIST) {
1024204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
1025204076Spjd			    "Another hastd is already running, pid: %jd.",
1026204076Spjd			    (intmax_t)otherpid);
1027204076Spjd		}
1028204076Spjd		/* If we cannot create pidfile from other reasons, only warn. */
1029210879Spjd		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1030204076Spjd	}
1031204076Spjd
1032210883Spjd	cfg = yy_config_parse(cfgpath, true);
1033218138Spjd	PJDLOG_ASSERT(cfg != NULL);
1034204076Spjd
1035213428Spjd	/*
1036217307Spjd	 * Restore default actions for interesting signals in case parent
1037217307Spjd	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1038217307Spjd	 */
1039217307Spjd	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1040217307Spjd	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1041217307Spjd	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1042217307Spjd	/*
1043213428Spjd	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1044213428Spjd	 * so we can mask it.
1045213428Spjd	 */
1046213428Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1047217307Spjd
1048213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1049213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1050213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1051213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1052213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1053213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1054204076Spjd
1055204076Spjd	/* Listen on control address. */
1056204076Spjd	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1057204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1058204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1059204076Spjd		    cfg->hc_controladdr);
1060204076Spjd	}
1061204076Spjd	/* Listen for remote connections. */
1062204076Spjd	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1063204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1064204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1065204076Spjd		    cfg->hc_listenaddr);
1066204076Spjd	}
1067204076Spjd
1068204076Spjd	if (!foreground) {
1069204076Spjd		if (daemon(0, 0) < 0) {
1070204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1071204076Spjd			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1072204076Spjd		}
1073204076Spjd
1074204076Spjd		/* Start logging to syslog. */
1075204076Spjd		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1076204076Spjd
1077204076Spjd		/* Write PID to a file. */
1078204076Spjd		if (pidfile_write(pfh) < 0) {
1079204076Spjd			pjdlog_errno(LOG_WARNING,
1080204076Spjd			    "Unable to write PID to a file");
1081204076Spjd		}
1082204076Spjd	}
1083204076Spjd
1084211977Spjd	hook_init();
1085211977Spjd
1086204076Spjd	main_loop();
1087204076Spjd
1088204076Spjd	exit(0);
1089204076Spjd}
1090