hastd.c revision 218374
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 218374 2011-02-06 14:07:58Z 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));
191218374Spjd			break;
192218044Spjd		}
193218044Spjd		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
194218044Spjd		    fd == STDERR_FILENO) {
195218044Spjd			if (!isopen) {
196218044Spjd				snprintf(msg, sizeof(msg),
197218044Spjd				    "Descriptor %d (%s) is closed, but should be open.",
198218044Spjd				    fd, (fd == STDIN_FILENO ? "stdin" :
199218044Spjd				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
200218044Spjd				break;
201218044Spjd			}
202218044Spjd		} else if (fd == proto_descriptor(res->hr_event)) {
203218044Spjd			if (!isopen) {
204218044Spjd				snprintf(msg, sizeof(msg),
205218044Spjd				    "Descriptor %d (event) is closed, but should be open.",
206218044Spjd				    fd);
207218044Spjd				break;
208218044Spjd			}
209218044Spjd			if (!S_ISSOCK(mode)) {
210218044Spjd				snprintf(msg, sizeof(msg),
211218044Spjd				    "Descriptor %d (event) is %s, but should be %s.",
212218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
213218044Spjd				break;
214218044Spjd			}
215218044Spjd		} else if (fd == proto_descriptor(res->hr_ctrl)) {
216218044Spjd			if (!isopen) {
217218044Spjd				snprintf(msg, sizeof(msg),
218218044Spjd				    "Descriptor %d (ctrl) is closed, but should be open.",
219218044Spjd				    fd);
220218044Spjd				break;
221218044Spjd			}
222218044Spjd			if (!S_ISSOCK(mode)) {
223218044Spjd				snprintf(msg, sizeof(msg),
224218044Spjd				    "Descriptor %d (ctrl) is %s, but should be %s.",
225218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
226218044Spjd				break;
227218044Spjd			}
228218218Spjd		} else if (fd == proto_descriptor(res->hr_conn)) {
229218218Spjd			if (!isopen) {
230218218Spjd				snprintf(msg, sizeof(msg),
231218218Spjd				    "Descriptor %d (conn) is closed, but should be open.",
232218218Spjd				    fd);
233218218Spjd				break;
234218218Spjd			}
235218218Spjd			if (!S_ISSOCK(mode)) {
236218218Spjd				snprintf(msg, sizeof(msg),
237218218Spjd				    "Descriptor %d (conn) is %s, but should be %s.",
238218218Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
239218218Spjd				break;
240218218Spjd			}
241218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
242218044Spjd		    fd == proto_descriptor(res->hr_remotein)) {
243218044Spjd			if (!isopen) {
244218044Spjd				snprintf(msg, sizeof(msg),
245218044Spjd				    "Descriptor %d (remote in) is closed, but should be open.",
246218044Spjd				    fd);
247218044Spjd				break;
248218044Spjd			}
249218044Spjd			if (!S_ISSOCK(mode)) {
250218044Spjd				snprintf(msg, sizeof(msg),
251218044Spjd				    "Descriptor %d (remote in) is %s, but should be %s.",
252218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
253218044Spjd				break;
254218044Spjd			}
255218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
256218044Spjd		    fd == proto_descriptor(res->hr_remoteout)) {
257218044Spjd			if (!isopen) {
258218044Spjd				snprintf(msg, sizeof(msg),
259218044Spjd				    "Descriptor %d (remote out) is closed, but should be open.",
260218044Spjd				    fd);
261218044Spjd				break;
262218044Spjd			}
263218044Spjd			if (!S_ISSOCK(mode)) {
264218044Spjd				snprintf(msg, sizeof(msg),
265218044Spjd				    "Descriptor %d (remote out) is %s, but should be %s.",
266218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
267218044Spjd				break;
268218044Spjd			}
269218044Spjd		} else {
270218044Spjd			if (isopen) {
271218044Spjd				snprintf(msg, sizeof(msg),
272218044Spjd				    "Descriptor %d is open (%s), but should be closed.",
273218044Spjd				    fd, dtype2str(mode));
274218044Spjd				break;
275218044Spjd			}
276218044Spjd		}
277218044Spjd	}
278218044Spjd	if (msg[0] != '\0') {
279218044Spjd		pjdlog_init(pjdlogmode);
280218044Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
281218044Spjd		    role2str(res->hr_role));
282218044Spjd		PJDLOG_ABORT("%s", msg);
283218044Spjd	}
284218044Spjd}
285218044Spjd
286204076Spjdstatic void
287207372Spjdchild_exit_log(unsigned int pid, int status)
288207372Spjd{
289207372Spjd
290207372Spjd	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
291207372Spjd		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
292207372Spjd		    pid);
293207372Spjd	} else if (WIFSIGNALED(status)) {
294207372Spjd		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
295207372Spjd		    pid, WTERMSIG(status));
296207372Spjd	} else {
297207372Spjd		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
298207372Spjd		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
299207372Spjd	}
300207372Spjd}
301207372Spjd
302207372Spjdstatic void
303204076Spjdchild_exit(void)
304204076Spjd{
305204076Spjd	struct hast_resource *res;
306204076Spjd	int status;
307204076Spjd	pid_t pid;
308204076Spjd
309204076Spjd	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
310204076Spjd		/* Find resource related to the process that just exited. */
311204076Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
312204076Spjd			if (pid == res->hr_workerpid)
313204076Spjd				break;
314204076Spjd		}
315204076Spjd		if (res == NULL) {
316204076Spjd			/*
317204076Spjd			 * This can happen when new connection arrives and we
318211977Spjd			 * cancel child responsible for the old one or if this
319211977Spjd			 * was hook which we executed.
320204076Spjd			 */
321211977Spjd			hook_check_one(pid, status);
322204076Spjd			continue;
323204076Spjd		}
324204076Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
325204076Spjd		    role2str(res->hr_role));
326207372Spjd		child_exit_log(pid, status);
327213006Spjd		child_cleanup(res);
328204076Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
329207372Spjd			/*
330207372Spjd			 * Restart child process if it was killed by signal
331207372Spjd			 * or exited because of temporary problem.
332207372Spjd			 */
333207372Spjd			if (WIFSIGNALED(status) ||
334207372Spjd			    (WIFEXITED(status) &&
335207372Spjd			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
336207348Spjd				sleep(1);
337207348Spjd				pjdlog_info("Restarting worker process.");
338207348Spjd				hastd_primary(res);
339207348Spjd			} else {
340207348Spjd				res->hr_role = HAST_ROLE_INIT;
341207348Spjd				pjdlog_info("Changing resource role back to %s.",
342207348Spjd				    role2str(res->hr_role));
343207348Spjd			}
344204076Spjd		}
345204076Spjd		pjdlog_prefix_set("%s", "");
346204076Spjd	}
347204076Spjd}
348204076Spjd
349210886Spjdstatic bool
350210886Spjdresource_needs_restart(const struct hast_resource *res0,
351210886Spjd    const struct hast_resource *res1)
352210886Spjd{
353210886Spjd
354218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
355210886Spjd
356210886Spjd	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
357210886Spjd		return (true);
358210886Spjd	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
359210886Spjd		return (true);
360210886Spjd	if (res0->hr_role == HAST_ROLE_INIT ||
361210886Spjd	    res0->hr_role == HAST_ROLE_SECONDARY) {
362210886Spjd		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
363210886Spjd			return (true);
364210886Spjd		if (res0->hr_replication != res1->hr_replication)
365210886Spjd			return (true);
366210886Spjd		if (res0->hr_timeout != res1->hr_timeout)
367210886Spjd			return (true);
368211886Spjd		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
369211886Spjd			return (true);
370210886Spjd	}
371210886Spjd	return (false);
372210886Spjd}
373210886Spjd
374210886Spjdstatic bool
375210886Spjdresource_needs_reload(const struct hast_resource *res0,
376210886Spjd    const struct hast_resource *res1)
377210886Spjd{
378210886Spjd
379218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
380218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
381218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
382210886Spjd
383210886Spjd	if (res0->hr_role != HAST_ROLE_PRIMARY)
384210886Spjd		return (false);
385210886Spjd
386210886Spjd	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
387210886Spjd		return (true);
388210886Spjd	if (res0->hr_replication != res1->hr_replication)
389210886Spjd		return (true);
390210886Spjd	if (res0->hr_timeout != res1->hr_timeout)
391210886Spjd		return (true);
392211886Spjd	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
393211886Spjd		return (true);
394210886Spjd	return (false);
395210886Spjd}
396210886Spjd
397204076Spjdstatic void
398217784Spjdresource_reload(const struct hast_resource *res)
399217784Spjd{
400217784Spjd	struct nv *nvin, *nvout;
401217784Spjd	int error;
402217784Spjd
403218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
404217784Spjd
405217784Spjd	nvout = nv_alloc();
406217784Spjd	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
407217784Spjd	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
408217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
409217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
410217784Spjd	nv_add_string(nvout, res->hr_exec, "exec");
411217784Spjd	if (nv_error(nvout) != 0) {
412217784Spjd		nv_free(nvout);
413217784Spjd		pjdlog_error("Unable to allocate header for reload message.");
414217784Spjd		return;
415217784Spjd	}
416217784Spjd	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
417217784Spjd		pjdlog_errno(LOG_ERR, "Unable to send reload message");
418217784Spjd		nv_free(nvout);
419217784Spjd		return;
420217784Spjd	}
421217784Spjd	nv_free(nvout);
422217784Spjd
423217784Spjd	/* Receive response. */
424217784Spjd	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
425217784Spjd		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
426217784Spjd		return;
427217784Spjd	}
428217784Spjd	error = nv_get_int16(nvin, "error");
429217784Spjd	nv_free(nvin);
430217784Spjd	if (error != 0) {
431217784Spjd		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
432217784Spjd		return;
433217784Spjd	}
434217784Spjd}
435217784Spjd
436217784Spjdstatic void
437204076Spjdhastd_reload(void)
438204076Spjd{
439210886Spjd	struct hastd_config *newcfg;
440210886Spjd	struct hast_resource *nres, *cres, *tres;
441210886Spjd	uint8_t role;
442204076Spjd
443210886Spjd	pjdlog_info("Reloading configuration...");
444210886Spjd
445210886Spjd	newcfg = yy_config_parse(cfgpath, false);
446210886Spjd	if (newcfg == NULL)
447210886Spjd		goto failed;
448210886Spjd
449210886Spjd	/*
450210886Spjd	 * Check if control address has changed.
451210886Spjd	 */
452210886Spjd	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
453210886Spjd		if (proto_server(newcfg->hc_controladdr,
454210886Spjd		    &newcfg->hc_controlconn) < 0) {
455210886Spjd			pjdlog_errno(LOG_ERR,
456210886Spjd			    "Unable to listen on control address %s",
457210886Spjd			    newcfg->hc_controladdr);
458210886Spjd			goto failed;
459210886Spjd		}
460210886Spjd	}
461210886Spjd	/*
462210886Spjd	 * Check if listen address has changed.
463210886Spjd	 */
464210886Spjd	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
465210886Spjd		if (proto_server(newcfg->hc_listenaddr,
466210886Spjd		    &newcfg->hc_listenconn) < 0) {
467210886Spjd			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
468210886Spjd			    newcfg->hc_listenaddr);
469210886Spjd			goto failed;
470210886Spjd		}
471210886Spjd	}
472210886Spjd	/*
473210886Spjd	 * Only when both control and listen sockets are successfully
474210886Spjd	 * initialized switch them to new configuration.
475210886Spjd	 */
476210886Spjd	if (newcfg->hc_controlconn != NULL) {
477210886Spjd		pjdlog_info("Control socket changed from %s to %s.",
478210886Spjd		    cfg->hc_controladdr, newcfg->hc_controladdr);
479210886Spjd		proto_close(cfg->hc_controlconn);
480210886Spjd		cfg->hc_controlconn = newcfg->hc_controlconn;
481210886Spjd		newcfg->hc_controlconn = NULL;
482210886Spjd		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
483210886Spjd		    sizeof(cfg->hc_controladdr));
484210886Spjd	}
485210886Spjd	if (newcfg->hc_listenconn != NULL) {
486210886Spjd		pjdlog_info("Listen socket changed from %s to %s.",
487210886Spjd		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
488210886Spjd		proto_close(cfg->hc_listenconn);
489210886Spjd		cfg->hc_listenconn = newcfg->hc_listenconn;
490210886Spjd		newcfg->hc_listenconn = NULL;
491210886Spjd		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
492210886Spjd		    sizeof(cfg->hc_listenaddr));
493210886Spjd	}
494210886Spjd
495210886Spjd	/*
496210886Spjd	 * Stop and remove resources that were removed from the configuration.
497210886Spjd	 */
498210886Spjd	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
499210886Spjd		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
500210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
501210886Spjd				break;
502210886Spjd		}
503210886Spjd		if (nres == NULL) {
504210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
505210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
506210886Spjd			pjdlog_info("Resource %s removed.", cres->hr_name);
507210886Spjd			free(cres);
508210886Spjd		}
509210886Spjd	}
510210886Spjd	/*
511210886Spjd	 * Move new resources to the current configuration.
512210886Spjd	 */
513210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
514210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
515210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
516210886Spjd				break;
517210886Spjd		}
518210886Spjd		if (cres == NULL) {
519210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
520210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
521210886Spjd			pjdlog_info("Resource %s added.", nres->hr_name);
522210886Spjd		}
523210886Spjd	}
524210886Spjd	/*
525210886Spjd	 * Deal with modified resources.
526210886Spjd	 * Depending on what has changed exactly we might want to perform
527210886Spjd	 * different actions.
528210886Spjd	 *
529210886Spjd	 * We do full resource restart in the following situations:
530210886Spjd	 * Resource role is INIT or SECONDARY.
531210886Spjd	 * Resource role is PRIMARY and path to local component or provider
532210886Spjd	 * name has changed.
533210886Spjd	 * In case of PRIMARY, the worker process will be killed and restarted,
534210886Spjd	 * which also means removing /dev/hast/<name> provider and
535210886Spjd	 * recreating it.
536210886Spjd	 *
537210886Spjd	 * We do just reload (send SIGHUP to worker process) if we act as
538217729Spjd	 * PRIMARY, but only if remote address, replication mode, timeout or
539217729Spjd	 * execution path has changed. For those, there is no need to restart
540217729Spjd	 * worker process.
541210886Spjd	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
542210886Spjd	 * replication mode has changed or simply set new timeout if only
543210886Spjd	 * timeout has changed.
544210886Spjd	 */
545210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
546210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
547210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
548210886Spjd				break;
549210886Spjd		}
550218138Spjd		PJDLOG_ASSERT(cres != NULL);
551210886Spjd		if (resource_needs_restart(cres, nres)) {
552210886Spjd			pjdlog_info("Resource %s configuration was modified, restarting it.",
553210886Spjd			    cres->hr_name);
554210886Spjd			role = cres->hr_role;
555210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
556210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
557210886Spjd			free(cres);
558210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
559210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
560210886Spjd			control_set_role(nres, role);
561210886Spjd		} else if (resource_needs_reload(cres, nres)) {
562210886Spjd			pjdlog_info("Resource %s configuration was modified, reloading it.",
563210886Spjd			    cres->hr_name);
564210886Spjd			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
565210886Spjd			    sizeof(cres->hr_remoteaddr));
566210886Spjd			cres->hr_replication = nres->hr_replication;
567210886Spjd			cres->hr_timeout = nres->hr_timeout;
568217729Spjd			strlcpy(cres->hr_exec, nres->hr_exec,
569217729Spjd			    sizeof(cres->hr_exec));
570217784Spjd			if (cres->hr_workerpid != 0)
571217784Spjd				resource_reload(cres);
572210886Spjd		}
573210886Spjd	}
574210886Spjd
575210886Spjd	yy_config_free(newcfg);
576210886Spjd	pjdlog_info("Configuration reloaded successfully.");
577210886Spjd	return;
578210886Spjdfailed:
579210886Spjd	if (newcfg != NULL) {
580210886Spjd		if (newcfg->hc_controlconn != NULL)
581210886Spjd			proto_close(newcfg->hc_controlconn);
582210886Spjd		if (newcfg->hc_listenconn != NULL)
583210886Spjd			proto_close(newcfg->hc_listenconn);
584210886Spjd		yy_config_free(newcfg);
585210886Spjd	}
586210886Spjd	pjdlog_warning("Configuration not reloaded.");
587204076Spjd}
588204076Spjd
589204076Spjdstatic void
590211899Spjdterminate_workers(void)
591211899Spjd{
592211899Spjd	struct hast_resource *res;
593211899Spjd
594211899Spjd	pjdlog_info("Termination signal received, exiting.");
595211899Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
596211899Spjd		if (res->hr_workerpid == 0)
597211899Spjd			continue;
598211899Spjd		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
599211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
600211899Spjd		if (kill(res->hr_workerpid, SIGTERM) == 0)
601211899Spjd			continue;
602211899Spjd		pjdlog_errno(LOG_WARNING,
603211899Spjd		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
604211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
605211899Spjd	}
606211899Spjd}
607211899Spjd
608211899Spjdstatic void
609204076Spjdlisten_accept(void)
610204076Spjd{
611204076Spjd	struct hast_resource *res;
612204076Spjd	struct proto_conn *conn;
613204076Spjd	struct nv *nvin, *nvout, *nverr;
614204076Spjd	const char *resname;
615204076Spjd	const unsigned char *token;
616204076Spjd	char laddr[256], raddr[256];
617204076Spjd	size_t size;
618204076Spjd	pid_t pid;
619204076Spjd	int status;
620204076Spjd
621204076Spjd	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
622204076Spjd	pjdlog_debug(1, "Accepting connection to %s.", laddr);
623204076Spjd
624204076Spjd	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
625204076Spjd		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
626204076Spjd		return;
627204076Spjd	}
628204076Spjd
629204076Spjd	proto_local_address(conn, laddr, sizeof(laddr));
630204076Spjd	proto_remote_address(conn, raddr, sizeof(raddr));
631209185Spjd	pjdlog_info("Connection from %s to %s.", raddr, laddr);
632204076Spjd
633207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
634207371Spjd	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
635207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
636207371Spjd
637204076Spjd	nvin = nvout = nverr = NULL;
638204076Spjd
639204076Spjd	/*
640204076Spjd	 * Before receiving any data see if remote host have access to any
641204076Spjd	 * resource.
642204076Spjd	 */
643204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
644204076Spjd		if (proto_address_match(conn, res->hr_remoteaddr))
645204076Spjd			break;
646204076Spjd	}
647204076Spjd	if (res == NULL) {
648204076Spjd		pjdlog_error("Client %s isn't known.", raddr);
649204076Spjd		goto close;
650204076Spjd	}
651204076Spjd	/* Ok, remote host can access at least one resource. */
652204076Spjd
653204076Spjd	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
654204076Spjd		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
655204076Spjd		    raddr);
656204076Spjd		goto close;
657204076Spjd	}
658204076Spjd
659204076Spjd	resname = nv_get_string(nvin, "resource");
660204076Spjd	if (resname == NULL) {
661204076Spjd		pjdlog_error("No 'resource' field in the header received from %s.",
662204076Spjd		    raddr);
663204076Spjd		goto close;
664204076Spjd	}
665204076Spjd	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
666204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
667204076Spjd	/*
668204076Spjd	 * NULL token means that this is first conection.
669204076Spjd	 */
670204076Spjd	if (token != NULL && size != sizeof(res->hr_token)) {
671204076Spjd		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
672204076Spjd		    raddr, sizeof(res->hr_token), size);
673204076Spjd		goto close;
674204076Spjd	}
675204076Spjd
676204076Spjd	/*
677204076Spjd	 * From now on we want to send errors to the remote node.
678204076Spjd	 */
679204076Spjd	nverr = nv_alloc();
680204076Spjd
681204076Spjd	/* Find resource related to this connection. */
682204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
683204076Spjd		if (strcmp(resname, res->hr_name) == 0)
684204076Spjd			break;
685204076Spjd	}
686204076Spjd	/* Have we found the resource? */
687204076Spjd	if (res == NULL) {
688204076Spjd		pjdlog_error("No resource '%s' as requested by %s.",
689204076Spjd		    resname, raddr);
690204076Spjd		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
691204076Spjd		goto fail;
692204076Spjd	}
693204076Spjd
694204076Spjd	/* Now that we know resource name setup log prefix. */
695204076Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
696204076Spjd
697204076Spjd	/* Does the remote host have access to this resource? */
698204076Spjd	if (!proto_address_match(conn, res->hr_remoteaddr)) {
699204076Spjd		pjdlog_error("Client %s has no access to the resource.", raddr);
700204076Spjd		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
701204076Spjd		goto fail;
702204076Spjd	}
703204076Spjd	/* Is the resource marked as secondary? */
704204076Spjd	if (res->hr_role != HAST_ROLE_SECONDARY) {
705204076Spjd		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
706204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
707204076Spjd		    raddr);
708204076Spjd		nv_add_stringf(nverr, "errmsg",
709204076Spjd		    "Remote node acts as %s for the resource and not as %s.",
710204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
711204076Spjd		goto fail;
712204076Spjd	}
713204076Spjd	/* Does token (if exists) match? */
714204076Spjd	if (token != NULL && memcmp(token, res->hr_token,
715204076Spjd	    sizeof(res->hr_token)) != 0) {
716204076Spjd		pjdlog_error("Token received from %s doesn't match.", raddr);
717209185Spjd		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
718204076Spjd		goto fail;
719204076Spjd	}
720204076Spjd	/*
721204076Spjd	 * If there is no token, but we have half-open connection
722204076Spjd	 * (only remotein) or full connection (worker process is running)
723204076Spjd	 * we have to cancel those and accept the new connection.
724204076Spjd	 */
725204076Spjd	if (token == NULL) {
726218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
727204076Spjd		pjdlog_debug(1, "Initial connection from %s.", raddr);
728204076Spjd		if (res->hr_workerpid != 0) {
729218138Spjd			PJDLOG_ASSERT(res->hr_remotein == NULL);
730204076Spjd			pjdlog_debug(1,
731204076Spjd			    "Worker process exists (pid=%u), stopping it.",
732204076Spjd			    (unsigned int)res->hr_workerpid);
733204076Spjd			/* Stop child process. */
734204076Spjd			if (kill(res->hr_workerpid, SIGINT) < 0) {
735204076Spjd				pjdlog_errno(LOG_ERR,
736204076Spjd				    "Unable to stop worker process (pid=%u)",
737204076Spjd				    (unsigned int)res->hr_workerpid);
738204076Spjd				/*
739204076Spjd				 * Other than logging the problem we
740204076Spjd				 * ignore it - nothing smart to do.
741204076Spjd				 */
742204076Spjd			}
743204076Spjd			/* Wait for it to exit. */
744204076Spjd			else if ((pid = waitpid(res->hr_workerpid,
745204076Spjd			    &status, 0)) != res->hr_workerpid) {
746207372Spjd				/* We can only log the problem. */
747204076Spjd				pjdlog_errno(LOG_ERR,
748204076Spjd				    "Waiting for worker process (pid=%u) failed",
749204076Spjd				    (unsigned int)res->hr_workerpid);
750204076Spjd			} else {
751207372Spjd				child_exit_log(res->hr_workerpid, status);
752204076Spjd			}
753213006Spjd			child_cleanup(res);
754204076Spjd		} else if (res->hr_remotein != NULL) {
755204076Spjd			char oaddr[256];
756204076Spjd
757213981Spjd			proto_remote_address(res->hr_remotein, oaddr,
758213981Spjd			    sizeof(oaddr));
759204076Spjd			pjdlog_debug(1,
760204076Spjd			    "Canceling half-open connection from %s on connection from %s.",
761204076Spjd			    oaddr, raddr);
762204076Spjd			proto_close(res->hr_remotein);
763204076Spjd			res->hr_remotein = NULL;
764204076Spjd		}
765204076Spjd	}
766204076Spjd
767204076Spjd	/*
768204076Spjd	 * Checks and cleanups are done.
769204076Spjd	 */
770204076Spjd
771204076Spjd	if (token == NULL) {
772204076Spjd		arc4random_buf(res->hr_token, sizeof(res->hr_token));
773204076Spjd		nvout = nv_alloc();
774204076Spjd		nv_add_uint8_array(nvout, res->hr_token,
775204076Spjd		    sizeof(res->hr_token), "token");
776204076Spjd		if (nv_error(nvout) != 0) {
777204076Spjd			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
778204076Spjd			    "Unable to prepare return header for %s", raddr);
779204076Spjd			nv_add_stringf(nverr, "errmsg",
780204076Spjd			    "Remote node was unable to prepare return header: %s.",
781204076Spjd			    strerror(nv_error(nvout)));
782204076Spjd			goto fail;
783204076Spjd		}
784204076Spjd		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
785204076Spjd			int error = errno;
786204076Spjd
787204076Spjd			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
788204076Spjd			    raddr);
789204076Spjd			nv_add_stringf(nverr, "errmsg",
790204076Spjd			    "Remote node was unable to send response: %s.",
791204076Spjd			    strerror(error));
792204076Spjd			goto fail;
793204076Spjd		}
794204076Spjd		res->hr_remotein = conn;
795204076Spjd		pjdlog_debug(1, "Incoming connection from %s configured.",
796204076Spjd		    raddr);
797204076Spjd	} else {
798204076Spjd		res->hr_remoteout = conn;
799204076Spjd		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
800204076Spjd		hastd_secondary(res, nvin);
801204076Spjd	}
802204076Spjd	nv_free(nvin);
803204076Spjd	nv_free(nvout);
804204076Spjd	nv_free(nverr);
805204076Spjd	pjdlog_prefix_set("%s", "");
806204076Spjd	return;
807204076Spjdfail:
808204076Spjd	if (nv_error(nverr) != 0) {
809204076Spjd		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
810204076Spjd		    "Unable to prepare error header for %s", raddr);
811204076Spjd		goto close;
812204076Spjd	}
813204076Spjd	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
814204076Spjd		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
815204076Spjd		goto close;
816204076Spjd	}
817204076Spjdclose:
818204076Spjd	if (nvin != NULL)
819204076Spjd		nv_free(nvin);
820204076Spjd	if (nvout != NULL)
821204076Spjd		nv_free(nvout);
822204076Spjd	if (nverr != NULL)
823204076Spjd		nv_free(nverr);
824204076Spjd	proto_close(conn);
825204076Spjd	pjdlog_prefix_set("%s", "");
826204076Spjd}
827204076Spjd
828204076Spjdstatic void
829218218Spjdconnection_migrate(struct hast_resource *res)
830218218Spjd{
831218218Spjd	struct proto_conn *conn;
832218218Spjd	int16_t val = 0;
833218218Spjd
834218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
835218218Spjd		pjdlog_errno(LOG_WARNING,
836218218Spjd		    "Unable to receive connection command");
837218218Spjd		return;
838218218Spjd	}
839218218Spjd	if (proto_client(res->hr_remoteaddr, &conn) < 0) {
840218218Spjd		val = errno;
841218218Spjd		pjdlog_errno(LOG_WARNING,
842218218Spjd		    "Unable to create outgoing connection to %s",
843218218Spjd		    res->hr_remoteaddr);
844218218Spjd		goto out;
845218218Spjd	}
846218218Spjd	if (proto_connect(conn, -1) < 0) {
847218218Spjd		val = errno;
848218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
849218218Spjd		    res->hr_remoteaddr);
850218218Spjd		proto_close(conn);
851218218Spjd		goto out;
852218218Spjd	}
853218218Spjd	val = 0;
854218218Spjdout:
855218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
856218218Spjd		pjdlog_errno(LOG_WARNING,
857218218Spjd		    "Unable to send reply to connection request");
858218218Spjd	}
859218218Spjd	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
860218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to send connection");
861218218Spjd}
862218218Spjd
863218218Spjdstatic void
864204076Spjdmain_loop(void)
865204076Spjd{
866212038Spjd	struct hast_resource *res;
867213009Spjd	struct timeval seltimeout;
868213009Spjd	struct timespec sigtimeout;
869213009Spjd	int fd, maxfd, ret, signo;
870213009Spjd	sigset_t mask;
871212037Spjd	fd_set rfds;
872204076Spjd
873213009Spjd	seltimeout.tv_sec = REPORT_INTERVAL;
874213009Spjd	seltimeout.tv_usec = 0;
875213009Spjd	sigtimeout.tv_sec = 0;
876213009Spjd	sigtimeout.tv_nsec = 0;
877211977Spjd
878213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
879213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
880213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
881213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
882213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
883213009Spjd
884216477Spjd	pjdlog_info("Started successfully, running protocol version %d.",
885216477Spjd	    HAST_PROTO_VERSION);
886216477Spjd
887204076Spjd	for (;;) {
888213009Spjd		while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
889213009Spjd			switch (signo) {
890213009Spjd			case SIGINT:
891213009Spjd			case SIGTERM:
892213009Spjd				sigexit_received = true;
893213009Spjd				terminate_workers();
894217967Spjd				proto_close(cfg->hc_controlconn);
895213009Spjd				exit(EX_OK);
896213009Spjd				break;
897213009Spjd			case SIGCHLD:
898213009Spjd				child_exit();
899213009Spjd				break;
900213009Spjd			case SIGHUP:
901213009Spjd				hastd_reload();
902213009Spjd				break;
903213009Spjd			default:
904218138Spjd				PJDLOG_ABORT("Unexpected signal (%d).", signo);
905213009Spjd			}
906211899Spjd		}
907204076Spjd
908209177Spjd		/* Setup descriptors for select(2). */
909204076Spjd		FD_ZERO(&rfds);
910212038Spjd		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
911218138Spjd		PJDLOG_ASSERT(fd >= 0);
912212038Spjd		FD_SET(fd, &rfds);
913212038Spjd		fd = proto_descriptor(cfg->hc_listenconn);
914218138Spjd		PJDLOG_ASSERT(fd >= 0);
915212038Spjd		FD_SET(fd, &rfds);
916212038Spjd		maxfd = fd > maxfd ? fd : maxfd;
917212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
918212038Spjd			if (res->hr_event == NULL)
919212038Spjd				continue;
920218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
921212038Spjd			fd = proto_descriptor(res->hr_event);
922218138Spjd			PJDLOG_ASSERT(fd >= 0);
923212038Spjd			FD_SET(fd, &rfds);
924212038Spjd			maxfd = fd > maxfd ? fd : maxfd;
925218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
926218218Spjd				/* Only primary workers asks for connections. */
927218218Spjd				fd = proto_descriptor(res->hr_conn);
928218218Spjd				PJDLOG_ASSERT(fd >= 0);
929218218Spjd				FD_SET(fd, &rfds);
930218218Spjd				maxfd = fd > maxfd ? fd : maxfd;
931218218Spjd			}
932212038Spjd		}
933204076Spjd
934218138Spjd		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
935213009Spjd		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
936211977Spjd		if (ret == 0)
937213429Spjd			hook_check();
938211977Spjd		else if (ret == -1) {
939204076Spjd			if (errno == EINTR)
940204076Spjd				continue;
941204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
942204076Spjd			pjdlog_exit(EX_OSERR, "select() failed");
943204076Spjd		}
944204076Spjd
945212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
946204076Spjd			control_handle(cfg);
947212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
948204076Spjd			listen_accept();
949212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
950212038Spjd			if (res->hr_event == NULL)
951212038Spjd				continue;
952218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
953212038Spjd			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
954212038Spjd				if (event_recv(res) == 0)
955212038Spjd					continue;
956212038Spjd				/* The worker process exited? */
957212038Spjd				proto_close(res->hr_event);
958212038Spjd				res->hr_event = NULL;
959218218Spjd				proto_close(res->hr_conn);
960218218Spjd				res->hr_conn = NULL;
961218218Spjd				continue;
962212038Spjd			}
963218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY &&
964218218Spjd			    FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) {
965218218Spjd				connection_migrate(res);
966218218Spjd			}
967212038Spjd		}
968204076Spjd	}
969204076Spjd}
970204076Spjd
971213428Spjdstatic void
972213428Spjddummy_sighandler(int sig __unused)
973213428Spjd{
974213428Spjd	/* Nothing to do. */
975213428Spjd}
976213428Spjd
977204076Spjdint
978204076Spjdmain(int argc, char *argv[])
979204076Spjd{
980204076Spjd	const char *pidfile;
981204076Spjd	pid_t otherpid;
982204076Spjd	bool foreground;
983204076Spjd	int debuglevel;
984213009Spjd	sigset_t mask;
985204076Spjd
986204076Spjd	foreground = false;
987204076Spjd	debuglevel = 0;
988204076Spjd	pidfile = HASTD_PIDFILE;
989204076Spjd
990204076Spjd	for (;;) {
991204076Spjd		int ch;
992204076Spjd
993204076Spjd		ch = getopt(argc, argv, "c:dFhP:");
994204076Spjd		if (ch == -1)
995204076Spjd			break;
996204076Spjd		switch (ch) {
997204076Spjd		case 'c':
998204076Spjd			cfgpath = optarg;
999204076Spjd			break;
1000204076Spjd		case 'd':
1001204076Spjd			debuglevel++;
1002204076Spjd			break;
1003204076Spjd		case 'F':
1004204076Spjd			foreground = true;
1005204076Spjd			break;
1006204076Spjd		case 'P':
1007204076Spjd			pidfile = optarg;
1008204076Spjd			break;
1009204076Spjd		case 'h':
1010204076Spjd		default:
1011204076Spjd			usage();
1012204076Spjd		}
1013204076Spjd	}
1014204076Spjd	argc -= optind;
1015204076Spjd	argv += optind;
1016204076Spjd
1017217965Spjd	pjdlog_init(PJDLOG_MODE_STD);
1018204076Spjd	pjdlog_debug_set(debuglevel);
1019204076Spjd
1020214273Spjd	g_gate_load();
1021214273Spjd
1022204076Spjd	pfh = pidfile_open(pidfile, 0600, &otherpid);
1023204076Spjd	if (pfh == NULL) {
1024204076Spjd		if (errno == EEXIST) {
1025204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
1026204076Spjd			    "Another hastd is already running, pid: %jd.",
1027204076Spjd			    (intmax_t)otherpid);
1028204076Spjd		}
1029204076Spjd		/* If we cannot create pidfile from other reasons, only warn. */
1030210879Spjd		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1031204076Spjd	}
1032204076Spjd
1033210883Spjd	cfg = yy_config_parse(cfgpath, true);
1034218138Spjd	PJDLOG_ASSERT(cfg != NULL);
1035204076Spjd
1036213428Spjd	/*
1037217307Spjd	 * Restore default actions for interesting signals in case parent
1038217307Spjd	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1039217307Spjd	 */
1040217307Spjd	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1041217307Spjd	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1042217307Spjd	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1043217307Spjd	/*
1044213428Spjd	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1045213428Spjd	 * so we can mask it.
1046213428Spjd	 */
1047213428Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1048217307Spjd
1049213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1050213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1051213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1052213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1053213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1054213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1055204076Spjd
1056204076Spjd	/* Listen on control address. */
1057204076Spjd	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1058204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1059204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1060204076Spjd		    cfg->hc_controladdr);
1061204076Spjd	}
1062204076Spjd	/* Listen for remote connections. */
1063204076Spjd	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1064204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1065204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1066204076Spjd		    cfg->hc_listenaddr);
1067204076Spjd	}
1068204076Spjd
1069204076Spjd	if (!foreground) {
1070204076Spjd		if (daemon(0, 0) < 0) {
1071204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1072204076Spjd			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1073204076Spjd		}
1074204076Spjd
1075204076Spjd		/* Start logging to syslog. */
1076204076Spjd		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1077204076Spjd
1078204076Spjd		/* Write PID to a file. */
1079204076Spjd		if (pidfile_write(pfh) < 0) {
1080204076Spjd			pjdlog_errno(LOG_WARNING,
1081204076Spjd			    "Unable to write PID to a file");
1082204076Spjd		}
1083204076Spjd	}
1084204076Spjd
1085211977Spjd	hook_init();
1086211977Spjd
1087204076Spjd	main_loop();
1088204076Spjd
1089204076Spjd	exit(0);
1090204076Spjd}
1091