hastd.c revision 222108
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 222108 2011-05-19 23:18:42Z 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;
101222108Spjd	struct hastd_listen *lst;
102218041Spjd
103218041Spjd	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
104218041Spjd		if (tres == res) {
105218041Spjd			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
106218041Spjd			    (res->hr_remotein == NULL &&
107218041Spjd			     res->hr_remoteout == NULL));
108218041Spjd			continue;
109218041Spjd		}
110218041Spjd		if (tres->hr_remotein != NULL)
111218041Spjd			proto_close(tres->hr_remotein);
112218041Spjd		if (tres->hr_remoteout != NULL)
113218041Spjd			proto_close(tres->hr_remoteout);
114218370Spjd		if (tres->hr_ctrl != NULL)
115218370Spjd			proto_close(tres->hr_ctrl);
116218370Spjd		if (tres->hr_event != NULL)
117218370Spjd			proto_close(tres->hr_event);
118218370Spjd		if (tres->hr_conn != NULL)
119218370Spjd			proto_close(tres->hr_conn);
120218041Spjd	}
121218041Spjd	if (cfg->hc_controlin != NULL)
122218041Spjd		proto_close(cfg->hc_controlin);
123218041Spjd	proto_close(cfg->hc_controlconn);
124222108Spjd	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
125222108Spjd		if (lst->hl_conn != NULL)
126222108Spjd			proto_close(lst->hl_conn);
127222108Spjd	}
128218041Spjd	(void)pidfile_close(pfh);
129218041Spjd	hook_fini();
130218041Spjd	pjdlog_fini();
131218041Spjd}
132218041Spjd
133218044Spjdstatic const char *
134218044Spjddtype2str(mode_t mode)
135218044Spjd{
136218044Spjd
137218044Spjd	if (S_ISBLK(mode))
138218044Spjd		return ("block device");
139219864Spjd	else if (S_ISCHR(mode))
140218044Spjd		return ("character device");
141219864Spjd	else if (S_ISDIR(mode))
142218044Spjd		return ("directory");
143218044Spjd	else if (S_ISFIFO(mode))
144218044Spjd		return ("pipe or FIFO");
145219864Spjd	else if (S_ISLNK(mode))
146218044Spjd		return ("symbolic link");
147219864Spjd	else if (S_ISREG(mode))
148218044Spjd		return ("regular file");
149218044Spjd	else if (S_ISSOCK(mode))
150218044Spjd		return ("socket");
151219864Spjd	else if (S_ISWHT(mode))
152218044Spjd		return ("whiteout");
153218044Spjd	else
154218044Spjd		return ("unknown");
155218044Spjd}
156218044Spjd
157218044Spjdvoid
158218044Spjddescriptors_assert(const struct hast_resource *res, int pjdlogmode)
159218044Spjd{
160218044Spjd	char msg[256];
161218044Spjd	struct stat sb;
162218044Spjd	long maxfd;
163218044Spjd	bool isopen;
164218044Spjd	mode_t mode;
165218044Spjd	int fd;
166218044Spjd
167218044Spjd	/*
168218044Spjd	 * At this point descriptor to syslog socket is closed, so if we want
169218044Spjd	 * to log assertion message, we have to first store it in 'msg' local
170218044Spjd	 * buffer and then open syslog socket and log it.
171218044Spjd	 */
172218044Spjd	msg[0] = '\0';
173218044Spjd
174218044Spjd	maxfd = sysconf(_SC_OPEN_MAX);
175218044Spjd	if (maxfd < 0) {
176218373Spjd		pjdlog_init(pjdlogmode);
177218373Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
178218373Spjd		    role2str(res->hr_role));
179218044Spjd		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
180218373Spjd		pjdlog_fini();
181218044Spjd		maxfd = 16384;
182218044Spjd	}
183218044Spjd	for (fd = 0; fd <= maxfd; fd++) {
184218044Spjd		if (fstat(fd, &sb) == 0) {
185218044Spjd			isopen = true;
186218044Spjd			mode = sb.st_mode;
187218044Spjd		} else if (errno == EBADF) {
188218044Spjd			isopen = false;
189218044Spjd			mode = 0;
190218044Spjd		} else {
191218375Spjd			(void)snprintf(msg, sizeof(msg),
192218044Spjd			    "Unable to fstat descriptor %d: %s", fd,
193218044Spjd			    strerror(errno));
194218374Spjd			break;
195218044Spjd		}
196218044Spjd		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
197218044Spjd		    fd == STDERR_FILENO) {
198218044Spjd			if (!isopen) {
199218375Spjd				(void)snprintf(msg, sizeof(msg),
200218044Spjd				    "Descriptor %d (%s) is closed, but should be open.",
201218044Spjd				    fd, (fd == STDIN_FILENO ? "stdin" :
202218044Spjd				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
203218044Spjd				break;
204218044Spjd			}
205218044Spjd		} else if (fd == proto_descriptor(res->hr_event)) {
206218044Spjd			if (!isopen) {
207218375Spjd				(void)snprintf(msg, sizeof(msg),
208218044Spjd				    "Descriptor %d (event) is closed, but should be open.",
209218044Spjd				    fd);
210218044Spjd				break;
211218044Spjd			}
212218044Spjd			if (!S_ISSOCK(mode)) {
213218375Spjd				(void)snprintf(msg, sizeof(msg),
214218044Spjd				    "Descriptor %d (event) is %s, but should be %s.",
215218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
216218044Spjd				break;
217218044Spjd			}
218218044Spjd		} else if (fd == proto_descriptor(res->hr_ctrl)) {
219218044Spjd			if (!isopen) {
220218375Spjd				(void)snprintf(msg, sizeof(msg),
221218044Spjd				    "Descriptor %d (ctrl) is closed, but should be open.",
222218044Spjd				    fd);
223218044Spjd				break;
224218044Spjd			}
225218044Spjd			if (!S_ISSOCK(mode)) {
226218375Spjd				(void)snprintf(msg, sizeof(msg),
227218044Spjd				    "Descriptor %d (ctrl) is %s, but should be %s.",
228218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
229218044Spjd				break;
230218044Spjd			}
231219900Spjd		} else if (res->hr_role == HAST_ROLE_PRIMARY &&
232219900Spjd		    fd == proto_descriptor(res->hr_conn)) {
233218218Spjd			if (!isopen) {
234218375Spjd				(void)snprintf(msg, sizeof(msg),
235218218Spjd				    "Descriptor %d (conn) is closed, but should be open.",
236218218Spjd				    fd);
237218218Spjd				break;
238218218Spjd			}
239218218Spjd			if (!S_ISSOCK(mode)) {
240218375Spjd				(void)snprintf(msg, sizeof(msg),
241218218Spjd				    "Descriptor %d (conn) is %s, but should be %s.",
242218218Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
243218218Spjd				break;
244218218Spjd			}
245218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
246219900Spjd		    res->hr_conn != NULL &&
247219900Spjd		    fd == proto_descriptor(res->hr_conn)) {
248219900Spjd			if (isopen) {
249219900Spjd				(void)snprintf(msg, sizeof(msg),
250219900Spjd				    "Descriptor %d (conn) is open, but should be closed.",
251219900Spjd				    fd);
252219900Spjd				break;
253219900Spjd			}
254219900Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
255218044Spjd		    fd == proto_descriptor(res->hr_remotein)) {
256218044Spjd			if (!isopen) {
257218375Spjd				(void)snprintf(msg, sizeof(msg),
258218044Spjd				    "Descriptor %d (remote in) 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 in) is %s, but should be %s.",
265218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
266218044Spjd				break;
267218044Spjd			}
268218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
269218044Spjd		    fd == proto_descriptor(res->hr_remoteout)) {
270218044Spjd			if (!isopen) {
271218375Spjd				(void)snprintf(msg, sizeof(msg),
272218044Spjd				    "Descriptor %d (remote out) is closed, but should be open.",
273218044Spjd				    fd);
274218044Spjd				break;
275218044Spjd			}
276218044Spjd			if (!S_ISSOCK(mode)) {
277218375Spjd				(void)snprintf(msg, sizeof(msg),
278218044Spjd				    "Descriptor %d (remote out) is %s, but should be %s.",
279218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
280218044Spjd				break;
281218044Spjd			}
282218044Spjd		} else {
283218044Spjd			if (isopen) {
284218375Spjd				(void)snprintf(msg, sizeof(msg),
285218044Spjd				    "Descriptor %d is open (%s), but should be closed.",
286218044Spjd				    fd, dtype2str(mode));
287218044Spjd				break;
288218044Spjd			}
289218044Spjd		}
290218044Spjd	}
291218044Spjd	if (msg[0] != '\0') {
292218044Spjd		pjdlog_init(pjdlogmode);
293218044Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
294218044Spjd		    role2str(res->hr_role));
295218044Spjd		PJDLOG_ABORT("%s", msg);
296218044Spjd	}
297218044Spjd}
298218044Spjd
299204076Spjdstatic void
300207372Spjdchild_exit_log(unsigned int pid, int status)
301207372Spjd{
302207372Spjd
303207372Spjd	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
304207372Spjd		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
305207372Spjd		    pid);
306207372Spjd	} else if (WIFSIGNALED(status)) {
307207372Spjd		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
308207372Spjd		    pid, WTERMSIG(status));
309207372Spjd	} else {
310207372Spjd		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
311207372Spjd		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
312207372Spjd	}
313207372Spjd}
314207372Spjd
315207372Spjdstatic void
316204076Spjdchild_exit(void)
317204076Spjd{
318204076Spjd	struct hast_resource *res;
319204076Spjd	int status;
320204076Spjd	pid_t pid;
321204076Spjd
322204076Spjd	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
323204076Spjd		/* Find resource related to the process that just exited. */
324204076Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
325204076Spjd			if (pid == res->hr_workerpid)
326204076Spjd				break;
327204076Spjd		}
328204076Spjd		if (res == NULL) {
329204076Spjd			/*
330204076Spjd			 * This can happen when new connection arrives and we
331211977Spjd			 * cancel child responsible for the old one or if this
332211977Spjd			 * was hook which we executed.
333204076Spjd			 */
334211977Spjd			hook_check_one(pid, status);
335204076Spjd			continue;
336204076Spjd		}
337204076Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
338204076Spjd		    role2str(res->hr_role));
339207372Spjd		child_exit_log(pid, status);
340213006Spjd		child_cleanup(res);
341204076Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
342207372Spjd			/*
343207372Spjd			 * Restart child process if it was killed by signal
344207372Spjd			 * or exited because of temporary problem.
345207372Spjd			 */
346207372Spjd			if (WIFSIGNALED(status) ||
347207372Spjd			    (WIFEXITED(status) &&
348207372Spjd			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
349207348Spjd				sleep(1);
350207348Spjd				pjdlog_info("Restarting worker process.");
351207348Spjd				hastd_primary(res);
352207348Spjd			} else {
353207348Spjd				res->hr_role = HAST_ROLE_INIT;
354207348Spjd				pjdlog_info("Changing resource role back to %s.",
355207348Spjd				    role2str(res->hr_role));
356207348Spjd			}
357204076Spjd		}
358204076Spjd		pjdlog_prefix_set("%s", "");
359204076Spjd	}
360204076Spjd}
361204076Spjd
362210886Spjdstatic bool
363210886Spjdresource_needs_restart(const struct hast_resource *res0,
364210886Spjd    const struct hast_resource *res1)
365210886Spjd{
366210886Spjd
367218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
368210886Spjd
369210886Spjd	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
370210886Spjd		return (true);
371210886Spjd	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
372210886Spjd		return (true);
373210886Spjd	if (res0->hr_role == HAST_ROLE_INIT ||
374210886Spjd	    res0->hr_role == HAST_ROLE_SECONDARY) {
375210886Spjd		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
376210886Spjd			return (true);
377219818Spjd		if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
378219818Spjd			return (true);
379210886Spjd		if (res0->hr_replication != res1->hr_replication)
380210886Spjd			return (true);
381219351Spjd		if (res0->hr_checksum != res1->hr_checksum)
382219351Spjd			return (true);
383219354Spjd		if (res0->hr_compression != res1->hr_compression)
384219354Spjd			return (true);
385210886Spjd		if (res0->hr_timeout != res1->hr_timeout)
386210886Spjd			return (true);
387211886Spjd		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
388211886Spjd			return (true);
389210886Spjd	}
390210886Spjd	return (false);
391210886Spjd}
392210886Spjd
393210886Spjdstatic bool
394210886Spjdresource_needs_reload(const struct hast_resource *res0,
395210886Spjd    const struct hast_resource *res1)
396210886Spjd{
397210886Spjd
398218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
399218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
400218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
401210886Spjd
402210886Spjd	if (res0->hr_role != HAST_ROLE_PRIMARY)
403210886Spjd		return (false);
404210886Spjd
405210886Spjd	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
406210886Spjd		return (true);
407219818Spjd	if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
408219818Spjd		return (true);
409210886Spjd	if (res0->hr_replication != res1->hr_replication)
410210886Spjd		return (true);
411219351Spjd	if (res0->hr_checksum != res1->hr_checksum)
412219351Spjd		return (true);
413219354Spjd	if (res0->hr_compression != res1->hr_compression)
414219354Spjd		return (true);
415210886Spjd	if (res0->hr_timeout != res1->hr_timeout)
416210886Spjd		return (true);
417211886Spjd	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
418211886Spjd		return (true);
419210886Spjd	return (false);
420210886Spjd}
421210886Spjd
422204076Spjdstatic void
423217784Spjdresource_reload(const struct hast_resource *res)
424217784Spjd{
425217784Spjd	struct nv *nvin, *nvout;
426217784Spjd	int error;
427217784Spjd
428218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
429217784Spjd
430217784Spjd	nvout = nv_alloc();
431221076Strociny	nv_add_uint8(nvout, CONTROL_RELOAD, "cmd");
432217784Spjd	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
433219818Spjd	nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
434217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
435219351Spjd	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
436219354Spjd	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
437217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
438217784Spjd	nv_add_string(nvout, res->hr_exec, "exec");
439217784Spjd	if (nv_error(nvout) != 0) {
440217784Spjd		nv_free(nvout);
441217784Spjd		pjdlog_error("Unable to allocate header for reload message.");
442217784Spjd		return;
443217784Spjd	}
444217784Spjd	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
445217784Spjd		pjdlog_errno(LOG_ERR, "Unable to send reload message");
446217784Spjd		nv_free(nvout);
447217784Spjd		return;
448217784Spjd	}
449217784Spjd	nv_free(nvout);
450217784Spjd
451217784Spjd	/* Receive response. */
452217784Spjd	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
453217784Spjd		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
454217784Spjd		return;
455217784Spjd	}
456217784Spjd	error = nv_get_int16(nvin, "error");
457217784Spjd	nv_free(nvin);
458217784Spjd	if (error != 0) {
459217784Spjd		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
460217784Spjd		return;
461217784Spjd	}
462217784Spjd}
463217784Spjd
464217784Spjdstatic void
465204076Spjdhastd_reload(void)
466204076Spjd{
467210886Spjd	struct hastd_config *newcfg;
468210886Spjd	struct hast_resource *nres, *cres, *tres;
469222108Spjd	struct hastd_listen *nlst, *clst;
470222108Spjd	unsigned int nlisten;
471210886Spjd	uint8_t role;
472204076Spjd
473210886Spjd	pjdlog_info("Reloading configuration...");
474210886Spjd
475210886Spjd	newcfg = yy_config_parse(cfgpath, false);
476210886Spjd	if (newcfg == NULL)
477210886Spjd		goto failed;
478210886Spjd
479210886Spjd	/*
480210886Spjd	 * Check if control address has changed.
481210886Spjd	 */
482210886Spjd	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
483210886Spjd		if (proto_server(newcfg->hc_controladdr,
484210886Spjd		    &newcfg->hc_controlconn) < 0) {
485210886Spjd			pjdlog_errno(LOG_ERR,
486210886Spjd			    "Unable to listen on control address %s",
487210886Spjd			    newcfg->hc_controladdr);
488210886Spjd			goto failed;
489210886Spjd		}
490210886Spjd	}
491210886Spjd	/*
492222108Spjd	 * Check if any listen address has changed.
493210886Spjd	 */
494222108Spjd	nlisten = 0;
495222108Spjd	TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
496222108Spjd		TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
497222108Spjd			if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
498222108Spjd				break;
499210886Spjd		}
500222108Spjd		if (clst != NULL && clst->hl_conn != NULL) {
501222108Spjd			pjdlog_info("Keep listening on address %s.",
502222108Spjd			    nlst->hl_addr);
503222108Spjd			nlst->hl_conn = clst->hl_conn;
504222108Spjd			nlisten++;
505222108Spjd		} else if (proto_server(nlst->hl_addr, &nlst->hl_conn) == 0) {
506222108Spjd			pjdlog_info("Listening on new address %s.",
507222108Spjd			    nlst->hl_addr);
508222108Spjd			nlisten++;
509222108Spjd		} else {
510222108Spjd			pjdlog_errno(LOG_WARNING,
511222108Spjd			    "Unable to listen on address %s", nlst->hl_addr);
512222108Spjd		}
513210886Spjd	}
514222108Spjd	if (nlisten == 0) {
515222108Spjd		pjdlog_error("No addresses to listen on.");
516222108Spjd		goto failed;
517222108Spjd	}
518222108Spjd
519222108Spjd	/* No failures from now on. */
520222108Spjd
521210886Spjd	/*
522222108Spjd	 * Switch to new control socket.
523210886Spjd	 */
524210886Spjd	if (newcfg->hc_controlconn != NULL) {
525210886Spjd		pjdlog_info("Control socket changed from %s to %s.",
526210886Spjd		    cfg->hc_controladdr, newcfg->hc_controladdr);
527210886Spjd		proto_close(cfg->hc_controlconn);
528210886Spjd		cfg->hc_controlconn = newcfg->hc_controlconn;
529210886Spjd		newcfg->hc_controlconn = NULL;
530210886Spjd		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
531210886Spjd		    sizeof(cfg->hc_controladdr));
532210886Spjd	}
533222108Spjd	/*
534222108Spjd	 * Switch to new listen addresses. Close all that were removed.
535222108Spjd	 */
536222108Spjd	while ((clst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
537222108Spjd		TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
538222108Spjd			if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
539222108Spjd				break;
540222108Spjd		}
541222108Spjd		if (nlst == NULL && clst->hl_conn != NULL) {
542222108Spjd			proto_close(clst->hl_conn);
543222108Spjd			pjdlog_info("No longer listening on address %s.",
544222108Spjd			    clst->hl_addr);
545222108Spjd		}
546222108Spjd		TAILQ_REMOVE(&cfg->hc_listen, clst, hl_next);
547222108Spjd		free(clst);
548210886Spjd	}
549222108Spjd	TAILQ_CONCAT(&cfg->hc_listen, &newcfg->hc_listen, hl_next);
550210886Spjd
551210886Spjd	/*
552210886Spjd	 * Stop and remove resources that were removed from the configuration.
553210886Spjd	 */
554210886Spjd	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
555210886Spjd		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
556210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
557210886Spjd				break;
558210886Spjd		}
559210886Spjd		if (nres == NULL) {
560210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
561210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
562210886Spjd			pjdlog_info("Resource %s removed.", cres->hr_name);
563210886Spjd			free(cres);
564210886Spjd		}
565210886Spjd	}
566210886Spjd	/*
567210886Spjd	 * Move new resources to the current configuration.
568210886Spjd	 */
569210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
570210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
571210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
572210886Spjd				break;
573210886Spjd		}
574210886Spjd		if (cres == NULL) {
575210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
576210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
577210886Spjd			pjdlog_info("Resource %s added.", nres->hr_name);
578210886Spjd		}
579210886Spjd	}
580210886Spjd	/*
581210886Spjd	 * Deal with modified resources.
582210886Spjd	 * Depending on what has changed exactly we might want to perform
583210886Spjd	 * different actions.
584210886Spjd	 *
585210886Spjd	 * We do full resource restart in the following situations:
586210886Spjd	 * Resource role is INIT or SECONDARY.
587210886Spjd	 * Resource role is PRIMARY and path to local component or provider
588210886Spjd	 * name has changed.
589210886Spjd	 * In case of PRIMARY, the worker process will be killed and restarted,
590210886Spjd	 * which also means removing /dev/hast/<name> provider and
591210886Spjd	 * recreating it.
592210886Spjd	 *
593210886Spjd	 * We do just reload (send SIGHUP to worker process) if we act as
594217729Spjd	 * PRIMARY, but only if remote address, replication mode, timeout or
595217729Spjd	 * execution path has changed. For those, there is no need to restart
596217729Spjd	 * worker process.
597210886Spjd	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
598210886Spjd	 * replication mode has changed or simply set new timeout if only
599210886Spjd	 * timeout has changed.
600210886Spjd	 */
601210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
602210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
603210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
604210886Spjd				break;
605210886Spjd		}
606218138Spjd		PJDLOG_ASSERT(cres != NULL);
607210886Spjd		if (resource_needs_restart(cres, nres)) {
608210886Spjd			pjdlog_info("Resource %s configuration was modified, restarting it.",
609210886Spjd			    cres->hr_name);
610210886Spjd			role = cres->hr_role;
611210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
612210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
613210886Spjd			free(cres);
614210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
615210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
616210886Spjd			control_set_role(nres, role);
617210886Spjd		} else if (resource_needs_reload(cres, nres)) {
618210886Spjd			pjdlog_info("Resource %s configuration was modified, reloading it.",
619210886Spjd			    cres->hr_name);
620210886Spjd			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
621210886Spjd			    sizeof(cres->hr_remoteaddr));
622219818Spjd			strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
623219818Spjd			    sizeof(cres->hr_sourceaddr));
624210886Spjd			cres->hr_replication = nres->hr_replication;
625219351Spjd			cres->hr_checksum = nres->hr_checksum;
626219354Spjd			cres->hr_compression = nres->hr_compression;
627210886Spjd			cres->hr_timeout = nres->hr_timeout;
628217729Spjd			strlcpy(cres->hr_exec, nres->hr_exec,
629217729Spjd			    sizeof(cres->hr_exec));
630217784Spjd			if (cres->hr_workerpid != 0)
631217784Spjd				resource_reload(cres);
632210886Spjd		}
633210886Spjd	}
634210886Spjd
635210886Spjd	yy_config_free(newcfg);
636210886Spjd	pjdlog_info("Configuration reloaded successfully.");
637210886Spjd	return;
638210886Spjdfailed:
639210886Spjd	if (newcfg != NULL) {
640210886Spjd		if (newcfg->hc_controlconn != NULL)
641210886Spjd			proto_close(newcfg->hc_controlconn);
642222108Spjd		while ((nlst = TAILQ_FIRST(&newcfg->hc_listen)) != NULL) {
643222108Spjd			if (nlst->hl_conn != NULL) {
644222108Spjd				TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
645222108Spjd					if (strcmp(nlst->hl_addr,
646222108Spjd					    clst->hl_addr) == 0) {
647222108Spjd						break;
648222108Spjd					}
649222108Spjd				}
650222108Spjd				if (clst == NULL || clst->hl_conn == NULL)
651222108Spjd					proto_close(nlst->hl_conn);
652222108Spjd			}
653222108Spjd			TAILQ_REMOVE(&newcfg->hc_listen, nlst, hl_next);
654222108Spjd			free(nlst);
655222108Spjd		}
656210886Spjd		yy_config_free(newcfg);
657210886Spjd	}
658210886Spjd	pjdlog_warning("Configuration not reloaded.");
659204076Spjd}
660204076Spjd
661204076Spjdstatic void
662211899Spjdterminate_workers(void)
663211899Spjd{
664211899Spjd	struct hast_resource *res;
665211899Spjd
666211899Spjd	pjdlog_info("Termination signal received, exiting.");
667211899Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
668211899Spjd		if (res->hr_workerpid == 0)
669211899Spjd			continue;
670211899Spjd		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
671211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
672211899Spjd		if (kill(res->hr_workerpid, SIGTERM) == 0)
673211899Spjd			continue;
674211899Spjd		pjdlog_errno(LOG_WARNING,
675211899Spjd		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
676211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
677211899Spjd	}
678211899Spjd}
679211899Spjd
680211899Spjdstatic void
681222108Spjdlisten_accept(struct hastd_listen *lst)
682204076Spjd{
683204076Spjd	struct hast_resource *res;
684204076Spjd	struct proto_conn *conn;
685204076Spjd	struct nv *nvin, *nvout, *nverr;
686204076Spjd	const char *resname;
687204076Spjd	const unsigned char *token;
688204076Spjd	char laddr[256], raddr[256];
689204076Spjd	size_t size;
690204076Spjd	pid_t pid;
691204076Spjd	int status;
692204076Spjd
693222108Spjd	proto_local_address(lst->hl_conn, laddr, sizeof(laddr));
694204076Spjd	pjdlog_debug(1, "Accepting connection to %s.", laddr);
695204076Spjd
696222108Spjd	if (proto_accept(lst->hl_conn, &conn) < 0) {
697204076Spjd		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
698204076Spjd		return;
699204076Spjd	}
700204076Spjd
701204076Spjd	proto_local_address(conn, laddr, sizeof(laddr));
702204076Spjd	proto_remote_address(conn, raddr, sizeof(raddr));
703209185Spjd	pjdlog_info("Connection from %s to %s.", raddr, laddr);
704204076Spjd
705207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
706207371Spjd	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
707207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
708207371Spjd
709204076Spjd	nvin = nvout = nverr = NULL;
710204076Spjd
711204076Spjd	/*
712204076Spjd	 * Before receiving any data see if remote host have access to any
713204076Spjd	 * resource.
714204076Spjd	 */
715204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
716204076Spjd		if (proto_address_match(conn, res->hr_remoteaddr))
717204076Spjd			break;
718204076Spjd	}
719204076Spjd	if (res == NULL) {
720204076Spjd		pjdlog_error("Client %s isn't known.", raddr);
721204076Spjd		goto close;
722204076Spjd	}
723204076Spjd	/* Ok, remote host can access at least one resource. */
724204076Spjd
725204076Spjd	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
726204076Spjd		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
727204076Spjd		    raddr);
728204076Spjd		goto close;
729204076Spjd	}
730204076Spjd
731204076Spjd	resname = nv_get_string(nvin, "resource");
732204076Spjd	if (resname == NULL) {
733204076Spjd		pjdlog_error("No 'resource' field in the header received from %s.",
734204076Spjd		    raddr);
735204076Spjd		goto close;
736204076Spjd	}
737204076Spjd	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
738204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
739204076Spjd	/*
740204076Spjd	 * NULL token means that this is first conection.
741204076Spjd	 */
742204076Spjd	if (token != NULL && size != sizeof(res->hr_token)) {
743204076Spjd		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
744204076Spjd		    raddr, sizeof(res->hr_token), size);
745204076Spjd		goto close;
746204076Spjd	}
747204076Spjd
748204076Spjd	/*
749204076Spjd	 * From now on we want to send errors to the remote node.
750204076Spjd	 */
751204076Spjd	nverr = nv_alloc();
752204076Spjd
753204076Spjd	/* Find resource related to this connection. */
754204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
755204076Spjd		if (strcmp(resname, res->hr_name) == 0)
756204076Spjd			break;
757204076Spjd	}
758204076Spjd	/* Have we found the resource? */
759204076Spjd	if (res == NULL) {
760204076Spjd		pjdlog_error("No resource '%s' as requested by %s.",
761204076Spjd		    resname, raddr);
762204076Spjd		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
763204076Spjd		goto fail;
764204076Spjd	}
765204076Spjd
766204076Spjd	/* Now that we know resource name setup log prefix. */
767204076Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
768204076Spjd
769204076Spjd	/* Does the remote host have access to this resource? */
770204076Spjd	if (!proto_address_match(conn, res->hr_remoteaddr)) {
771204076Spjd		pjdlog_error("Client %s has no access to the resource.", raddr);
772204076Spjd		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
773204076Spjd		goto fail;
774204076Spjd	}
775204076Spjd	/* Is the resource marked as secondary? */
776204076Spjd	if (res->hr_role != HAST_ROLE_SECONDARY) {
777220890Spjd		pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
778204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
779204076Spjd		    raddr);
780204076Spjd		nv_add_stringf(nverr, "errmsg",
781204076Spjd		    "Remote node acts as %s for the resource and not as %s.",
782204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
783220898Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
784220898Spjd			/*
785220898Spjd			 * If we act as primary request the other side to wait
786220899Spjd			 * for us a bit, as we might be finishing cleanups.
787220898Spjd			 */
788220898Spjd			nv_add_uint8(nverr, 1, "wait");
789220898Spjd		}
790204076Spjd		goto fail;
791204076Spjd	}
792204076Spjd	/* Does token (if exists) match? */
793204076Spjd	if (token != NULL && memcmp(token, res->hr_token,
794204076Spjd	    sizeof(res->hr_token)) != 0) {
795204076Spjd		pjdlog_error("Token received from %s doesn't match.", raddr);
796209185Spjd		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
797204076Spjd		goto fail;
798204076Spjd	}
799204076Spjd	/*
800204076Spjd	 * If there is no token, but we have half-open connection
801204076Spjd	 * (only remotein) or full connection (worker process is running)
802204076Spjd	 * we have to cancel those and accept the new connection.
803204076Spjd	 */
804204076Spjd	if (token == NULL) {
805218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
806204076Spjd		pjdlog_debug(1, "Initial connection from %s.", raddr);
807204076Spjd		if (res->hr_workerpid != 0) {
808218138Spjd			PJDLOG_ASSERT(res->hr_remotein == NULL);
809204076Spjd			pjdlog_debug(1,
810204076Spjd			    "Worker process exists (pid=%u), stopping it.",
811204076Spjd			    (unsigned int)res->hr_workerpid);
812204076Spjd			/* Stop child process. */
813204076Spjd			if (kill(res->hr_workerpid, SIGINT) < 0) {
814204076Spjd				pjdlog_errno(LOG_ERR,
815204076Spjd				    "Unable to stop worker process (pid=%u)",
816204076Spjd				    (unsigned int)res->hr_workerpid);
817204076Spjd				/*
818204076Spjd				 * Other than logging the problem we
819204076Spjd				 * ignore it - nothing smart to do.
820204076Spjd				 */
821204076Spjd			}
822204076Spjd			/* Wait for it to exit. */
823204076Spjd			else if ((pid = waitpid(res->hr_workerpid,
824204076Spjd			    &status, 0)) != res->hr_workerpid) {
825207372Spjd				/* We can only log the problem. */
826204076Spjd				pjdlog_errno(LOG_ERR,
827204076Spjd				    "Waiting for worker process (pid=%u) failed",
828204076Spjd				    (unsigned int)res->hr_workerpid);
829204076Spjd			} else {
830207372Spjd				child_exit_log(res->hr_workerpid, status);
831204076Spjd			}
832213006Spjd			child_cleanup(res);
833204076Spjd		} else if (res->hr_remotein != NULL) {
834204076Spjd			char oaddr[256];
835204076Spjd
836213981Spjd			proto_remote_address(res->hr_remotein, oaddr,
837213981Spjd			    sizeof(oaddr));
838204076Spjd			pjdlog_debug(1,
839204076Spjd			    "Canceling half-open connection from %s on connection from %s.",
840204076Spjd			    oaddr, raddr);
841204076Spjd			proto_close(res->hr_remotein);
842204076Spjd			res->hr_remotein = NULL;
843204076Spjd		}
844204076Spjd	}
845204076Spjd
846204076Spjd	/*
847204076Spjd	 * Checks and cleanups are done.
848204076Spjd	 */
849204076Spjd
850204076Spjd	if (token == NULL) {
851204076Spjd		arc4random_buf(res->hr_token, sizeof(res->hr_token));
852204076Spjd		nvout = nv_alloc();
853204076Spjd		nv_add_uint8_array(nvout, res->hr_token,
854204076Spjd		    sizeof(res->hr_token), "token");
855204076Spjd		if (nv_error(nvout) != 0) {
856204076Spjd			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
857204076Spjd			    "Unable to prepare return header for %s", raddr);
858204076Spjd			nv_add_stringf(nverr, "errmsg",
859204076Spjd			    "Remote node was unable to prepare return header: %s.",
860204076Spjd			    strerror(nv_error(nvout)));
861204076Spjd			goto fail;
862204076Spjd		}
863204076Spjd		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
864204076Spjd			int error = errno;
865204076Spjd
866204076Spjd			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
867204076Spjd			    raddr);
868204076Spjd			nv_add_stringf(nverr, "errmsg",
869204076Spjd			    "Remote node was unable to send response: %s.",
870204076Spjd			    strerror(error));
871204076Spjd			goto fail;
872204076Spjd		}
873204076Spjd		res->hr_remotein = conn;
874204076Spjd		pjdlog_debug(1, "Incoming connection from %s configured.",
875204076Spjd		    raddr);
876204076Spjd	} else {
877204076Spjd		res->hr_remoteout = conn;
878204076Spjd		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
879204076Spjd		hastd_secondary(res, nvin);
880204076Spjd	}
881204076Spjd	nv_free(nvin);
882204076Spjd	nv_free(nvout);
883204076Spjd	nv_free(nverr);
884204076Spjd	pjdlog_prefix_set("%s", "");
885204076Spjd	return;
886204076Spjdfail:
887204076Spjd	if (nv_error(nverr) != 0) {
888204076Spjd		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
889204076Spjd		    "Unable to prepare error header for %s", raddr);
890204076Spjd		goto close;
891204076Spjd	}
892204076Spjd	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
893204076Spjd		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
894204076Spjd		goto close;
895204076Spjd	}
896204076Spjdclose:
897204076Spjd	if (nvin != NULL)
898204076Spjd		nv_free(nvin);
899204076Spjd	if (nvout != NULL)
900204076Spjd		nv_free(nvout);
901204076Spjd	if (nverr != NULL)
902204076Spjd		nv_free(nverr);
903204076Spjd	proto_close(conn);
904204076Spjd	pjdlog_prefix_set("%s", "");
905204076Spjd}
906204076Spjd
907204076Spjdstatic void
908218218Spjdconnection_migrate(struct hast_resource *res)
909218218Spjd{
910218218Spjd	struct proto_conn *conn;
911218218Spjd	int16_t val = 0;
912218218Spjd
913219814Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
914219814Spjd
915219900Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
916219900Spjd
917218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
918218218Spjd		pjdlog_errno(LOG_WARNING,
919218218Spjd		    "Unable to receive connection command");
920218218Spjd		return;
921218218Spjd	}
922219818Spjd	if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
923219818Spjd	    res->hr_remoteaddr, &conn) < 0) {
924218218Spjd		val = errno;
925218218Spjd		pjdlog_errno(LOG_WARNING,
926218218Spjd		    "Unable to create outgoing connection to %s",
927218218Spjd		    res->hr_remoteaddr);
928218218Spjd		goto out;
929218218Spjd	}
930218218Spjd	if (proto_connect(conn, -1) < 0) {
931218218Spjd		val = errno;
932218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
933218218Spjd		    res->hr_remoteaddr);
934218218Spjd		proto_close(conn);
935218218Spjd		goto out;
936218218Spjd	}
937218218Spjd	val = 0;
938218218Spjdout:
939218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
940218218Spjd		pjdlog_errno(LOG_WARNING,
941218218Spjd		    "Unable to send reply to connection request");
942218218Spjd	}
943218218Spjd	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
944218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to send connection");
945219814Spjd
946219814Spjd	pjdlog_prefix_set("%s", "");
947218218Spjd}
948218218Spjd
949218218Spjdstatic void
950219837Spjdcheck_signals(void)
951204076Spjd{
952213009Spjd	struct timespec sigtimeout;
953213009Spjd	sigset_t mask;
954219837Spjd	int signo;
955204076Spjd
956213009Spjd	sigtimeout.tv_sec = 0;
957213009Spjd	sigtimeout.tv_nsec = 0;
958211977Spjd
959213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
960213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
961213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
962213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
963213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
964213009Spjd
965219837Spjd	while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
966219837Spjd		switch (signo) {
967219837Spjd		case SIGINT:
968219837Spjd		case SIGTERM:
969219837Spjd			sigexit_received = true;
970219837Spjd			terminate_workers();
971219837Spjd			proto_close(cfg->hc_controlconn);
972219837Spjd			exit(EX_OK);
973219837Spjd			break;
974219837Spjd		case SIGCHLD:
975219837Spjd			child_exit();
976219837Spjd			break;
977219837Spjd		case SIGHUP:
978219837Spjd			hastd_reload();
979219837Spjd			break;
980219837Spjd		default:
981219837Spjd			PJDLOG_ABORT("Unexpected signal (%d).", signo);
982219837Spjd		}
983219837Spjd	}
984219837Spjd}
985219837Spjd
986219837Spjdstatic void
987219837Spjdmain_loop(void)
988219837Spjd{
989219837Spjd	struct hast_resource *res;
990222108Spjd	struct hastd_listen *lst;
991219837Spjd	struct timeval seltimeout;
992219837Spjd	int fd, maxfd, ret;
993219837Spjd	time_t lastcheck, now;
994219837Spjd	fd_set rfds;
995219837Spjd
996219864Spjd	lastcheck = time(NULL);
997219837Spjd	seltimeout.tv_sec = REPORT_INTERVAL;
998219837Spjd	seltimeout.tv_usec = 0;
999219837Spjd
1000204076Spjd	for (;;) {
1001219837Spjd		check_signals();
1002204076Spjd
1003209177Spjd		/* Setup descriptors for select(2). */
1004204076Spjd		FD_ZERO(&rfds);
1005212038Spjd		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
1006218138Spjd		PJDLOG_ASSERT(fd >= 0);
1007212038Spjd		FD_SET(fd, &rfds);
1008222108Spjd		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1009222108Spjd			if (lst->hl_conn == NULL)
1010222108Spjd				continue;
1011222108Spjd			fd = proto_descriptor(lst->hl_conn);
1012222108Spjd			PJDLOG_ASSERT(fd >= 0);
1013222108Spjd			FD_SET(fd, &rfds);
1014222108Spjd			maxfd = fd > maxfd ? fd : maxfd;
1015222108Spjd		}
1016212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1017212038Spjd			if (res->hr_event == NULL)
1018212038Spjd				continue;
1019212038Spjd			fd = proto_descriptor(res->hr_event);
1020218138Spjd			PJDLOG_ASSERT(fd >= 0);
1021212038Spjd			FD_SET(fd, &rfds);
1022212038Spjd			maxfd = fd > maxfd ? fd : maxfd;
1023218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
1024218218Spjd				/* Only primary workers asks for connections. */
1025219900Spjd				PJDLOG_ASSERT(res->hr_conn != NULL);
1026218218Spjd				fd = proto_descriptor(res->hr_conn);
1027218218Spjd				PJDLOG_ASSERT(fd >= 0);
1028218218Spjd				FD_SET(fd, &rfds);
1029218218Spjd				maxfd = fd > maxfd ? fd : maxfd;
1030219900Spjd			} else {
1031219900Spjd				PJDLOG_ASSERT(res->hr_conn == NULL);
1032218218Spjd			}
1033212038Spjd		}
1034204076Spjd
1035218138Spjd		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
1036213009Spjd		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
1037219813Spjd		now = time(NULL);
1038219813Spjd		if (lastcheck + REPORT_INTERVAL <= now) {
1039213429Spjd			hook_check();
1040219813Spjd			lastcheck = now;
1041219813Spjd		}
1042219813Spjd		if (ret == 0) {
1043219813Spjd			/*
1044219813Spjd			 * select(2) timed out, so there should be no
1045219813Spjd			 * descriptors to check.
1046219813Spjd			 */
1047219813Spjd			continue;
1048219813Spjd		} else if (ret == -1) {
1049204076Spjd			if (errno == EINTR)
1050204076Spjd				continue;
1051204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1052204076Spjd			pjdlog_exit(EX_OSERR, "select() failed");
1053204076Spjd		}
1054204076Spjd
1055219837Spjd		/*
1056219837Spjd		 * Check for signals before we do anything to update our
1057219837Spjd		 * info about terminated workers in the meantime.
1058219837Spjd		 */
1059219837Spjd		check_signals();
1060219837Spjd
1061212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1062204076Spjd			control_handle(cfg);
1063222108Spjd		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1064222108Spjd			if (lst->hl_conn == NULL)
1065222108Spjd				continue;
1066222108Spjd			if (FD_ISSET(proto_descriptor(lst->hl_conn), &rfds))
1067222108Spjd				listen_accept(lst);
1068222108Spjd		}
1069212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1070212038Spjd			if (res->hr_event == NULL)
1071212038Spjd				continue;
1072212038Spjd			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1073212038Spjd				if (event_recv(res) == 0)
1074212038Spjd					continue;
1075212038Spjd				/* The worker process exited? */
1076212038Spjd				proto_close(res->hr_event);
1077212038Spjd				res->hr_event = NULL;
1078219900Spjd				if (res->hr_conn != NULL) {
1079219900Spjd					proto_close(res->hr_conn);
1080219900Spjd					res->hr_conn = NULL;
1081219900Spjd				}
1082218218Spjd				continue;
1083212038Spjd			}
1084219900Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
1085219900Spjd				PJDLOG_ASSERT(res->hr_conn != NULL);
1086219900Spjd				if (FD_ISSET(proto_descriptor(res->hr_conn),
1087219900Spjd				    &rfds)) {
1088219900Spjd					connection_migrate(res);
1089219900Spjd				}
1090219900Spjd			} else {
1091219900Spjd				PJDLOG_ASSERT(res->hr_conn == NULL);
1092218218Spjd			}
1093212038Spjd		}
1094204076Spjd	}
1095204076Spjd}
1096204076Spjd
1097213428Spjdstatic void
1098213428Spjddummy_sighandler(int sig __unused)
1099213428Spjd{
1100213428Spjd	/* Nothing to do. */
1101213428Spjd}
1102213428Spjd
1103204076Spjdint
1104204076Spjdmain(int argc, char *argv[])
1105204076Spjd{
1106222108Spjd	struct hastd_listen *lst;
1107204076Spjd	const char *pidfile;
1108204076Spjd	pid_t otherpid;
1109204076Spjd	bool foreground;
1110204076Spjd	int debuglevel;
1111213009Spjd	sigset_t mask;
1112204076Spjd
1113204076Spjd	foreground = false;
1114204076Spjd	debuglevel = 0;
1115204076Spjd	pidfile = HASTD_PIDFILE;
1116204076Spjd
1117204076Spjd	for (;;) {
1118204076Spjd		int ch;
1119204076Spjd
1120204076Spjd		ch = getopt(argc, argv, "c:dFhP:");
1121204076Spjd		if (ch == -1)
1122204076Spjd			break;
1123204076Spjd		switch (ch) {
1124204076Spjd		case 'c':
1125204076Spjd			cfgpath = optarg;
1126204076Spjd			break;
1127204076Spjd		case 'd':
1128204076Spjd			debuglevel++;
1129204076Spjd			break;
1130204076Spjd		case 'F':
1131204076Spjd			foreground = true;
1132204076Spjd			break;
1133204076Spjd		case 'P':
1134204076Spjd			pidfile = optarg;
1135204076Spjd			break;
1136204076Spjd		case 'h':
1137204076Spjd		default:
1138204076Spjd			usage();
1139204076Spjd		}
1140204076Spjd	}
1141204076Spjd	argc -= optind;
1142204076Spjd	argv += optind;
1143204076Spjd
1144217965Spjd	pjdlog_init(PJDLOG_MODE_STD);
1145204076Spjd	pjdlog_debug_set(debuglevel);
1146204076Spjd
1147214273Spjd	g_gate_load();
1148214273Spjd
1149204076Spjd	pfh = pidfile_open(pidfile, 0600, &otherpid);
1150204076Spjd	if (pfh == NULL) {
1151204076Spjd		if (errno == EEXIST) {
1152204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
1153204076Spjd			    "Another hastd is already running, pid: %jd.",
1154204076Spjd			    (intmax_t)otherpid);
1155204076Spjd		}
1156204076Spjd		/* If we cannot create pidfile from other reasons, only warn. */
1157210879Spjd		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1158204076Spjd	}
1159204076Spjd
1160210883Spjd	cfg = yy_config_parse(cfgpath, true);
1161218138Spjd	PJDLOG_ASSERT(cfg != NULL);
1162204076Spjd
1163213428Spjd	/*
1164217307Spjd	 * Restore default actions for interesting signals in case parent
1165217307Spjd	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1166217307Spjd	 */
1167217307Spjd	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1168217307Spjd	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1169217307Spjd	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1170217307Spjd	/*
1171213428Spjd	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1172213428Spjd	 * so we can mask it.
1173213428Spjd	 */
1174213428Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1175217307Spjd
1176213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1177213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1178213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1179213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1180213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1181213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1182204076Spjd
1183204076Spjd	/* Listen on control address. */
1184204076Spjd	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1185204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1186204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1187204076Spjd		    cfg->hc_controladdr);
1188204076Spjd	}
1189204076Spjd	/* Listen for remote connections. */
1190222108Spjd	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1191222108Spjd		if (proto_server(lst->hl_addr, &lst->hl_conn) < 0) {
1192222108Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1193222108Spjd			pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1194222108Spjd			    lst->hl_addr);
1195222108Spjd		}
1196204076Spjd	}
1197204076Spjd
1198204076Spjd	if (!foreground) {
1199204076Spjd		if (daemon(0, 0) < 0) {
1200204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1201204076Spjd			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1202204076Spjd		}
1203204076Spjd
1204204076Spjd		/* Start logging to syslog. */
1205204076Spjd		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1206204076Spjd
1207204076Spjd		/* Write PID to a file. */
1208204076Spjd		if (pidfile_write(pfh) < 0) {
1209204076Spjd			pjdlog_errno(LOG_WARNING,
1210204076Spjd			    "Unable to write PID to a file");
1211204076Spjd		}
1212204076Spjd	}
1213204076Spjd
1214222108Spjd	pjdlog_info("Started successfully, running protocol version %d.",
1215222108Spjd	    HAST_PROTO_VERSION);
1216222108Spjd
1217222108Spjd	pjdlog_debug(1, "Listening on control address %s.",
1218222108Spjd	    cfg->hc_controladdr);
1219222108Spjd	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next)
1220222108Spjd		pjdlog_info("Listening on address %s.", lst->hl_addr);
1221222108Spjd
1222211977Spjd	hook_init();
1223211977Spjd
1224204076Spjd	main_loop();
1225204076Spjd
1226204076Spjd	exit(0);
1227204076Spjd}
1228