hastd.c revision 219864
1204076Spjd/*-
2204076Spjd * Copyright (c) 2009-2010 The FreeBSD Foundation
3219351Spjd * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
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 219864 2011-03-22 10:39:34Z 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>
49219813Spjd#include <time.h>
50204076Spjd#include <unistd.h>
51204076Spjd
52204076Spjd#include <activemap.h>
53204076Spjd#include <pjdlog.h>
54204076Spjd
55204076Spjd#include "control.h"
56212038Spjd#include "event.h"
57204076Spjd#include "hast.h"
58204076Spjd#include "hast_proto.h"
59204076Spjd#include "hastd.h"
60211977Spjd#include "hooks.h"
61204076Spjd#include "subr.h"
62204076Spjd
63204076Spjd/* Path to configuration file. */
64210886Spjdconst char *cfgpath = HAST_CONFIG;
65204076Spjd/* Hastd configuration. */
66204076Spjdstatic struct hastd_config *cfg;
67204076Spjd/* Was SIGINT or SIGTERM signal received? */
68204076Spjdbool sigexit_received = false;
69204076Spjd/* PID file handle. */
70204076Spjdstruct pidfh *pfh;
71204076Spjd
72211977Spjd/* How often check for hooks running for too long. */
73213430Spjd#define	REPORT_INTERVAL	5
74211977Spjd
75204076Spjdstatic void
76204076Spjdusage(void)
77204076Spjd{
78204076Spjd
79204076Spjd	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
80204076Spjd}
81204076Spjd
82204076Spjdstatic void
83204076Spjdg_gate_load(void)
84204076Spjd{
85204076Spjd
86204076Spjd	if (modfind("g_gate") == -1) {
87204076Spjd		/* Not present in kernel, try loading it. */
88204076Spjd		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
89204076Spjd			if (errno != EEXIST) {
90204076Spjd				pjdlog_exit(EX_OSERR,
91204076Spjd				    "Unable to load geom_gate module");
92204076Spjd			}
93204076Spjd		}
94204076Spjd	}
95204076Spjd}
96204076Spjd
97218041Spjdvoid
98218041Spjddescriptors_cleanup(struct hast_resource *res)
99218041Spjd{
100218041Spjd	struct hast_resource *tres;
101218041Spjd
102218041Spjd	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
103218041Spjd		if (tres == res) {
104218041Spjd			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
105218041Spjd			    (res->hr_remotein == NULL &&
106218041Spjd			     res->hr_remoteout == NULL));
107218041Spjd			continue;
108218041Spjd		}
109218041Spjd		if (tres->hr_remotein != NULL)
110218041Spjd			proto_close(tres->hr_remotein);
111218041Spjd		if (tres->hr_remoteout != NULL)
112218041Spjd			proto_close(tres->hr_remoteout);
113218370Spjd		if (tres->hr_ctrl != NULL)
114218370Spjd			proto_close(tres->hr_ctrl);
115218370Spjd		if (tres->hr_event != NULL)
116218370Spjd			proto_close(tres->hr_event);
117218370Spjd		if (tres->hr_conn != NULL)
118218370Spjd			proto_close(tres->hr_conn);
119218041Spjd	}
120218041Spjd	if (cfg->hc_controlin != NULL)
121218041Spjd		proto_close(cfg->hc_controlin);
122218041Spjd	proto_close(cfg->hc_controlconn);
123218041Spjd	proto_close(cfg->hc_listenconn);
124218041Spjd	(void)pidfile_close(pfh);
125218041Spjd	hook_fini();
126218041Spjd	pjdlog_fini();
127218041Spjd}
128218041Spjd
129218044Spjdstatic const char *
130218044Spjddtype2str(mode_t mode)
131218044Spjd{
132218044Spjd
133218044Spjd	if (S_ISBLK(mode))
134218044Spjd		return ("block device");
135219864Spjd	else if (S_ISCHR(mode))
136218044Spjd		return ("character device");
137219864Spjd	else if (S_ISDIR(mode))
138218044Spjd		return ("directory");
139218044Spjd	else if (S_ISFIFO(mode))
140218044Spjd		return ("pipe or FIFO");
141219864Spjd	else if (S_ISLNK(mode))
142218044Spjd		return ("symbolic link");
143219864Spjd	else if (S_ISREG(mode))
144218044Spjd		return ("regular file");
145218044Spjd	else if (S_ISSOCK(mode))
146218044Spjd		return ("socket");
147219864Spjd	else if (S_ISWHT(mode))
148218044Spjd		return ("whiteout");
149218044Spjd	else
150218044Spjd		return ("unknown");
151218044Spjd}
152218044Spjd
153218044Spjdvoid
154218044Spjddescriptors_assert(const struct hast_resource *res, int pjdlogmode)
155218044Spjd{
156218044Spjd	char msg[256];
157218044Spjd	struct stat sb;
158218044Spjd	long maxfd;
159218044Spjd	bool isopen;
160218044Spjd	mode_t mode;
161218044Spjd	int fd;
162218044Spjd
163218044Spjd	/*
164218044Spjd	 * At this point descriptor to syslog socket is closed, so if we want
165218044Spjd	 * to log assertion message, we have to first store it in 'msg' local
166218044Spjd	 * buffer and then open syslog socket and log it.
167218044Spjd	 */
168218044Spjd	msg[0] = '\0';
169218044Spjd
170218044Spjd	maxfd = sysconf(_SC_OPEN_MAX);
171218044Spjd	if (maxfd < 0) {
172218373Spjd		pjdlog_init(pjdlogmode);
173218373Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
174218373Spjd		    role2str(res->hr_role));
175218044Spjd		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
176218373Spjd		pjdlog_fini();
177218044Spjd		maxfd = 16384;
178218044Spjd	}
179218044Spjd	for (fd = 0; fd <= maxfd; fd++) {
180218044Spjd		if (fstat(fd, &sb) == 0) {
181218044Spjd			isopen = true;
182218044Spjd			mode = sb.st_mode;
183218044Spjd		} else if (errno == EBADF) {
184218044Spjd			isopen = false;
185218044Spjd			mode = 0;
186218044Spjd		} else {
187218375Spjd			(void)snprintf(msg, sizeof(msg),
188218044Spjd			    "Unable to fstat descriptor %d: %s", fd,
189218044Spjd			    strerror(errno));
190218374Spjd			break;
191218044Spjd		}
192218044Spjd		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
193218044Spjd		    fd == STDERR_FILENO) {
194218044Spjd			if (!isopen) {
195218375Spjd				(void)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) {
203218375Spjd				(void)snprintf(msg, sizeof(msg),
204218044Spjd				    "Descriptor %d (event) is closed, but should be open.",
205218044Spjd				    fd);
206218044Spjd				break;
207218044Spjd			}
208218044Spjd			if (!S_ISSOCK(mode)) {
209218375Spjd				(void)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) {
216218375Spjd				(void)snprintf(msg, sizeof(msg),
217218044Spjd				    "Descriptor %d (ctrl) is closed, but should be open.",
218218044Spjd				    fd);
219218044Spjd				break;
220218044Spjd			}
221218044Spjd			if (!S_ISSOCK(mode)) {
222218375Spjd				(void)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) {
229218375Spjd				(void)snprintf(msg, sizeof(msg),
230218218Spjd				    "Descriptor %d (conn) is closed, but should be open.",
231218218Spjd				    fd);
232218218Spjd				break;
233218218Spjd			}
234218218Spjd			if (!S_ISSOCK(mode)) {
235218375Spjd				(void)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) {
243218375Spjd				(void)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)) {
249218375Spjd				(void)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) {
257218375Spjd				(void)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)) {
263218375Spjd				(void)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) {
270218375Spjd				(void)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);
363219818Spjd		if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
364219818Spjd			return (true);
365210886Spjd		if (res0->hr_replication != res1->hr_replication)
366210886Spjd			return (true);
367219351Spjd		if (res0->hr_checksum != res1->hr_checksum)
368219351Spjd			return (true);
369219354Spjd		if (res0->hr_compression != res1->hr_compression)
370219354Spjd			return (true);
371210886Spjd		if (res0->hr_timeout != res1->hr_timeout)
372210886Spjd			return (true);
373211886Spjd		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
374211886Spjd			return (true);
375210886Spjd	}
376210886Spjd	return (false);
377210886Spjd}
378210886Spjd
379210886Spjdstatic bool
380210886Spjdresource_needs_reload(const struct hast_resource *res0,
381210886Spjd    const struct hast_resource *res1)
382210886Spjd{
383210886Spjd
384218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
385218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
386218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
387210886Spjd
388210886Spjd	if (res0->hr_role != HAST_ROLE_PRIMARY)
389210886Spjd		return (false);
390210886Spjd
391210886Spjd	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
392210886Spjd		return (true);
393219818Spjd	if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
394219818Spjd		return (true);
395210886Spjd	if (res0->hr_replication != res1->hr_replication)
396210886Spjd		return (true);
397219351Spjd	if (res0->hr_checksum != res1->hr_checksum)
398219351Spjd		return (true);
399219354Spjd	if (res0->hr_compression != res1->hr_compression)
400219354Spjd		return (true);
401210886Spjd	if (res0->hr_timeout != res1->hr_timeout)
402210886Spjd		return (true);
403211886Spjd	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
404211886Spjd		return (true);
405210886Spjd	return (false);
406210886Spjd}
407210886Spjd
408204076Spjdstatic void
409217784Spjdresource_reload(const struct hast_resource *res)
410217784Spjd{
411217784Spjd	struct nv *nvin, *nvout;
412217784Spjd	int error;
413217784Spjd
414218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
415217784Spjd
416217784Spjd	nvout = nv_alloc();
417217784Spjd	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
418217784Spjd	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
419219818Spjd	nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
420217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
421219351Spjd	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
422219354Spjd	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
423217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
424217784Spjd	nv_add_string(nvout, res->hr_exec, "exec");
425217784Spjd	if (nv_error(nvout) != 0) {
426217784Spjd		nv_free(nvout);
427217784Spjd		pjdlog_error("Unable to allocate header for reload message.");
428217784Spjd		return;
429217784Spjd	}
430217784Spjd	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
431217784Spjd		pjdlog_errno(LOG_ERR, "Unable to send reload message");
432217784Spjd		nv_free(nvout);
433217784Spjd		return;
434217784Spjd	}
435217784Spjd	nv_free(nvout);
436217784Spjd
437217784Spjd	/* Receive response. */
438217784Spjd	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
439217784Spjd		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
440217784Spjd		return;
441217784Spjd	}
442217784Spjd	error = nv_get_int16(nvin, "error");
443217784Spjd	nv_free(nvin);
444217784Spjd	if (error != 0) {
445217784Spjd		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
446217784Spjd		return;
447217784Spjd	}
448217784Spjd}
449217784Spjd
450217784Spjdstatic void
451204076Spjdhastd_reload(void)
452204076Spjd{
453210886Spjd	struct hastd_config *newcfg;
454210886Spjd	struct hast_resource *nres, *cres, *tres;
455210886Spjd	uint8_t role;
456204076Spjd
457210886Spjd	pjdlog_info("Reloading configuration...");
458210886Spjd
459210886Spjd	newcfg = yy_config_parse(cfgpath, false);
460210886Spjd	if (newcfg == NULL)
461210886Spjd		goto failed;
462210886Spjd
463210886Spjd	/*
464210886Spjd	 * Check if control address has changed.
465210886Spjd	 */
466210886Spjd	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
467210886Spjd		if (proto_server(newcfg->hc_controladdr,
468210886Spjd		    &newcfg->hc_controlconn) < 0) {
469210886Spjd			pjdlog_errno(LOG_ERR,
470210886Spjd			    "Unable to listen on control address %s",
471210886Spjd			    newcfg->hc_controladdr);
472210886Spjd			goto failed;
473210886Spjd		}
474210886Spjd	}
475210886Spjd	/*
476210886Spjd	 * Check if listen address has changed.
477210886Spjd	 */
478210886Spjd	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
479210886Spjd		if (proto_server(newcfg->hc_listenaddr,
480210886Spjd		    &newcfg->hc_listenconn) < 0) {
481210886Spjd			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
482210886Spjd			    newcfg->hc_listenaddr);
483210886Spjd			goto failed;
484210886Spjd		}
485210886Spjd	}
486210886Spjd	/*
487210886Spjd	 * Only when both control and listen sockets are successfully
488210886Spjd	 * initialized switch them to new configuration.
489210886Spjd	 */
490210886Spjd	if (newcfg->hc_controlconn != NULL) {
491210886Spjd		pjdlog_info("Control socket changed from %s to %s.",
492210886Spjd		    cfg->hc_controladdr, newcfg->hc_controladdr);
493210886Spjd		proto_close(cfg->hc_controlconn);
494210886Spjd		cfg->hc_controlconn = newcfg->hc_controlconn;
495210886Spjd		newcfg->hc_controlconn = NULL;
496210886Spjd		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
497210886Spjd		    sizeof(cfg->hc_controladdr));
498210886Spjd	}
499210886Spjd	if (newcfg->hc_listenconn != NULL) {
500210886Spjd		pjdlog_info("Listen socket changed from %s to %s.",
501210886Spjd		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
502210886Spjd		proto_close(cfg->hc_listenconn);
503210886Spjd		cfg->hc_listenconn = newcfg->hc_listenconn;
504210886Spjd		newcfg->hc_listenconn = NULL;
505210886Spjd		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
506210886Spjd		    sizeof(cfg->hc_listenaddr));
507210886Spjd	}
508210886Spjd
509210886Spjd	/*
510210886Spjd	 * Stop and remove resources that were removed from the configuration.
511210886Spjd	 */
512210886Spjd	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
513210886Spjd		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
514210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
515210886Spjd				break;
516210886Spjd		}
517210886Spjd		if (nres == NULL) {
518210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
519210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
520210886Spjd			pjdlog_info("Resource %s removed.", cres->hr_name);
521210886Spjd			free(cres);
522210886Spjd		}
523210886Spjd	}
524210886Spjd	/*
525210886Spjd	 * Move new resources to the current configuration.
526210886Spjd	 */
527210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
528210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
529210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
530210886Spjd				break;
531210886Spjd		}
532210886Spjd		if (cres == NULL) {
533210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
534210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
535210886Spjd			pjdlog_info("Resource %s added.", nres->hr_name);
536210886Spjd		}
537210886Spjd	}
538210886Spjd	/*
539210886Spjd	 * Deal with modified resources.
540210886Spjd	 * Depending on what has changed exactly we might want to perform
541210886Spjd	 * different actions.
542210886Spjd	 *
543210886Spjd	 * We do full resource restart in the following situations:
544210886Spjd	 * Resource role is INIT or SECONDARY.
545210886Spjd	 * Resource role is PRIMARY and path to local component or provider
546210886Spjd	 * name has changed.
547210886Spjd	 * In case of PRIMARY, the worker process will be killed and restarted,
548210886Spjd	 * which also means removing /dev/hast/<name> provider and
549210886Spjd	 * recreating it.
550210886Spjd	 *
551210886Spjd	 * We do just reload (send SIGHUP to worker process) if we act as
552217729Spjd	 * PRIMARY, but only if remote address, replication mode, timeout or
553217729Spjd	 * execution path has changed. For those, there is no need to restart
554217729Spjd	 * worker process.
555210886Spjd	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
556210886Spjd	 * replication mode has changed or simply set new timeout if only
557210886Spjd	 * timeout has changed.
558210886Spjd	 */
559210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
560210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
561210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
562210886Spjd				break;
563210886Spjd		}
564218138Spjd		PJDLOG_ASSERT(cres != NULL);
565210886Spjd		if (resource_needs_restart(cres, nres)) {
566210886Spjd			pjdlog_info("Resource %s configuration was modified, restarting it.",
567210886Spjd			    cres->hr_name);
568210886Spjd			role = cres->hr_role;
569210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
570210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
571210886Spjd			free(cres);
572210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
573210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
574210886Spjd			control_set_role(nres, role);
575210886Spjd		} else if (resource_needs_reload(cres, nres)) {
576210886Spjd			pjdlog_info("Resource %s configuration was modified, reloading it.",
577210886Spjd			    cres->hr_name);
578210886Spjd			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
579210886Spjd			    sizeof(cres->hr_remoteaddr));
580219818Spjd			strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
581219818Spjd			    sizeof(cres->hr_sourceaddr));
582210886Spjd			cres->hr_replication = nres->hr_replication;
583219351Spjd			cres->hr_checksum = nres->hr_checksum;
584219354Spjd			cres->hr_compression = nres->hr_compression;
585210886Spjd			cres->hr_timeout = nres->hr_timeout;
586217729Spjd			strlcpy(cres->hr_exec, nres->hr_exec,
587217729Spjd			    sizeof(cres->hr_exec));
588217784Spjd			if (cres->hr_workerpid != 0)
589217784Spjd				resource_reload(cres);
590210886Spjd		}
591210886Spjd	}
592210886Spjd
593210886Spjd	yy_config_free(newcfg);
594210886Spjd	pjdlog_info("Configuration reloaded successfully.");
595210886Spjd	return;
596210886Spjdfailed:
597210886Spjd	if (newcfg != NULL) {
598210886Spjd		if (newcfg->hc_controlconn != NULL)
599210886Spjd			proto_close(newcfg->hc_controlconn);
600210886Spjd		if (newcfg->hc_listenconn != NULL)
601210886Spjd			proto_close(newcfg->hc_listenconn);
602210886Spjd		yy_config_free(newcfg);
603210886Spjd	}
604210886Spjd	pjdlog_warning("Configuration not reloaded.");
605204076Spjd}
606204076Spjd
607204076Spjdstatic void
608211899Spjdterminate_workers(void)
609211899Spjd{
610211899Spjd	struct hast_resource *res;
611211899Spjd
612211899Spjd	pjdlog_info("Termination signal received, exiting.");
613211899Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
614211899Spjd		if (res->hr_workerpid == 0)
615211899Spjd			continue;
616211899Spjd		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
617211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
618211899Spjd		if (kill(res->hr_workerpid, SIGTERM) == 0)
619211899Spjd			continue;
620211899Spjd		pjdlog_errno(LOG_WARNING,
621211899Spjd		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
622211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
623211899Spjd	}
624211899Spjd}
625211899Spjd
626211899Spjdstatic void
627204076Spjdlisten_accept(void)
628204076Spjd{
629204076Spjd	struct hast_resource *res;
630204076Spjd	struct proto_conn *conn;
631204076Spjd	struct nv *nvin, *nvout, *nverr;
632204076Spjd	const char *resname;
633204076Spjd	const unsigned char *token;
634204076Spjd	char laddr[256], raddr[256];
635204076Spjd	size_t size;
636204076Spjd	pid_t pid;
637204076Spjd	int status;
638204076Spjd
639204076Spjd	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
640204076Spjd	pjdlog_debug(1, "Accepting connection to %s.", laddr);
641204076Spjd
642204076Spjd	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
643204076Spjd		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
644204076Spjd		return;
645204076Spjd	}
646204076Spjd
647204076Spjd	proto_local_address(conn, laddr, sizeof(laddr));
648204076Spjd	proto_remote_address(conn, raddr, sizeof(raddr));
649209185Spjd	pjdlog_info("Connection from %s to %s.", raddr, laddr);
650204076Spjd
651207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
652207371Spjd	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
653207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
654207371Spjd
655204076Spjd	nvin = nvout = nverr = NULL;
656204076Spjd
657204076Spjd	/*
658204076Spjd	 * Before receiving any data see if remote host have access to any
659204076Spjd	 * resource.
660204076Spjd	 */
661204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
662204076Spjd		if (proto_address_match(conn, res->hr_remoteaddr))
663204076Spjd			break;
664204076Spjd	}
665204076Spjd	if (res == NULL) {
666204076Spjd		pjdlog_error("Client %s isn't known.", raddr);
667204076Spjd		goto close;
668204076Spjd	}
669204076Spjd	/* Ok, remote host can access at least one resource. */
670204076Spjd
671204076Spjd	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
672204076Spjd		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
673204076Spjd		    raddr);
674204076Spjd		goto close;
675204076Spjd	}
676204076Spjd
677204076Spjd	resname = nv_get_string(nvin, "resource");
678204076Spjd	if (resname == NULL) {
679204076Spjd		pjdlog_error("No 'resource' field in the header received from %s.",
680204076Spjd		    raddr);
681204076Spjd		goto close;
682204076Spjd	}
683204076Spjd	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
684204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
685204076Spjd	/*
686204076Spjd	 * NULL token means that this is first conection.
687204076Spjd	 */
688204076Spjd	if (token != NULL && size != sizeof(res->hr_token)) {
689204076Spjd		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
690204076Spjd		    raddr, sizeof(res->hr_token), size);
691204076Spjd		goto close;
692204076Spjd	}
693204076Spjd
694204076Spjd	/*
695204076Spjd	 * From now on we want to send errors to the remote node.
696204076Spjd	 */
697204076Spjd	nverr = nv_alloc();
698204076Spjd
699204076Spjd	/* Find resource related to this connection. */
700204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
701204076Spjd		if (strcmp(resname, res->hr_name) == 0)
702204076Spjd			break;
703204076Spjd	}
704204076Spjd	/* Have we found the resource? */
705204076Spjd	if (res == NULL) {
706204076Spjd		pjdlog_error("No resource '%s' as requested by %s.",
707204076Spjd		    resname, raddr);
708204076Spjd		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
709204076Spjd		goto fail;
710204076Spjd	}
711204076Spjd
712204076Spjd	/* Now that we know resource name setup log prefix. */
713204076Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
714204076Spjd
715204076Spjd	/* Does the remote host have access to this resource? */
716204076Spjd	if (!proto_address_match(conn, res->hr_remoteaddr)) {
717204076Spjd		pjdlog_error("Client %s has no access to the resource.", raddr);
718204076Spjd		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
719204076Spjd		goto fail;
720204076Spjd	}
721204076Spjd	/* Is the resource marked as secondary? */
722204076Spjd	if (res->hr_role != HAST_ROLE_SECONDARY) {
723204076Spjd		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
724204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
725204076Spjd		    raddr);
726204076Spjd		nv_add_stringf(nverr, "errmsg",
727204076Spjd		    "Remote node acts as %s for the resource and not as %s.",
728204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
729204076Spjd		goto fail;
730204076Spjd	}
731204076Spjd	/* Does token (if exists) match? */
732204076Spjd	if (token != NULL && memcmp(token, res->hr_token,
733204076Spjd	    sizeof(res->hr_token)) != 0) {
734204076Spjd		pjdlog_error("Token received from %s doesn't match.", raddr);
735209185Spjd		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
736204076Spjd		goto fail;
737204076Spjd	}
738204076Spjd	/*
739204076Spjd	 * If there is no token, but we have half-open connection
740204076Spjd	 * (only remotein) or full connection (worker process is running)
741204076Spjd	 * we have to cancel those and accept the new connection.
742204076Spjd	 */
743204076Spjd	if (token == NULL) {
744218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
745204076Spjd		pjdlog_debug(1, "Initial connection from %s.", raddr);
746204076Spjd		if (res->hr_workerpid != 0) {
747218138Spjd			PJDLOG_ASSERT(res->hr_remotein == NULL);
748204076Spjd			pjdlog_debug(1,
749204076Spjd			    "Worker process exists (pid=%u), stopping it.",
750204076Spjd			    (unsigned int)res->hr_workerpid);
751204076Spjd			/* Stop child process. */
752204076Spjd			if (kill(res->hr_workerpid, SIGINT) < 0) {
753204076Spjd				pjdlog_errno(LOG_ERR,
754204076Spjd				    "Unable to stop worker process (pid=%u)",
755204076Spjd				    (unsigned int)res->hr_workerpid);
756204076Spjd				/*
757204076Spjd				 * Other than logging the problem we
758204076Spjd				 * ignore it - nothing smart to do.
759204076Spjd				 */
760204076Spjd			}
761204076Spjd			/* Wait for it to exit. */
762204076Spjd			else if ((pid = waitpid(res->hr_workerpid,
763204076Spjd			    &status, 0)) != res->hr_workerpid) {
764207372Spjd				/* We can only log the problem. */
765204076Spjd				pjdlog_errno(LOG_ERR,
766204076Spjd				    "Waiting for worker process (pid=%u) failed",
767204076Spjd				    (unsigned int)res->hr_workerpid);
768204076Spjd			} else {
769207372Spjd				child_exit_log(res->hr_workerpid, status);
770204076Spjd			}
771213006Spjd			child_cleanup(res);
772204076Spjd		} else if (res->hr_remotein != NULL) {
773204076Spjd			char oaddr[256];
774204076Spjd
775213981Spjd			proto_remote_address(res->hr_remotein, oaddr,
776213981Spjd			    sizeof(oaddr));
777204076Spjd			pjdlog_debug(1,
778204076Spjd			    "Canceling half-open connection from %s on connection from %s.",
779204076Spjd			    oaddr, raddr);
780204076Spjd			proto_close(res->hr_remotein);
781204076Spjd			res->hr_remotein = NULL;
782204076Spjd		}
783204076Spjd	}
784204076Spjd
785204076Spjd	/*
786204076Spjd	 * Checks and cleanups are done.
787204076Spjd	 */
788204076Spjd
789204076Spjd	if (token == NULL) {
790204076Spjd		arc4random_buf(res->hr_token, sizeof(res->hr_token));
791204076Spjd		nvout = nv_alloc();
792204076Spjd		nv_add_uint8_array(nvout, res->hr_token,
793204076Spjd		    sizeof(res->hr_token), "token");
794204076Spjd		if (nv_error(nvout) != 0) {
795204076Spjd			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
796204076Spjd			    "Unable to prepare return header for %s", raddr);
797204076Spjd			nv_add_stringf(nverr, "errmsg",
798204076Spjd			    "Remote node was unable to prepare return header: %s.",
799204076Spjd			    strerror(nv_error(nvout)));
800204076Spjd			goto fail;
801204076Spjd		}
802204076Spjd		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
803204076Spjd			int error = errno;
804204076Spjd
805204076Spjd			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
806204076Spjd			    raddr);
807204076Spjd			nv_add_stringf(nverr, "errmsg",
808204076Spjd			    "Remote node was unable to send response: %s.",
809204076Spjd			    strerror(error));
810204076Spjd			goto fail;
811204076Spjd		}
812204076Spjd		res->hr_remotein = conn;
813204076Spjd		pjdlog_debug(1, "Incoming connection from %s configured.",
814204076Spjd		    raddr);
815204076Spjd	} else {
816204076Spjd		res->hr_remoteout = conn;
817204076Spjd		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
818204076Spjd		hastd_secondary(res, nvin);
819204076Spjd	}
820204076Spjd	nv_free(nvin);
821204076Spjd	nv_free(nvout);
822204076Spjd	nv_free(nverr);
823204076Spjd	pjdlog_prefix_set("%s", "");
824204076Spjd	return;
825204076Spjdfail:
826204076Spjd	if (nv_error(nverr) != 0) {
827204076Spjd		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
828204076Spjd		    "Unable to prepare error header for %s", raddr);
829204076Spjd		goto close;
830204076Spjd	}
831204076Spjd	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
832204076Spjd		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
833204076Spjd		goto close;
834204076Spjd	}
835204076Spjdclose:
836204076Spjd	if (nvin != NULL)
837204076Spjd		nv_free(nvin);
838204076Spjd	if (nvout != NULL)
839204076Spjd		nv_free(nvout);
840204076Spjd	if (nverr != NULL)
841204076Spjd		nv_free(nverr);
842204076Spjd	proto_close(conn);
843204076Spjd	pjdlog_prefix_set("%s", "");
844204076Spjd}
845204076Spjd
846204076Spjdstatic void
847218218Spjdconnection_migrate(struct hast_resource *res)
848218218Spjd{
849218218Spjd	struct proto_conn *conn;
850218218Spjd	int16_t val = 0;
851218218Spjd
852219814Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
853219814Spjd
854218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
855218218Spjd		pjdlog_errno(LOG_WARNING,
856218218Spjd		    "Unable to receive connection command");
857218218Spjd		return;
858218218Spjd	}
859219818Spjd	if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
860219818Spjd	    res->hr_remoteaddr, &conn) < 0) {
861218218Spjd		val = errno;
862218218Spjd		pjdlog_errno(LOG_WARNING,
863218218Spjd		    "Unable to create outgoing connection to %s",
864218218Spjd		    res->hr_remoteaddr);
865218218Spjd		goto out;
866218218Spjd	}
867218218Spjd	if (proto_connect(conn, -1) < 0) {
868218218Spjd		val = errno;
869218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
870218218Spjd		    res->hr_remoteaddr);
871218218Spjd		proto_close(conn);
872218218Spjd		goto out;
873218218Spjd	}
874218218Spjd	val = 0;
875218218Spjdout:
876218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
877218218Spjd		pjdlog_errno(LOG_WARNING,
878218218Spjd		    "Unable to send reply to connection request");
879218218Spjd	}
880218218Spjd	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
881218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to send connection");
882219814Spjd
883219814Spjd	pjdlog_prefix_set("%s", "");
884218218Spjd}
885218218Spjd
886218218Spjdstatic void
887219837Spjdcheck_signals(void)
888204076Spjd{
889213009Spjd	struct timespec sigtimeout;
890213009Spjd	sigset_t mask;
891219837Spjd	int signo;
892204076Spjd
893213009Spjd	sigtimeout.tv_sec = 0;
894213009Spjd	sigtimeout.tv_nsec = 0;
895211977Spjd
896213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
897213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
898213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
899213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
900213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
901213009Spjd
902219837Spjd	while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
903219837Spjd		switch (signo) {
904219837Spjd		case SIGINT:
905219837Spjd		case SIGTERM:
906219837Spjd			sigexit_received = true;
907219837Spjd			terminate_workers();
908219837Spjd			proto_close(cfg->hc_controlconn);
909219837Spjd			exit(EX_OK);
910219837Spjd			break;
911219837Spjd		case SIGCHLD:
912219837Spjd			child_exit();
913219837Spjd			break;
914219837Spjd		case SIGHUP:
915219837Spjd			hastd_reload();
916219837Spjd			break;
917219837Spjd		default:
918219837Spjd			PJDLOG_ABORT("Unexpected signal (%d).", signo);
919219837Spjd		}
920219837Spjd	}
921219837Spjd}
922219837Spjd
923219837Spjdstatic void
924219837Spjdmain_loop(void)
925219837Spjd{
926219837Spjd	struct hast_resource *res;
927219837Spjd	struct timeval seltimeout;
928219837Spjd	int fd, maxfd, ret;
929219837Spjd	time_t lastcheck, now;
930219837Spjd	fd_set rfds;
931219837Spjd
932219864Spjd	lastcheck = time(NULL);
933219837Spjd	seltimeout.tv_sec = REPORT_INTERVAL;
934219837Spjd	seltimeout.tv_usec = 0;
935219837Spjd
936216477Spjd	pjdlog_info("Started successfully, running protocol version %d.",
937216477Spjd	    HAST_PROTO_VERSION);
938216477Spjd
939204076Spjd	for (;;) {
940219837Spjd		check_signals();
941204076Spjd
942209177Spjd		/* Setup descriptors for select(2). */
943204076Spjd		FD_ZERO(&rfds);
944212038Spjd		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
945218138Spjd		PJDLOG_ASSERT(fd >= 0);
946212038Spjd		FD_SET(fd, &rfds);
947212038Spjd		fd = proto_descriptor(cfg->hc_listenconn);
948218138Spjd		PJDLOG_ASSERT(fd >= 0);
949212038Spjd		FD_SET(fd, &rfds);
950212038Spjd		maxfd = fd > maxfd ? fd : maxfd;
951212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
952212038Spjd			if (res->hr_event == NULL)
953212038Spjd				continue;
954218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
955212038Spjd			fd = proto_descriptor(res->hr_event);
956218138Spjd			PJDLOG_ASSERT(fd >= 0);
957212038Spjd			FD_SET(fd, &rfds);
958212038Spjd			maxfd = fd > maxfd ? fd : maxfd;
959218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
960218218Spjd				/* Only primary workers asks for connections. */
961218218Spjd				fd = proto_descriptor(res->hr_conn);
962218218Spjd				PJDLOG_ASSERT(fd >= 0);
963218218Spjd				FD_SET(fd, &rfds);
964218218Spjd				maxfd = fd > maxfd ? fd : maxfd;
965218218Spjd			}
966212038Spjd		}
967204076Spjd
968218138Spjd		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
969213009Spjd		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
970219813Spjd		now = time(NULL);
971219813Spjd		if (lastcheck + REPORT_INTERVAL <= now) {
972213429Spjd			hook_check();
973219813Spjd			lastcheck = now;
974219813Spjd		}
975219813Spjd		if (ret == 0) {
976219813Spjd			/*
977219813Spjd			 * select(2) timed out, so there should be no
978219813Spjd			 * descriptors to check.
979219813Spjd			 */
980219813Spjd			continue;
981219813Spjd		} else if (ret == -1) {
982204076Spjd			if (errno == EINTR)
983204076Spjd				continue;
984204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
985204076Spjd			pjdlog_exit(EX_OSERR, "select() failed");
986204076Spjd		}
987204076Spjd
988219837Spjd		/*
989219837Spjd		 * Check for signals before we do anything to update our
990219837Spjd		 * info about terminated workers in the meantime.
991219837Spjd		 */
992219837Spjd		check_signals();
993219837Spjd
994212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
995204076Spjd			control_handle(cfg);
996212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
997204076Spjd			listen_accept();
998212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
999212038Spjd			if (res->hr_event == NULL)
1000212038Spjd				continue;
1001218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
1002212038Spjd			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1003212038Spjd				if (event_recv(res) == 0)
1004212038Spjd					continue;
1005212038Spjd				/* The worker process exited? */
1006212038Spjd				proto_close(res->hr_event);
1007212038Spjd				res->hr_event = NULL;
1008218218Spjd				proto_close(res->hr_conn);
1009218218Spjd				res->hr_conn = NULL;
1010218218Spjd				continue;
1011212038Spjd			}
1012218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY &&
1013218218Spjd			    FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) {
1014218218Spjd				connection_migrate(res);
1015218218Spjd			}
1016212038Spjd		}
1017204076Spjd	}
1018204076Spjd}
1019204076Spjd
1020213428Spjdstatic void
1021213428Spjddummy_sighandler(int sig __unused)
1022213428Spjd{
1023213428Spjd	/* Nothing to do. */
1024213428Spjd}
1025213428Spjd
1026204076Spjdint
1027204076Spjdmain(int argc, char *argv[])
1028204076Spjd{
1029204076Spjd	const char *pidfile;
1030204076Spjd	pid_t otherpid;
1031204076Spjd	bool foreground;
1032204076Spjd	int debuglevel;
1033213009Spjd	sigset_t mask;
1034204076Spjd
1035204076Spjd	foreground = false;
1036204076Spjd	debuglevel = 0;
1037204076Spjd	pidfile = HASTD_PIDFILE;
1038204076Spjd
1039204076Spjd	for (;;) {
1040204076Spjd		int ch;
1041204076Spjd
1042204076Spjd		ch = getopt(argc, argv, "c:dFhP:");
1043204076Spjd		if (ch == -1)
1044204076Spjd			break;
1045204076Spjd		switch (ch) {
1046204076Spjd		case 'c':
1047204076Spjd			cfgpath = optarg;
1048204076Spjd			break;
1049204076Spjd		case 'd':
1050204076Spjd			debuglevel++;
1051204076Spjd			break;
1052204076Spjd		case 'F':
1053204076Spjd			foreground = true;
1054204076Spjd			break;
1055204076Spjd		case 'P':
1056204076Spjd			pidfile = optarg;
1057204076Spjd			break;
1058204076Spjd		case 'h':
1059204076Spjd		default:
1060204076Spjd			usage();
1061204076Spjd		}
1062204076Spjd	}
1063204076Spjd	argc -= optind;
1064204076Spjd	argv += optind;
1065204076Spjd
1066217965Spjd	pjdlog_init(PJDLOG_MODE_STD);
1067204076Spjd	pjdlog_debug_set(debuglevel);
1068204076Spjd
1069214273Spjd	g_gate_load();
1070214273Spjd
1071204076Spjd	pfh = pidfile_open(pidfile, 0600, &otherpid);
1072204076Spjd	if (pfh == NULL) {
1073204076Spjd		if (errno == EEXIST) {
1074204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
1075204076Spjd			    "Another hastd is already running, pid: %jd.",
1076204076Spjd			    (intmax_t)otherpid);
1077204076Spjd		}
1078204076Spjd		/* If we cannot create pidfile from other reasons, only warn. */
1079210879Spjd		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1080204076Spjd	}
1081204076Spjd
1082210883Spjd	cfg = yy_config_parse(cfgpath, true);
1083218138Spjd	PJDLOG_ASSERT(cfg != NULL);
1084204076Spjd
1085213428Spjd	/*
1086217307Spjd	 * Restore default actions for interesting signals in case parent
1087217307Spjd	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1088217307Spjd	 */
1089217307Spjd	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1090217307Spjd	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1091217307Spjd	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1092217307Spjd	/*
1093213428Spjd	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1094213428Spjd	 * so we can mask it.
1095213428Spjd	 */
1096213428Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1097217307Spjd
1098213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1099213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1100213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1101213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1102213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1103213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1104204076Spjd
1105204076Spjd	/* Listen on control address. */
1106204076Spjd	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1107204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1108204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1109204076Spjd		    cfg->hc_controladdr);
1110204076Spjd	}
1111204076Spjd	/* Listen for remote connections. */
1112204076Spjd	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1113204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1114204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1115204076Spjd		    cfg->hc_listenaddr);
1116204076Spjd	}
1117204076Spjd
1118204076Spjd	if (!foreground) {
1119204076Spjd		if (daemon(0, 0) < 0) {
1120204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1121204076Spjd			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1122204076Spjd		}
1123204076Spjd
1124204076Spjd		/* Start logging to syslog. */
1125204076Spjd		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1126204076Spjd
1127204076Spjd		/* Write PID to a file. */
1128204076Spjd		if (pidfile_write(pfh) < 0) {
1129204076Spjd			pjdlog_errno(LOG_WARNING,
1130204076Spjd			    "Unable to write PID to a file");
1131204076Spjd		}
1132204076Spjd	}
1133204076Spjd
1134211977Spjd	hook_init();
1135211977Spjd
1136204076Spjd	main_loop();
1137204076Spjd
1138204076Spjd	exit(0);
1139204076Spjd}
1140