hastd.c revision 219900
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 219900 2011-03-23 11:09:04Z 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			}
227219900Spjd		} else if (res->hr_role == HAST_ROLE_PRIMARY &&
228219900Spjd		    fd == proto_descriptor(res->hr_conn)) {
229218218Spjd			if (!isopen) {
230218375Spjd				(void)snprintf(msg, sizeof(msg),
231218218Spjd				    "Descriptor %d (conn) is closed, but should be open.",
232218218Spjd				    fd);
233218218Spjd				break;
234218218Spjd			}
235218218Spjd			if (!S_ISSOCK(mode)) {
236218375Spjd				(void)snprintf(msg, sizeof(msg),
237218218Spjd				    "Descriptor %d (conn) is %s, but should be %s.",
238218218Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
239218218Spjd				break;
240218218Spjd			}
241218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
242219900Spjd		    res->hr_conn != NULL &&
243219900Spjd		    fd == proto_descriptor(res->hr_conn)) {
244219900Spjd			if (isopen) {
245219900Spjd				(void)snprintf(msg, sizeof(msg),
246219900Spjd				    "Descriptor %d (conn) is open, but should be closed.",
247219900Spjd				    fd);
248219900Spjd				break;
249219900Spjd			}
250219900Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
251218044Spjd		    fd == proto_descriptor(res->hr_remotein)) {
252218044Spjd			if (!isopen) {
253218375Spjd				(void)snprintf(msg, sizeof(msg),
254218044Spjd				    "Descriptor %d (remote in) is closed, but should be open.",
255218044Spjd				    fd);
256218044Spjd				break;
257218044Spjd			}
258218044Spjd			if (!S_ISSOCK(mode)) {
259218375Spjd				(void)snprintf(msg, sizeof(msg),
260218044Spjd				    "Descriptor %d (remote in) is %s, but should be %s.",
261218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
262218044Spjd				break;
263218044Spjd			}
264218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
265218044Spjd		    fd == proto_descriptor(res->hr_remoteout)) {
266218044Spjd			if (!isopen) {
267218375Spjd				(void)snprintf(msg, sizeof(msg),
268218044Spjd				    "Descriptor %d (remote out) is closed, but should be open.",
269218044Spjd				    fd);
270218044Spjd				break;
271218044Spjd			}
272218044Spjd			if (!S_ISSOCK(mode)) {
273218375Spjd				(void)snprintf(msg, sizeof(msg),
274218044Spjd				    "Descriptor %d (remote out) is %s, but should be %s.",
275218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
276218044Spjd				break;
277218044Spjd			}
278218044Spjd		} else {
279218044Spjd			if (isopen) {
280218375Spjd				(void)snprintf(msg, sizeof(msg),
281218044Spjd				    "Descriptor %d is open (%s), but should be closed.",
282218044Spjd				    fd, dtype2str(mode));
283218044Spjd				break;
284218044Spjd			}
285218044Spjd		}
286218044Spjd	}
287218044Spjd	if (msg[0] != '\0') {
288218044Spjd		pjdlog_init(pjdlogmode);
289218044Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
290218044Spjd		    role2str(res->hr_role));
291218044Spjd		PJDLOG_ABORT("%s", msg);
292218044Spjd	}
293218044Spjd}
294218044Spjd
295204076Spjdstatic void
296207372Spjdchild_exit_log(unsigned int pid, int status)
297207372Spjd{
298207372Spjd
299207372Spjd	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
300207372Spjd		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
301207372Spjd		    pid);
302207372Spjd	} else if (WIFSIGNALED(status)) {
303207372Spjd		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
304207372Spjd		    pid, WTERMSIG(status));
305207372Spjd	} else {
306207372Spjd		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
307207372Spjd		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
308207372Spjd	}
309207372Spjd}
310207372Spjd
311207372Spjdstatic void
312204076Spjdchild_exit(void)
313204076Spjd{
314204076Spjd	struct hast_resource *res;
315204076Spjd	int status;
316204076Spjd	pid_t pid;
317204076Spjd
318204076Spjd	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
319204076Spjd		/* Find resource related to the process that just exited. */
320204076Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
321204076Spjd			if (pid == res->hr_workerpid)
322204076Spjd				break;
323204076Spjd		}
324204076Spjd		if (res == NULL) {
325204076Spjd			/*
326204076Spjd			 * This can happen when new connection arrives and we
327211977Spjd			 * cancel child responsible for the old one or if this
328211977Spjd			 * was hook which we executed.
329204076Spjd			 */
330211977Spjd			hook_check_one(pid, status);
331204076Spjd			continue;
332204076Spjd		}
333204076Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
334204076Spjd		    role2str(res->hr_role));
335207372Spjd		child_exit_log(pid, status);
336213006Spjd		child_cleanup(res);
337204076Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
338207372Spjd			/*
339207372Spjd			 * Restart child process if it was killed by signal
340207372Spjd			 * or exited because of temporary problem.
341207372Spjd			 */
342207372Spjd			if (WIFSIGNALED(status) ||
343207372Spjd			    (WIFEXITED(status) &&
344207372Spjd			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
345207348Spjd				sleep(1);
346207348Spjd				pjdlog_info("Restarting worker process.");
347207348Spjd				hastd_primary(res);
348207348Spjd			} else {
349207348Spjd				res->hr_role = HAST_ROLE_INIT;
350207348Spjd				pjdlog_info("Changing resource role back to %s.",
351207348Spjd				    role2str(res->hr_role));
352207348Spjd			}
353204076Spjd		}
354204076Spjd		pjdlog_prefix_set("%s", "");
355204076Spjd	}
356204076Spjd}
357204076Spjd
358210886Spjdstatic bool
359210886Spjdresource_needs_restart(const struct hast_resource *res0,
360210886Spjd    const struct hast_resource *res1)
361210886Spjd{
362210886Spjd
363218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
364210886Spjd
365210886Spjd	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
366210886Spjd		return (true);
367210886Spjd	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
368210886Spjd		return (true);
369210886Spjd	if (res0->hr_role == HAST_ROLE_INIT ||
370210886Spjd	    res0->hr_role == HAST_ROLE_SECONDARY) {
371210886Spjd		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
372210886Spjd			return (true);
373219818Spjd		if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
374219818Spjd			return (true);
375210886Spjd		if (res0->hr_replication != res1->hr_replication)
376210886Spjd			return (true);
377219351Spjd		if (res0->hr_checksum != res1->hr_checksum)
378219351Spjd			return (true);
379219354Spjd		if (res0->hr_compression != res1->hr_compression)
380219354Spjd			return (true);
381210886Spjd		if (res0->hr_timeout != res1->hr_timeout)
382210886Spjd			return (true);
383211886Spjd		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
384211886Spjd			return (true);
385210886Spjd	}
386210886Spjd	return (false);
387210886Spjd}
388210886Spjd
389210886Spjdstatic bool
390210886Spjdresource_needs_reload(const struct hast_resource *res0,
391210886Spjd    const struct hast_resource *res1)
392210886Spjd{
393210886Spjd
394218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
395218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
396218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
397210886Spjd
398210886Spjd	if (res0->hr_role != HAST_ROLE_PRIMARY)
399210886Spjd		return (false);
400210886Spjd
401210886Spjd	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
402210886Spjd		return (true);
403219818Spjd	if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
404219818Spjd		return (true);
405210886Spjd	if (res0->hr_replication != res1->hr_replication)
406210886Spjd		return (true);
407219351Spjd	if (res0->hr_checksum != res1->hr_checksum)
408219351Spjd		return (true);
409219354Spjd	if (res0->hr_compression != res1->hr_compression)
410219354Spjd		return (true);
411210886Spjd	if (res0->hr_timeout != res1->hr_timeout)
412210886Spjd		return (true);
413211886Spjd	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
414211886Spjd		return (true);
415210886Spjd	return (false);
416210886Spjd}
417210886Spjd
418204076Spjdstatic void
419217784Spjdresource_reload(const struct hast_resource *res)
420217784Spjd{
421217784Spjd	struct nv *nvin, *nvout;
422217784Spjd	int error;
423217784Spjd
424218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
425217784Spjd
426217784Spjd	nvout = nv_alloc();
427217784Spjd	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
428217784Spjd	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
429219818Spjd	nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
430217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
431219351Spjd	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
432219354Spjd	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
433217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
434217784Spjd	nv_add_string(nvout, res->hr_exec, "exec");
435217784Spjd	if (nv_error(nvout) != 0) {
436217784Spjd		nv_free(nvout);
437217784Spjd		pjdlog_error("Unable to allocate header for reload message.");
438217784Spjd		return;
439217784Spjd	}
440217784Spjd	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
441217784Spjd		pjdlog_errno(LOG_ERR, "Unable to send reload message");
442217784Spjd		nv_free(nvout);
443217784Spjd		return;
444217784Spjd	}
445217784Spjd	nv_free(nvout);
446217784Spjd
447217784Spjd	/* Receive response. */
448217784Spjd	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
449217784Spjd		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
450217784Spjd		return;
451217784Spjd	}
452217784Spjd	error = nv_get_int16(nvin, "error");
453217784Spjd	nv_free(nvin);
454217784Spjd	if (error != 0) {
455217784Spjd		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
456217784Spjd		return;
457217784Spjd	}
458217784Spjd}
459217784Spjd
460217784Spjdstatic void
461204076Spjdhastd_reload(void)
462204076Spjd{
463210886Spjd	struct hastd_config *newcfg;
464210886Spjd	struct hast_resource *nres, *cres, *tres;
465210886Spjd	uint8_t role;
466204076Spjd
467210886Spjd	pjdlog_info("Reloading configuration...");
468210886Spjd
469210886Spjd	newcfg = yy_config_parse(cfgpath, false);
470210886Spjd	if (newcfg == NULL)
471210886Spjd		goto failed;
472210886Spjd
473210886Spjd	/*
474210886Spjd	 * Check if control address has changed.
475210886Spjd	 */
476210886Spjd	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
477210886Spjd		if (proto_server(newcfg->hc_controladdr,
478210886Spjd		    &newcfg->hc_controlconn) < 0) {
479210886Spjd			pjdlog_errno(LOG_ERR,
480210886Spjd			    "Unable to listen on control address %s",
481210886Spjd			    newcfg->hc_controladdr);
482210886Spjd			goto failed;
483210886Spjd		}
484210886Spjd	}
485210886Spjd	/*
486210886Spjd	 * Check if listen address has changed.
487210886Spjd	 */
488210886Spjd	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
489210886Spjd		if (proto_server(newcfg->hc_listenaddr,
490210886Spjd		    &newcfg->hc_listenconn) < 0) {
491210886Spjd			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
492210886Spjd			    newcfg->hc_listenaddr);
493210886Spjd			goto failed;
494210886Spjd		}
495210886Spjd	}
496210886Spjd	/*
497210886Spjd	 * Only when both control and listen sockets are successfully
498210886Spjd	 * initialized switch them to new configuration.
499210886Spjd	 */
500210886Spjd	if (newcfg->hc_controlconn != NULL) {
501210886Spjd		pjdlog_info("Control socket changed from %s to %s.",
502210886Spjd		    cfg->hc_controladdr, newcfg->hc_controladdr);
503210886Spjd		proto_close(cfg->hc_controlconn);
504210886Spjd		cfg->hc_controlconn = newcfg->hc_controlconn;
505210886Spjd		newcfg->hc_controlconn = NULL;
506210886Spjd		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
507210886Spjd		    sizeof(cfg->hc_controladdr));
508210886Spjd	}
509210886Spjd	if (newcfg->hc_listenconn != NULL) {
510210886Spjd		pjdlog_info("Listen socket changed from %s to %s.",
511210886Spjd		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
512210886Spjd		proto_close(cfg->hc_listenconn);
513210886Spjd		cfg->hc_listenconn = newcfg->hc_listenconn;
514210886Spjd		newcfg->hc_listenconn = NULL;
515210886Spjd		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
516210886Spjd		    sizeof(cfg->hc_listenaddr));
517210886Spjd	}
518210886Spjd
519210886Spjd	/*
520210886Spjd	 * Stop and remove resources that were removed from the configuration.
521210886Spjd	 */
522210886Spjd	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
523210886Spjd		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
524210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
525210886Spjd				break;
526210886Spjd		}
527210886Spjd		if (nres == NULL) {
528210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
529210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
530210886Spjd			pjdlog_info("Resource %s removed.", cres->hr_name);
531210886Spjd			free(cres);
532210886Spjd		}
533210886Spjd	}
534210886Spjd	/*
535210886Spjd	 * Move new resources to the current configuration.
536210886Spjd	 */
537210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
538210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
539210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
540210886Spjd				break;
541210886Spjd		}
542210886Spjd		if (cres == NULL) {
543210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
544210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
545210886Spjd			pjdlog_info("Resource %s added.", nres->hr_name);
546210886Spjd		}
547210886Spjd	}
548210886Spjd	/*
549210886Spjd	 * Deal with modified resources.
550210886Spjd	 * Depending on what has changed exactly we might want to perform
551210886Spjd	 * different actions.
552210886Spjd	 *
553210886Spjd	 * We do full resource restart in the following situations:
554210886Spjd	 * Resource role is INIT or SECONDARY.
555210886Spjd	 * Resource role is PRIMARY and path to local component or provider
556210886Spjd	 * name has changed.
557210886Spjd	 * In case of PRIMARY, the worker process will be killed and restarted,
558210886Spjd	 * which also means removing /dev/hast/<name> provider and
559210886Spjd	 * recreating it.
560210886Spjd	 *
561210886Spjd	 * We do just reload (send SIGHUP to worker process) if we act as
562217729Spjd	 * PRIMARY, but only if remote address, replication mode, timeout or
563217729Spjd	 * execution path has changed. For those, there is no need to restart
564217729Spjd	 * worker process.
565210886Spjd	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
566210886Spjd	 * replication mode has changed or simply set new timeout if only
567210886Spjd	 * timeout has changed.
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		}
574218138Spjd		PJDLOG_ASSERT(cres != NULL);
575210886Spjd		if (resource_needs_restart(cres, nres)) {
576210886Spjd			pjdlog_info("Resource %s configuration was modified, restarting it.",
577210886Spjd			    cres->hr_name);
578210886Spjd			role = cres->hr_role;
579210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
580210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
581210886Spjd			free(cres);
582210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
583210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
584210886Spjd			control_set_role(nres, role);
585210886Spjd		} else if (resource_needs_reload(cres, nres)) {
586210886Spjd			pjdlog_info("Resource %s configuration was modified, reloading it.",
587210886Spjd			    cres->hr_name);
588210886Spjd			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
589210886Spjd			    sizeof(cres->hr_remoteaddr));
590219818Spjd			strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
591219818Spjd			    sizeof(cres->hr_sourceaddr));
592210886Spjd			cres->hr_replication = nres->hr_replication;
593219351Spjd			cres->hr_checksum = nres->hr_checksum;
594219354Spjd			cres->hr_compression = nres->hr_compression;
595210886Spjd			cres->hr_timeout = nres->hr_timeout;
596217729Spjd			strlcpy(cres->hr_exec, nres->hr_exec,
597217729Spjd			    sizeof(cres->hr_exec));
598217784Spjd			if (cres->hr_workerpid != 0)
599217784Spjd				resource_reload(cres);
600210886Spjd		}
601210886Spjd	}
602210886Spjd
603210886Spjd	yy_config_free(newcfg);
604210886Spjd	pjdlog_info("Configuration reloaded successfully.");
605210886Spjd	return;
606210886Spjdfailed:
607210886Spjd	if (newcfg != NULL) {
608210886Spjd		if (newcfg->hc_controlconn != NULL)
609210886Spjd			proto_close(newcfg->hc_controlconn);
610210886Spjd		if (newcfg->hc_listenconn != NULL)
611210886Spjd			proto_close(newcfg->hc_listenconn);
612210886Spjd		yy_config_free(newcfg);
613210886Spjd	}
614210886Spjd	pjdlog_warning("Configuration not reloaded.");
615204076Spjd}
616204076Spjd
617204076Spjdstatic void
618211899Spjdterminate_workers(void)
619211899Spjd{
620211899Spjd	struct hast_resource *res;
621211899Spjd
622211899Spjd	pjdlog_info("Termination signal received, exiting.");
623211899Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
624211899Spjd		if (res->hr_workerpid == 0)
625211899Spjd			continue;
626211899Spjd		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
627211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
628211899Spjd		if (kill(res->hr_workerpid, SIGTERM) == 0)
629211899Spjd			continue;
630211899Spjd		pjdlog_errno(LOG_WARNING,
631211899Spjd		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
632211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
633211899Spjd	}
634211899Spjd}
635211899Spjd
636211899Spjdstatic void
637204076Spjdlisten_accept(void)
638204076Spjd{
639204076Spjd	struct hast_resource *res;
640204076Spjd	struct proto_conn *conn;
641204076Spjd	struct nv *nvin, *nvout, *nverr;
642204076Spjd	const char *resname;
643204076Spjd	const unsigned char *token;
644204076Spjd	char laddr[256], raddr[256];
645204076Spjd	size_t size;
646204076Spjd	pid_t pid;
647204076Spjd	int status;
648204076Spjd
649204076Spjd	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
650204076Spjd	pjdlog_debug(1, "Accepting connection to %s.", laddr);
651204076Spjd
652204076Spjd	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
653204076Spjd		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
654204076Spjd		return;
655204076Spjd	}
656204076Spjd
657204076Spjd	proto_local_address(conn, laddr, sizeof(laddr));
658204076Spjd	proto_remote_address(conn, raddr, sizeof(raddr));
659209185Spjd	pjdlog_info("Connection from %s to %s.", raddr, laddr);
660204076Spjd
661207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
662207371Spjd	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
663207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
664207371Spjd
665204076Spjd	nvin = nvout = nverr = NULL;
666204076Spjd
667204076Spjd	/*
668204076Spjd	 * Before receiving any data see if remote host have access to any
669204076Spjd	 * resource.
670204076Spjd	 */
671204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
672204076Spjd		if (proto_address_match(conn, res->hr_remoteaddr))
673204076Spjd			break;
674204076Spjd	}
675204076Spjd	if (res == NULL) {
676204076Spjd		pjdlog_error("Client %s isn't known.", raddr);
677204076Spjd		goto close;
678204076Spjd	}
679204076Spjd	/* Ok, remote host can access at least one resource. */
680204076Spjd
681204076Spjd	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
682204076Spjd		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
683204076Spjd		    raddr);
684204076Spjd		goto close;
685204076Spjd	}
686204076Spjd
687204076Spjd	resname = nv_get_string(nvin, "resource");
688204076Spjd	if (resname == NULL) {
689204076Spjd		pjdlog_error("No 'resource' field in the header received from %s.",
690204076Spjd		    raddr);
691204076Spjd		goto close;
692204076Spjd	}
693204076Spjd	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
694204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
695204076Spjd	/*
696204076Spjd	 * NULL token means that this is first conection.
697204076Spjd	 */
698204076Spjd	if (token != NULL && size != sizeof(res->hr_token)) {
699204076Spjd		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
700204076Spjd		    raddr, sizeof(res->hr_token), size);
701204076Spjd		goto close;
702204076Spjd	}
703204076Spjd
704204076Spjd	/*
705204076Spjd	 * From now on we want to send errors to the remote node.
706204076Spjd	 */
707204076Spjd	nverr = nv_alloc();
708204076Spjd
709204076Spjd	/* Find resource related to this connection. */
710204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
711204076Spjd		if (strcmp(resname, res->hr_name) == 0)
712204076Spjd			break;
713204076Spjd	}
714204076Spjd	/* Have we found the resource? */
715204076Spjd	if (res == NULL) {
716204076Spjd		pjdlog_error("No resource '%s' as requested by %s.",
717204076Spjd		    resname, raddr);
718204076Spjd		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
719204076Spjd		goto fail;
720204076Spjd	}
721204076Spjd
722204076Spjd	/* Now that we know resource name setup log prefix. */
723204076Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
724204076Spjd
725204076Spjd	/* Does the remote host have access to this resource? */
726204076Spjd	if (!proto_address_match(conn, res->hr_remoteaddr)) {
727204076Spjd		pjdlog_error("Client %s has no access to the resource.", raddr);
728204076Spjd		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
729204076Spjd		goto fail;
730204076Spjd	}
731204076Spjd	/* Is the resource marked as secondary? */
732204076Spjd	if (res->hr_role != HAST_ROLE_SECONDARY) {
733204076Spjd		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
734204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
735204076Spjd		    raddr);
736204076Spjd		nv_add_stringf(nverr, "errmsg",
737204076Spjd		    "Remote node acts as %s for the resource and not as %s.",
738204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
739204076Spjd		goto fail;
740204076Spjd	}
741204076Spjd	/* Does token (if exists) match? */
742204076Spjd	if (token != NULL && memcmp(token, res->hr_token,
743204076Spjd	    sizeof(res->hr_token)) != 0) {
744204076Spjd		pjdlog_error("Token received from %s doesn't match.", raddr);
745209185Spjd		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
746204076Spjd		goto fail;
747204076Spjd	}
748204076Spjd	/*
749204076Spjd	 * If there is no token, but we have half-open connection
750204076Spjd	 * (only remotein) or full connection (worker process is running)
751204076Spjd	 * we have to cancel those and accept the new connection.
752204076Spjd	 */
753204076Spjd	if (token == NULL) {
754218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
755204076Spjd		pjdlog_debug(1, "Initial connection from %s.", raddr);
756204076Spjd		if (res->hr_workerpid != 0) {
757218138Spjd			PJDLOG_ASSERT(res->hr_remotein == NULL);
758204076Spjd			pjdlog_debug(1,
759204076Spjd			    "Worker process exists (pid=%u), stopping it.",
760204076Spjd			    (unsigned int)res->hr_workerpid);
761204076Spjd			/* Stop child process. */
762204076Spjd			if (kill(res->hr_workerpid, SIGINT) < 0) {
763204076Spjd				pjdlog_errno(LOG_ERR,
764204076Spjd				    "Unable to stop worker process (pid=%u)",
765204076Spjd				    (unsigned int)res->hr_workerpid);
766204076Spjd				/*
767204076Spjd				 * Other than logging the problem we
768204076Spjd				 * ignore it - nothing smart to do.
769204076Spjd				 */
770204076Spjd			}
771204076Spjd			/* Wait for it to exit. */
772204076Spjd			else if ((pid = waitpid(res->hr_workerpid,
773204076Spjd			    &status, 0)) != res->hr_workerpid) {
774207372Spjd				/* We can only log the problem. */
775204076Spjd				pjdlog_errno(LOG_ERR,
776204076Spjd				    "Waiting for worker process (pid=%u) failed",
777204076Spjd				    (unsigned int)res->hr_workerpid);
778204076Spjd			} else {
779207372Spjd				child_exit_log(res->hr_workerpid, status);
780204076Spjd			}
781213006Spjd			child_cleanup(res);
782204076Spjd		} else if (res->hr_remotein != NULL) {
783204076Spjd			char oaddr[256];
784204076Spjd
785213981Spjd			proto_remote_address(res->hr_remotein, oaddr,
786213981Spjd			    sizeof(oaddr));
787204076Spjd			pjdlog_debug(1,
788204076Spjd			    "Canceling half-open connection from %s on connection from %s.",
789204076Spjd			    oaddr, raddr);
790204076Spjd			proto_close(res->hr_remotein);
791204076Spjd			res->hr_remotein = NULL;
792204076Spjd		}
793204076Spjd	}
794204076Spjd
795204076Spjd	/*
796204076Spjd	 * Checks and cleanups are done.
797204076Spjd	 */
798204076Spjd
799204076Spjd	if (token == NULL) {
800204076Spjd		arc4random_buf(res->hr_token, sizeof(res->hr_token));
801204076Spjd		nvout = nv_alloc();
802204076Spjd		nv_add_uint8_array(nvout, res->hr_token,
803204076Spjd		    sizeof(res->hr_token), "token");
804204076Spjd		if (nv_error(nvout) != 0) {
805204076Spjd			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
806204076Spjd			    "Unable to prepare return header for %s", raddr);
807204076Spjd			nv_add_stringf(nverr, "errmsg",
808204076Spjd			    "Remote node was unable to prepare return header: %s.",
809204076Spjd			    strerror(nv_error(nvout)));
810204076Spjd			goto fail;
811204076Spjd		}
812204076Spjd		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
813204076Spjd			int error = errno;
814204076Spjd
815204076Spjd			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
816204076Spjd			    raddr);
817204076Spjd			nv_add_stringf(nverr, "errmsg",
818204076Spjd			    "Remote node was unable to send response: %s.",
819204076Spjd			    strerror(error));
820204076Spjd			goto fail;
821204076Spjd		}
822204076Spjd		res->hr_remotein = conn;
823204076Spjd		pjdlog_debug(1, "Incoming connection from %s configured.",
824204076Spjd		    raddr);
825204076Spjd	} else {
826204076Spjd		res->hr_remoteout = conn;
827204076Spjd		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
828204076Spjd		hastd_secondary(res, nvin);
829204076Spjd	}
830204076Spjd	nv_free(nvin);
831204076Spjd	nv_free(nvout);
832204076Spjd	nv_free(nverr);
833204076Spjd	pjdlog_prefix_set("%s", "");
834204076Spjd	return;
835204076Spjdfail:
836204076Spjd	if (nv_error(nverr) != 0) {
837204076Spjd		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
838204076Spjd		    "Unable to prepare error header for %s", raddr);
839204076Spjd		goto close;
840204076Spjd	}
841204076Spjd	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
842204076Spjd		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
843204076Spjd		goto close;
844204076Spjd	}
845204076Spjdclose:
846204076Spjd	if (nvin != NULL)
847204076Spjd		nv_free(nvin);
848204076Spjd	if (nvout != NULL)
849204076Spjd		nv_free(nvout);
850204076Spjd	if (nverr != NULL)
851204076Spjd		nv_free(nverr);
852204076Spjd	proto_close(conn);
853204076Spjd	pjdlog_prefix_set("%s", "");
854204076Spjd}
855204076Spjd
856204076Spjdstatic void
857218218Spjdconnection_migrate(struct hast_resource *res)
858218218Spjd{
859218218Spjd	struct proto_conn *conn;
860218218Spjd	int16_t val = 0;
861218218Spjd
862219814Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
863219814Spjd
864219900Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
865219900Spjd
866218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
867218218Spjd		pjdlog_errno(LOG_WARNING,
868218218Spjd		    "Unable to receive connection command");
869218218Spjd		return;
870218218Spjd	}
871219818Spjd	if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
872219818Spjd	    res->hr_remoteaddr, &conn) < 0) {
873218218Spjd		val = errno;
874218218Spjd		pjdlog_errno(LOG_WARNING,
875218218Spjd		    "Unable to create outgoing connection to %s",
876218218Spjd		    res->hr_remoteaddr);
877218218Spjd		goto out;
878218218Spjd	}
879218218Spjd	if (proto_connect(conn, -1) < 0) {
880218218Spjd		val = errno;
881218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
882218218Spjd		    res->hr_remoteaddr);
883218218Spjd		proto_close(conn);
884218218Spjd		goto out;
885218218Spjd	}
886218218Spjd	val = 0;
887218218Spjdout:
888218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
889218218Spjd		pjdlog_errno(LOG_WARNING,
890218218Spjd		    "Unable to send reply to connection request");
891218218Spjd	}
892218218Spjd	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
893218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to send connection");
894219814Spjd
895219814Spjd	pjdlog_prefix_set("%s", "");
896218218Spjd}
897218218Spjd
898218218Spjdstatic void
899219837Spjdcheck_signals(void)
900204076Spjd{
901213009Spjd	struct timespec sigtimeout;
902213009Spjd	sigset_t mask;
903219837Spjd	int signo;
904204076Spjd
905213009Spjd	sigtimeout.tv_sec = 0;
906213009Spjd	sigtimeout.tv_nsec = 0;
907211977Spjd
908213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
909213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
910213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
911213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
912213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
913213009Spjd
914219837Spjd	while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
915219837Spjd		switch (signo) {
916219837Spjd		case SIGINT:
917219837Spjd		case SIGTERM:
918219837Spjd			sigexit_received = true;
919219837Spjd			terminate_workers();
920219837Spjd			proto_close(cfg->hc_controlconn);
921219837Spjd			exit(EX_OK);
922219837Spjd			break;
923219837Spjd		case SIGCHLD:
924219837Spjd			child_exit();
925219837Spjd			break;
926219837Spjd		case SIGHUP:
927219837Spjd			hastd_reload();
928219837Spjd			break;
929219837Spjd		default:
930219837Spjd			PJDLOG_ABORT("Unexpected signal (%d).", signo);
931219837Spjd		}
932219837Spjd	}
933219837Spjd}
934219837Spjd
935219837Spjdstatic void
936219837Spjdmain_loop(void)
937219837Spjd{
938219837Spjd	struct hast_resource *res;
939219837Spjd	struct timeval seltimeout;
940219837Spjd	int fd, maxfd, ret;
941219837Spjd	time_t lastcheck, now;
942219837Spjd	fd_set rfds;
943219837Spjd
944219864Spjd	lastcheck = time(NULL);
945219837Spjd	seltimeout.tv_sec = REPORT_INTERVAL;
946219837Spjd	seltimeout.tv_usec = 0;
947219837Spjd
948216477Spjd	pjdlog_info("Started successfully, running protocol version %d.",
949216477Spjd	    HAST_PROTO_VERSION);
950216477Spjd
951204076Spjd	for (;;) {
952219837Spjd		check_signals();
953204076Spjd
954209177Spjd		/* Setup descriptors for select(2). */
955204076Spjd		FD_ZERO(&rfds);
956212038Spjd		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
957218138Spjd		PJDLOG_ASSERT(fd >= 0);
958212038Spjd		FD_SET(fd, &rfds);
959212038Spjd		fd = proto_descriptor(cfg->hc_listenconn);
960218138Spjd		PJDLOG_ASSERT(fd >= 0);
961212038Spjd		FD_SET(fd, &rfds);
962212038Spjd		maxfd = fd > maxfd ? fd : maxfd;
963212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
964212038Spjd			if (res->hr_event == NULL)
965212038Spjd				continue;
966212038Spjd			fd = proto_descriptor(res->hr_event);
967218138Spjd			PJDLOG_ASSERT(fd >= 0);
968212038Spjd			FD_SET(fd, &rfds);
969212038Spjd			maxfd = fd > maxfd ? fd : maxfd;
970218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
971218218Spjd				/* Only primary workers asks for connections. */
972219900Spjd				PJDLOG_ASSERT(res->hr_conn != NULL);
973218218Spjd				fd = proto_descriptor(res->hr_conn);
974218218Spjd				PJDLOG_ASSERT(fd >= 0);
975218218Spjd				FD_SET(fd, &rfds);
976218218Spjd				maxfd = fd > maxfd ? fd : maxfd;
977219900Spjd			} else {
978219900Spjd				PJDLOG_ASSERT(res->hr_conn == NULL);
979218218Spjd			}
980212038Spjd		}
981204076Spjd
982218138Spjd		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
983213009Spjd		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
984219813Spjd		now = time(NULL);
985219813Spjd		if (lastcheck + REPORT_INTERVAL <= now) {
986213429Spjd			hook_check();
987219813Spjd			lastcheck = now;
988219813Spjd		}
989219813Spjd		if (ret == 0) {
990219813Spjd			/*
991219813Spjd			 * select(2) timed out, so there should be no
992219813Spjd			 * descriptors to check.
993219813Spjd			 */
994219813Spjd			continue;
995219813Spjd		} else if (ret == -1) {
996204076Spjd			if (errno == EINTR)
997204076Spjd				continue;
998204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
999204076Spjd			pjdlog_exit(EX_OSERR, "select() failed");
1000204076Spjd		}
1001204076Spjd
1002219837Spjd		/*
1003219837Spjd		 * Check for signals before we do anything to update our
1004219837Spjd		 * info about terminated workers in the meantime.
1005219837Spjd		 */
1006219837Spjd		check_signals();
1007219837Spjd
1008212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1009204076Spjd			control_handle(cfg);
1010212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
1011204076Spjd			listen_accept();
1012212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1013212038Spjd			if (res->hr_event == NULL)
1014212038Spjd				continue;
1015212038Spjd			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1016212038Spjd				if (event_recv(res) == 0)
1017212038Spjd					continue;
1018212038Spjd				/* The worker process exited? */
1019212038Spjd				proto_close(res->hr_event);
1020212038Spjd				res->hr_event = NULL;
1021219900Spjd				if (res->hr_conn != NULL) {
1022219900Spjd					proto_close(res->hr_conn);
1023219900Spjd					res->hr_conn = NULL;
1024219900Spjd				}
1025218218Spjd				continue;
1026212038Spjd			}
1027219900Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
1028219900Spjd				PJDLOG_ASSERT(res->hr_conn != NULL);
1029219900Spjd				if (FD_ISSET(proto_descriptor(res->hr_conn),
1030219900Spjd				    &rfds)) {
1031219900Spjd					connection_migrate(res);
1032219900Spjd				}
1033219900Spjd			} else {
1034219900Spjd				PJDLOG_ASSERT(res->hr_conn == NULL);
1035218218Spjd			}
1036212038Spjd		}
1037204076Spjd	}
1038204076Spjd}
1039204076Spjd
1040213428Spjdstatic void
1041213428Spjddummy_sighandler(int sig __unused)
1042213428Spjd{
1043213428Spjd	/* Nothing to do. */
1044213428Spjd}
1045213428Spjd
1046204076Spjdint
1047204076Spjdmain(int argc, char *argv[])
1048204076Spjd{
1049204076Spjd	const char *pidfile;
1050204076Spjd	pid_t otherpid;
1051204076Spjd	bool foreground;
1052204076Spjd	int debuglevel;
1053213009Spjd	sigset_t mask;
1054204076Spjd
1055204076Spjd	foreground = false;
1056204076Spjd	debuglevel = 0;
1057204076Spjd	pidfile = HASTD_PIDFILE;
1058204076Spjd
1059204076Spjd	for (;;) {
1060204076Spjd		int ch;
1061204076Spjd
1062204076Spjd		ch = getopt(argc, argv, "c:dFhP:");
1063204076Spjd		if (ch == -1)
1064204076Spjd			break;
1065204076Spjd		switch (ch) {
1066204076Spjd		case 'c':
1067204076Spjd			cfgpath = optarg;
1068204076Spjd			break;
1069204076Spjd		case 'd':
1070204076Spjd			debuglevel++;
1071204076Spjd			break;
1072204076Spjd		case 'F':
1073204076Spjd			foreground = true;
1074204076Spjd			break;
1075204076Spjd		case 'P':
1076204076Spjd			pidfile = optarg;
1077204076Spjd			break;
1078204076Spjd		case 'h':
1079204076Spjd		default:
1080204076Spjd			usage();
1081204076Spjd		}
1082204076Spjd	}
1083204076Spjd	argc -= optind;
1084204076Spjd	argv += optind;
1085204076Spjd
1086217965Spjd	pjdlog_init(PJDLOG_MODE_STD);
1087204076Spjd	pjdlog_debug_set(debuglevel);
1088204076Spjd
1089214273Spjd	g_gate_load();
1090214273Spjd
1091204076Spjd	pfh = pidfile_open(pidfile, 0600, &otherpid);
1092204076Spjd	if (pfh == NULL) {
1093204076Spjd		if (errno == EEXIST) {
1094204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
1095204076Spjd			    "Another hastd is already running, pid: %jd.",
1096204076Spjd			    (intmax_t)otherpid);
1097204076Spjd		}
1098204076Spjd		/* If we cannot create pidfile from other reasons, only warn. */
1099210879Spjd		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1100204076Spjd	}
1101204076Spjd
1102210883Spjd	cfg = yy_config_parse(cfgpath, true);
1103218138Spjd	PJDLOG_ASSERT(cfg != NULL);
1104204076Spjd
1105213428Spjd	/*
1106217307Spjd	 * Restore default actions for interesting signals in case parent
1107217307Spjd	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1108217307Spjd	 */
1109217307Spjd	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1110217307Spjd	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1111217307Spjd	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1112217307Spjd	/*
1113213428Spjd	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1114213428Spjd	 * so we can mask it.
1115213428Spjd	 */
1116213428Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1117217307Spjd
1118213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1119213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1120213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1121213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1122213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1123213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1124204076Spjd
1125204076Spjd	/* Listen on control address. */
1126204076Spjd	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1127204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1128204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1129204076Spjd		    cfg->hc_controladdr);
1130204076Spjd	}
1131204076Spjd	/* Listen for remote connections. */
1132204076Spjd	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1133204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1134204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1135204076Spjd		    cfg->hc_listenaddr);
1136204076Spjd	}
1137204076Spjd
1138204076Spjd	if (!foreground) {
1139204076Spjd		if (daemon(0, 0) < 0) {
1140204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1141204076Spjd			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1142204076Spjd		}
1143204076Spjd
1144204076Spjd		/* Start logging to syslog. */
1145204076Spjd		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1146204076Spjd
1147204076Spjd		/* Write PID to a file. */
1148204076Spjd		if (pidfile_write(pfh) < 0) {
1149204076Spjd			pjdlog_errno(LOG_WARNING,
1150204076Spjd			    "Unable to write PID to a file");
1151204076Spjd		}
1152204076Spjd	}
1153204076Spjd
1154211977Spjd	hook_init();
1155211977Spjd
1156204076Spjd	main_loop();
1157204076Spjd
1158204076Spjd	exit(0);
1159204076Spjd}
1160