hastd.c revision 219354
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 219354 2011-03-06 23:09:33Z pjd $");
33204076Spjd
34204076Spjd#include <sys/param.h>
35204076Spjd#include <sys/linker.h>
36204076Spjd#include <sys/module.h>
37218044Spjd#include <sys/stat.h>
38204076Spjd#include <sys/wait.h>
39204076Spjd
40204076Spjd#include <err.h>
41204076Spjd#include <errno.h>
42204076Spjd#include <libutil.h>
43204076Spjd#include <signal.h>
44204076Spjd#include <stdbool.h>
45204076Spjd#include <stdio.h>
46204076Spjd#include <stdlib.h>
47204076Spjd#include <string.h>
48204076Spjd#include <sysexits.h>
49204076Spjd#include <unistd.h>
50204076Spjd
51204076Spjd#include <activemap.h>
52204076Spjd#include <pjdlog.h>
53204076Spjd
54204076Spjd#include "control.h"
55212038Spjd#include "event.h"
56204076Spjd#include "hast.h"
57204076Spjd#include "hast_proto.h"
58204076Spjd#include "hastd.h"
59211977Spjd#include "hooks.h"
60204076Spjd#include "subr.h"
61204076Spjd
62204076Spjd/* Path to configuration file. */
63210886Spjdconst char *cfgpath = HAST_CONFIG;
64204076Spjd/* Hastd configuration. */
65204076Spjdstatic struct hastd_config *cfg;
66204076Spjd/* Was SIGINT or SIGTERM signal received? */
67204076Spjdbool sigexit_received = false;
68204076Spjd/* PID file handle. */
69204076Spjdstruct pidfh *pfh;
70204076Spjd
71211977Spjd/* How often check for hooks running for too long. */
72213430Spjd#define	REPORT_INTERVAL	5
73211977Spjd
74204076Spjdstatic void
75204076Spjdusage(void)
76204076Spjd{
77204076Spjd
78204076Spjd	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
79204076Spjd}
80204076Spjd
81204076Spjdstatic void
82204076Spjdg_gate_load(void)
83204076Spjd{
84204076Spjd
85204076Spjd	if (modfind("g_gate") == -1) {
86204076Spjd		/* Not present in kernel, try loading it. */
87204076Spjd		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
88204076Spjd			if (errno != EEXIST) {
89204076Spjd				pjdlog_exit(EX_OSERR,
90204076Spjd				    "Unable to load geom_gate module");
91204076Spjd			}
92204076Spjd		}
93204076Spjd	}
94204076Spjd}
95204076Spjd
96218041Spjdvoid
97218041Spjddescriptors_cleanup(struct hast_resource *res)
98218041Spjd{
99218041Spjd	struct hast_resource *tres;
100218041Spjd
101218041Spjd	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
102218041Spjd		if (tres == res) {
103218041Spjd			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
104218041Spjd			    (res->hr_remotein == NULL &&
105218041Spjd			     res->hr_remoteout == NULL));
106218041Spjd			continue;
107218041Spjd		}
108218041Spjd		if (tres->hr_remotein != NULL)
109218041Spjd			proto_close(tres->hr_remotein);
110218041Spjd		if (tres->hr_remoteout != NULL)
111218041Spjd			proto_close(tres->hr_remoteout);
112218370Spjd		if (tres->hr_ctrl != NULL)
113218370Spjd			proto_close(tres->hr_ctrl);
114218370Spjd		if (tres->hr_event != NULL)
115218370Spjd			proto_close(tres->hr_event);
116218370Spjd		if (tres->hr_conn != NULL)
117218370Spjd			proto_close(tres->hr_conn);
118218041Spjd	}
119218041Spjd	if (cfg->hc_controlin != NULL)
120218041Spjd		proto_close(cfg->hc_controlin);
121218041Spjd	proto_close(cfg->hc_controlconn);
122218041Spjd	proto_close(cfg->hc_listenconn);
123218041Spjd	(void)pidfile_close(pfh);
124218041Spjd	hook_fini();
125218041Spjd	pjdlog_fini();
126218041Spjd}
127218041Spjd
128218044Spjdstatic const char *
129218044Spjddtype2str(mode_t mode)
130218044Spjd{
131218044Spjd
132218044Spjd	if (S_ISBLK(mode))
133218044Spjd		return ("block device");
134218044Spjd	else if (S_ISCHR(mode))
135218044Spjd		return ("character device");
136218044Spjd	else if (S_ISDIR(mode))
137218044Spjd		return ("directory");
138218044Spjd	else if (S_ISFIFO(mode))
139218044Spjd		return ("pipe or FIFO");
140218044Spjd	else if (S_ISLNK(mode))
141218044Spjd		return ("symbolic link");
142218044Spjd	else if (S_ISREG(mode))
143218044Spjd		return ("regular file");
144218044Spjd	else if (S_ISSOCK(mode))
145218044Spjd		return ("socket");
146218044Spjd	else if (S_ISWHT(mode))
147218044Spjd		return ("whiteout");
148218044Spjd	else
149218044Spjd		return ("unknown");
150218044Spjd}
151218044Spjd
152218044Spjdvoid
153218044Spjddescriptors_assert(const struct hast_resource *res, int pjdlogmode)
154218044Spjd{
155218044Spjd	char msg[256];
156218044Spjd	struct stat sb;
157218044Spjd	long maxfd;
158218044Spjd	bool isopen;
159218044Spjd	mode_t mode;
160218044Spjd	int fd;
161218044Spjd
162218044Spjd	/*
163218044Spjd	 * At this point descriptor to syslog socket is closed, so if we want
164218044Spjd	 * to log assertion message, we have to first store it in 'msg' local
165218044Spjd	 * buffer and then open syslog socket and log it.
166218044Spjd	 */
167218044Spjd	msg[0] = '\0';
168218044Spjd
169218044Spjd	maxfd = sysconf(_SC_OPEN_MAX);
170218044Spjd	if (maxfd < 0) {
171218373Spjd		pjdlog_init(pjdlogmode);
172218373Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
173218373Spjd		    role2str(res->hr_role));
174218044Spjd		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
175218373Spjd		pjdlog_fini();
176218044Spjd		maxfd = 16384;
177218044Spjd	}
178218044Spjd	for (fd = 0; fd <= maxfd; fd++) {
179218044Spjd		if (fstat(fd, &sb) == 0) {
180218044Spjd			isopen = true;
181218044Spjd			mode = sb.st_mode;
182218044Spjd		} else if (errno == EBADF) {
183218044Spjd			isopen = false;
184218044Spjd			mode = 0;
185218044Spjd		} else {
186218375Spjd			(void)snprintf(msg, sizeof(msg),
187218044Spjd			    "Unable to fstat descriptor %d: %s", fd,
188218044Spjd			    strerror(errno));
189218374Spjd			break;
190218044Spjd		}
191218044Spjd		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
192218044Spjd		    fd == STDERR_FILENO) {
193218044Spjd			if (!isopen) {
194218375Spjd				(void)snprintf(msg, sizeof(msg),
195218044Spjd				    "Descriptor %d (%s) is closed, but should be open.",
196218044Spjd				    fd, (fd == STDIN_FILENO ? "stdin" :
197218044Spjd				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
198218044Spjd				break;
199218044Spjd			}
200218044Spjd		} else if (fd == proto_descriptor(res->hr_event)) {
201218044Spjd			if (!isopen) {
202218375Spjd				(void)snprintf(msg, sizeof(msg),
203218044Spjd				    "Descriptor %d (event) is closed, but should be open.",
204218044Spjd				    fd);
205218044Spjd				break;
206218044Spjd			}
207218044Spjd			if (!S_ISSOCK(mode)) {
208218375Spjd				(void)snprintf(msg, sizeof(msg),
209218044Spjd				    "Descriptor %d (event) is %s, but should be %s.",
210218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
211218044Spjd				break;
212218044Spjd			}
213218044Spjd		} else if (fd == proto_descriptor(res->hr_ctrl)) {
214218044Spjd			if (!isopen) {
215218375Spjd				(void)snprintf(msg, sizeof(msg),
216218044Spjd				    "Descriptor %d (ctrl) is closed, but should be open.",
217218044Spjd				    fd);
218218044Spjd				break;
219218044Spjd			}
220218044Spjd			if (!S_ISSOCK(mode)) {
221218375Spjd				(void)snprintf(msg, sizeof(msg),
222218044Spjd				    "Descriptor %d (ctrl) is %s, but should be %s.",
223218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
224218044Spjd				break;
225218044Spjd			}
226218218Spjd		} else if (fd == proto_descriptor(res->hr_conn)) {
227218218Spjd			if (!isopen) {
228218375Spjd				(void)snprintf(msg, sizeof(msg),
229218218Spjd				    "Descriptor %d (conn) is closed, but should be open.",
230218218Spjd				    fd);
231218218Spjd				break;
232218218Spjd			}
233218218Spjd			if (!S_ISSOCK(mode)) {
234218375Spjd				(void)snprintf(msg, sizeof(msg),
235218218Spjd				    "Descriptor %d (conn) is %s, but should be %s.",
236218218Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
237218218Spjd				break;
238218218Spjd			}
239218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
240218044Spjd		    fd == proto_descriptor(res->hr_remotein)) {
241218044Spjd			if (!isopen) {
242218375Spjd				(void)snprintf(msg, sizeof(msg),
243218044Spjd				    "Descriptor %d (remote in) is closed, but should be open.",
244218044Spjd				    fd);
245218044Spjd				break;
246218044Spjd			}
247218044Spjd			if (!S_ISSOCK(mode)) {
248218375Spjd				(void)snprintf(msg, sizeof(msg),
249218044Spjd				    "Descriptor %d (remote in) is %s, but should be %s.",
250218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
251218044Spjd				break;
252218044Spjd			}
253218044Spjd		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
254218044Spjd		    fd == proto_descriptor(res->hr_remoteout)) {
255218044Spjd			if (!isopen) {
256218375Spjd				(void)snprintf(msg, sizeof(msg),
257218044Spjd				    "Descriptor %d (remote out) is closed, but should be open.",
258218044Spjd				    fd);
259218044Spjd				break;
260218044Spjd			}
261218044Spjd			if (!S_ISSOCK(mode)) {
262218375Spjd				(void)snprintf(msg, sizeof(msg),
263218044Spjd				    "Descriptor %d (remote out) is %s, but should be %s.",
264218044Spjd				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
265218044Spjd				break;
266218044Spjd			}
267218044Spjd		} else {
268218044Spjd			if (isopen) {
269218375Spjd				(void)snprintf(msg, sizeof(msg),
270218044Spjd				    "Descriptor %d is open (%s), but should be closed.",
271218044Spjd				    fd, dtype2str(mode));
272218044Spjd				break;
273218044Spjd			}
274218044Spjd		}
275218044Spjd	}
276218044Spjd	if (msg[0] != '\0') {
277218044Spjd		pjdlog_init(pjdlogmode);
278218044Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
279218044Spjd		    role2str(res->hr_role));
280218044Spjd		PJDLOG_ABORT("%s", msg);
281218044Spjd	}
282218044Spjd}
283218044Spjd
284204076Spjdstatic void
285207372Spjdchild_exit_log(unsigned int pid, int status)
286207372Spjd{
287207372Spjd
288207372Spjd	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
289207372Spjd		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
290207372Spjd		    pid);
291207372Spjd	} else if (WIFSIGNALED(status)) {
292207372Spjd		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
293207372Spjd		    pid, WTERMSIG(status));
294207372Spjd	} else {
295207372Spjd		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
296207372Spjd		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
297207372Spjd	}
298207372Spjd}
299207372Spjd
300207372Spjdstatic void
301204076Spjdchild_exit(void)
302204076Spjd{
303204076Spjd	struct hast_resource *res;
304204076Spjd	int status;
305204076Spjd	pid_t pid;
306204076Spjd
307204076Spjd	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
308204076Spjd		/* Find resource related to the process that just exited. */
309204076Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
310204076Spjd			if (pid == res->hr_workerpid)
311204076Spjd				break;
312204076Spjd		}
313204076Spjd		if (res == NULL) {
314204076Spjd			/*
315204076Spjd			 * This can happen when new connection arrives and we
316211977Spjd			 * cancel child responsible for the old one or if this
317211977Spjd			 * was hook which we executed.
318204076Spjd			 */
319211977Spjd			hook_check_one(pid, status);
320204076Spjd			continue;
321204076Spjd		}
322204076Spjd		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
323204076Spjd		    role2str(res->hr_role));
324207372Spjd		child_exit_log(pid, status);
325213006Spjd		child_cleanup(res);
326204076Spjd		if (res->hr_role == HAST_ROLE_PRIMARY) {
327207372Spjd			/*
328207372Spjd			 * Restart child process if it was killed by signal
329207372Spjd			 * or exited because of temporary problem.
330207372Spjd			 */
331207372Spjd			if (WIFSIGNALED(status) ||
332207372Spjd			    (WIFEXITED(status) &&
333207372Spjd			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
334207348Spjd				sleep(1);
335207348Spjd				pjdlog_info("Restarting worker process.");
336207348Spjd				hastd_primary(res);
337207348Spjd			} else {
338207348Spjd				res->hr_role = HAST_ROLE_INIT;
339207348Spjd				pjdlog_info("Changing resource role back to %s.",
340207348Spjd				    role2str(res->hr_role));
341207348Spjd			}
342204076Spjd		}
343204076Spjd		pjdlog_prefix_set("%s", "");
344204076Spjd	}
345204076Spjd}
346204076Spjd
347210886Spjdstatic bool
348210886Spjdresource_needs_restart(const struct hast_resource *res0,
349210886Spjd    const struct hast_resource *res1)
350210886Spjd{
351210886Spjd
352218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
353210886Spjd
354210886Spjd	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
355210886Spjd		return (true);
356210886Spjd	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
357210886Spjd		return (true);
358210886Spjd	if (res0->hr_role == HAST_ROLE_INIT ||
359210886Spjd	    res0->hr_role == HAST_ROLE_SECONDARY) {
360210886Spjd		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
361210886Spjd			return (true);
362210886Spjd		if (res0->hr_replication != res1->hr_replication)
363210886Spjd			return (true);
364219351Spjd		if (res0->hr_checksum != res1->hr_checksum)
365219351Spjd			return (true);
366219354Spjd		if (res0->hr_compression != res1->hr_compression)
367219354Spjd			return (true);
368210886Spjd		if (res0->hr_timeout != res1->hr_timeout)
369210886Spjd			return (true);
370211886Spjd		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
371211886Spjd			return (true);
372210886Spjd	}
373210886Spjd	return (false);
374210886Spjd}
375210886Spjd
376210886Spjdstatic bool
377210886Spjdresource_needs_reload(const struct hast_resource *res0,
378210886Spjd    const struct hast_resource *res1)
379210886Spjd{
380210886Spjd
381218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
382218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
383218138Spjd	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
384210886Spjd
385210886Spjd	if (res0->hr_role != HAST_ROLE_PRIMARY)
386210886Spjd		return (false);
387210886Spjd
388210886Spjd	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
389210886Spjd		return (true);
390210886Spjd	if (res0->hr_replication != res1->hr_replication)
391210886Spjd		return (true);
392219351Spjd	if (res0->hr_checksum != res1->hr_checksum)
393219351Spjd		return (true);
394219354Spjd	if (res0->hr_compression != res1->hr_compression)
395219354Spjd		return (true);
396210886Spjd	if (res0->hr_timeout != res1->hr_timeout)
397210886Spjd		return (true);
398211886Spjd	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
399211886Spjd		return (true);
400210886Spjd	return (false);
401210886Spjd}
402210886Spjd
403204076Spjdstatic void
404217784Spjdresource_reload(const struct hast_resource *res)
405217784Spjd{
406217784Spjd	struct nv *nvin, *nvout;
407217784Spjd	int error;
408217784Spjd
409218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
410217784Spjd
411217784Spjd	nvout = nv_alloc();
412217784Spjd	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
413217784Spjd	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
414217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
415219351Spjd	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
416219354Spjd	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
417217784Spjd	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
418217784Spjd	nv_add_string(nvout, res->hr_exec, "exec");
419217784Spjd	if (nv_error(nvout) != 0) {
420217784Spjd		nv_free(nvout);
421217784Spjd		pjdlog_error("Unable to allocate header for reload message.");
422217784Spjd		return;
423217784Spjd	}
424217784Spjd	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
425217784Spjd		pjdlog_errno(LOG_ERR, "Unable to send reload message");
426217784Spjd		nv_free(nvout);
427217784Spjd		return;
428217784Spjd	}
429217784Spjd	nv_free(nvout);
430217784Spjd
431217784Spjd	/* Receive response. */
432217784Spjd	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
433217784Spjd		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
434217784Spjd		return;
435217784Spjd	}
436217784Spjd	error = nv_get_int16(nvin, "error");
437217784Spjd	nv_free(nvin);
438217784Spjd	if (error != 0) {
439217784Spjd		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
440217784Spjd		return;
441217784Spjd	}
442217784Spjd}
443217784Spjd
444217784Spjdstatic void
445204076Spjdhastd_reload(void)
446204076Spjd{
447210886Spjd	struct hastd_config *newcfg;
448210886Spjd	struct hast_resource *nres, *cres, *tres;
449210886Spjd	uint8_t role;
450204076Spjd
451210886Spjd	pjdlog_info("Reloading configuration...");
452210886Spjd
453210886Spjd	newcfg = yy_config_parse(cfgpath, false);
454210886Spjd	if (newcfg == NULL)
455210886Spjd		goto failed;
456210886Spjd
457210886Spjd	/*
458210886Spjd	 * Check if control address has changed.
459210886Spjd	 */
460210886Spjd	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
461210886Spjd		if (proto_server(newcfg->hc_controladdr,
462210886Spjd		    &newcfg->hc_controlconn) < 0) {
463210886Spjd			pjdlog_errno(LOG_ERR,
464210886Spjd			    "Unable to listen on control address %s",
465210886Spjd			    newcfg->hc_controladdr);
466210886Spjd			goto failed;
467210886Spjd		}
468210886Spjd	}
469210886Spjd	/*
470210886Spjd	 * Check if listen address has changed.
471210886Spjd	 */
472210886Spjd	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
473210886Spjd		if (proto_server(newcfg->hc_listenaddr,
474210886Spjd		    &newcfg->hc_listenconn) < 0) {
475210886Spjd			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
476210886Spjd			    newcfg->hc_listenaddr);
477210886Spjd			goto failed;
478210886Spjd		}
479210886Spjd	}
480210886Spjd	/*
481210886Spjd	 * Only when both control and listen sockets are successfully
482210886Spjd	 * initialized switch them to new configuration.
483210886Spjd	 */
484210886Spjd	if (newcfg->hc_controlconn != NULL) {
485210886Spjd		pjdlog_info("Control socket changed from %s to %s.",
486210886Spjd		    cfg->hc_controladdr, newcfg->hc_controladdr);
487210886Spjd		proto_close(cfg->hc_controlconn);
488210886Spjd		cfg->hc_controlconn = newcfg->hc_controlconn;
489210886Spjd		newcfg->hc_controlconn = NULL;
490210886Spjd		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
491210886Spjd		    sizeof(cfg->hc_controladdr));
492210886Spjd	}
493210886Spjd	if (newcfg->hc_listenconn != NULL) {
494210886Spjd		pjdlog_info("Listen socket changed from %s to %s.",
495210886Spjd		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
496210886Spjd		proto_close(cfg->hc_listenconn);
497210886Spjd		cfg->hc_listenconn = newcfg->hc_listenconn;
498210886Spjd		newcfg->hc_listenconn = NULL;
499210886Spjd		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
500210886Spjd		    sizeof(cfg->hc_listenaddr));
501210886Spjd	}
502210886Spjd
503210886Spjd	/*
504210886Spjd	 * Stop and remove resources that were removed from the configuration.
505210886Spjd	 */
506210886Spjd	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
507210886Spjd		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
508210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
509210886Spjd				break;
510210886Spjd		}
511210886Spjd		if (nres == NULL) {
512210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
513210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
514210886Spjd			pjdlog_info("Resource %s removed.", cres->hr_name);
515210886Spjd			free(cres);
516210886Spjd		}
517210886Spjd	}
518210886Spjd	/*
519210886Spjd	 * Move new resources to the current configuration.
520210886Spjd	 */
521210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
522210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
523210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
524210886Spjd				break;
525210886Spjd		}
526210886Spjd		if (cres == NULL) {
527210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
528210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
529210886Spjd			pjdlog_info("Resource %s added.", nres->hr_name);
530210886Spjd		}
531210886Spjd	}
532210886Spjd	/*
533210886Spjd	 * Deal with modified resources.
534210886Spjd	 * Depending on what has changed exactly we might want to perform
535210886Spjd	 * different actions.
536210886Spjd	 *
537210886Spjd	 * We do full resource restart in the following situations:
538210886Spjd	 * Resource role is INIT or SECONDARY.
539210886Spjd	 * Resource role is PRIMARY and path to local component or provider
540210886Spjd	 * name has changed.
541210886Spjd	 * In case of PRIMARY, the worker process will be killed and restarted,
542210886Spjd	 * which also means removing /dev/hast/<name> provider and
543210886Spjd	 * recreating it.
544210886Spjd	 *
545210886Spjd	 * We do just reload (send SIGHUP to worker process) if we act as
546217729Spjd	 * PRIMARY, but only if remote address, replication mode, timeout or
547217729Spjd	 * execution path has changed. For those, there is no need to restart
548217729Spjd	 * worker process.
549210886Spjd	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
550210886Spjd	 * replication mode has changed or simply set new timeout if only
551210886Spjd	 * timeout has changed.
552210886Spjd	 */
553210886Spjd	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
554210886Spjd		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
555210886Spjd			if (strcmp(cres->hr_name, nres->hr_name) == 0)
556210886Spjd				break;
557210886Spjd		}
558218138Spjd		PJDLOG_ASSERT(cres != NULL);
559210886Spjd		if (resource_needs_restart(cres, nres)) {
560210886Spjd			pjdlog_info("Resource %s configuration was modified, restarting it.",
561210886Spjd			    cres->hr_name);
562210886Spjd			role = cres->hr_role;
563210886Spjd			control_set_role(cres, HAST_ROLE_INIT);
564210886Spjd			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
565210886Spjd			free(cres);
566210886Spjd			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
567210886Spjd			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
568210886Spjd			control_set_role(nres, role);
569210886Spjd		} else if (resource_needs_reload(cres, nres)) {
570210886Spjd			pjdlog_info("Resource %s configuration was modified, reloading it.",
571210886Spjd			    cres->hr_name);
572210886Spjd			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
573210886Spjd			    sizeof(cres->hr_remoteaddr));
574210886Spjd			cres->hr_replication = nres->hr_replication;
575219351Spjd			cres->hr_checksum = nres->hr_checksum;
576219354Spjd			cres->hr_compression = nres->hr_compression;
577210886Spjd			cres->hr_timeout = nres->hr_timeout;
578217729Spjd			strlcpy(cres->hr_exec, nres->hr_exec,
579217729Spjd			    sizeof(cres->hr_exec));
580217784Spjd			if (cres->hr_workerpid != 0)
581217784Spjd				resource_reload(cres);
582210886Spjd		}
583210886Spjd	}
584210886Spjd
585210886Spjd	yy_config_free(newcfg);
586210886Spjd	pjdlog_info("Configuration reloaded successfully.");
587210886Spjd	return;
588210886Spjdfailed:
589210886Spjd	if (newcfg != NULL) {
590210886Spjd		if (newcfg->hc_controlconn != NULL)
591210886Spjd			proto_close(newcfg->hc_controlconn);
592210886Spjd		if (newcfg->hc_listenconn != NULL)
593210886Spjd			proto_close(newcfg->hc_listenconn);
594210886Spjd		yy_config_free(newcfg);
595210886Spjd	}
596210886Spjd	pjdlog_warning("Configuration not reloaded.");
597204076Spjd}
598204076Spjd
599204076Spjdstatic void
600211899Spjdterminate_workers(void)
601211899Spjd{
602211899Spjd	struct hast_resource *res;
603211899Spjd
604211899Spjd	pjdlog_info("Termination signal received, exiting.");
605211899Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
606211899Spjd		if (res->hr_workerpid == 0)
607211899Spjd			continue;
608211899Spjd		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
609211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
610211899Spjd		if (kill(res->hr_workerpid, SIGTERM) == 0)
611211899Spjd			continue;
612211899Spjd		pjdlog_errno(LOG_WARNING,
613211899Spjd		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
614211899Spjd		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
615211899Spjd	}
616211899Spjd}
617211899Spjd
618211899Spjdstatic void
619204076Spjdlisten_accept(void)
620204076Spjd{
621204076Spjd	struct hast_resource *res;
622204076Spjd	struct proto_conn *conn;
623204076Spjd	struct nv *nvin, *nvout, *nverr;
624204076Spjd	const char *resname;
625204076Spjd	const unsigned char *token;
626204076Spjd	char laddr[256], raddr[256];
627204076Spjd	size_t size;
628204076Spjd	pid_t pid;
629204076Spjd	int status;
630204076Spjd
631204076Spjd	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
632204076Spjd	pjdlog_debug(1, "Accepting connection to %s.", laddr);
633204076Spjd
634204076Spjd	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
635204076Spjd		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
636204076Spjd		return;
637204076Spjd	}
638204076Spjd
639204076Spjd	proto_local_address(conn, laddr, sizeof(laddr));
640204076Spjd	proto_remote_address(conn, raddr, sizeof(raddr));
641209185Spjd	pjdlog_info("Connection from %s to %s.", raddr, laddr);
642204076Spjd
643207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
644207371Spjd	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
645207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
646207371Spjd
647204076Spjd	nvin = nvout = nverr = NULL;
648204076Spjd
649204076Spjd	/*
650204076Spjd	 * Before receiving any data see if remote host have access to any
651204076Spjd	 * resource.
652204076Spjd	 */
653204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
654204076Spjd		if (proto_address_match(conn, res->hr_remoteaddr))
655204076Spjd			break;
656204076Spjd	}
657204076Spjd	if (res == NULL) {
658204076Spjd		pjdlog_error("Client %s isn't known.", raddr);
659204076Spjd		goto close;
660204076Spjd	}
661204076Spjd	/* Ok, remote host can access at least one resource. */
662204076Spjd
663204076Spjd	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
664204076Spjd		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
665204076Spjd		    raddr);
666204076Spjd		goto close;
667204076Spjd	}
668204076Spjd
669204076Spjd	resname = nv_get_string(nvin, "resource");
670204076Spjd	if (resname == NULL) {
671204076Spjd		pjdlog_error("No 'resource' field in the header received from %s.",
672204076Spjd		    raddr);
673204076Spjd		goto close;
674204076Spjd	}
675204076Spjd	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
676204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
677204076Spjd	/*
678204076Spjd	 * NULL token means that this is first conection.
679204076Spjd	 */
680204076Spjd	if (token != NULL && size != sizeof(res->hr_token)) {
681204076Spjd		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
682204076Spjd		    raddr, sizeof(res->hr_token), size);
683204076Spjd		goto close;
684204076Spjd	}
685204076Spjd
686204076Spjd	/*
687204076Spjd	 * From now on we want to send errors to the remote node.
688204076Spjd	 */
689204076Spjd	nverr = nv_alloc();
690204076Spjd
691204076Spjd	/* Find resource related to this connection. */
692204076Spjd	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
693204076Spjd		if (strcmp(resname, res->hr_name) == 0)
694204076Spjd			break;
695204076Spjd	}
696204076Spjd	/* Have we found the resource? */
697204076Spjd	if (res == NULL) {
698204076Spjd		pjdlog_error("No resource '%s' as requested by %s.",
699204076Spjd		    resname, raddr);
700204076Spjd		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
701204076Spjd		goto fail;
702204076Spjd	}
703204076Spjd
704204076Spjd	/* Now that we know resource name setup log prefix. */
705204076Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
706204076Spjd
707204076Spjd	/* Does the remote host have access to this resource? */
708204076Spjd	if (!proto_address_match(conn, res->hr_remoteaddr)) {
709204076Spjd		pjdlog_error("Client %s has no access to the resource.", raddr);
710204076Spjd		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
711204076Spjd		goto fail;
712204076Spjd	}
713204076Spjd	/* Is the resource marked as secondary? */
714204076Spjd	if (res->hr_role != HAST_ROLE_SECONDARY) {
715204076Spjd		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
716204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
717204076Spjd		    raddr);
718204076Spjd		nv_add_stringf(nverr, "errmsg",
719204076Spjd		    "Remote node acts as %s for the resource and not as %s.",
720204076Spjd		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
721204076Spjd		goto fail;
722204076Spjd	}
723204076Spjd	/* Does token (if exists) match? */
724204076Spjd	if (token != NULL && memcmp(token, res->hr_token,
725204076Spjd	    sizeof(res->hr_token)) != 0) {
726204076Spjd		pjdlog_error("Token received from %s doesn't match.", raddr);
727209185Spjd		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
728204076Spjd		goto fail;
729204076Spjd	}
730204076Spjd	/*
731204076Spjd	 * If there is no token, but we have half-open connection
732204076Spjd	 * (only remotein) or full connection (worker process is running)
733204076Spjd	 * we have to cancel those and accept the new connection.
734204076Spjd	 */
735204076Spjd	if (token == NULL) {
736218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
737204076Spjd		pjdlog_debug(1, "Initial connection from %s.", raddr);
738204076Spjd		if (res->hr_workerpid != 0) {
739218138Spjd			PJDLOG_ASSERT(res->hr_remotein == NULL);
740204076Spjd			pjdlog_debug(1,
741204076Spjd			    "Worker process exists (pid=%u), stopping it.",
742204076Spjd			    (unsigned int)res->hr_workerpid);
743204076Spjd			/* Stop child process. */
744204076Spjd			if (kill(res->hr_workerpid, SIGINT) < 0) {
745204076Spjd				pjdlog_errno(LOG_ERR,
746204076Spjd				    "Unable to stop worker process (pid=%u)",
747204076Spjd				    (unsigned int)res->hr_workerpid);
748204076Spjd				/*
749204076Spjd				 * Other than logging the problem we
750204076Spjd				 * ignore it - nothing smart to do.
751204076Spjd				 */
752204076Spjd			}
753204076Spjd			/* Wait for it to exit. */
754204076Spjd			else if ((pid = waitpid(res->hr_workerpid,
755204076Spjd			    &status, 0)) != res->hr_workerpid) {
756207372Spjd				/* We can only log the problem. */
757204076Spjd				pjdlog_errno(LOG_ERR,
758204076Spjd				    "Waiting for worker process (pid=%u) failed",
759204076Spjd				    (unsigned int)res->hr_workerpid);
760204076Spjd			} else {
761207372Spjd				child_exit_log(res->hr_workerpid, status);
762204076Spjd			}
763213006Spjd			child_cleanup(res);
764204076Spjd		} else if (res->hr_remotein != NULL) {
765204076Spjd			char oaddr[256];
766204076Spjd
767213981Spjd			proto_remote_address(res->hr_remotein, oaddr,
768213981Spjd			    sizeof(oaddr));
769204076Spjd			pjdlog_debug(1,
770204076Spjd			    "Canceling half-open connection from %s on connection from %s.",
771204076Spjd			    oaddr, raddr);
772204076Spjd			proto_close(res->hr_remotein);
773204076Spjd			res->hr_remotein = NULL;
774204076Spjd		}
775204076Spjd	}
776204076Spjd
777204076Spjd	/*
778204076Spjd	 * Checks and cleanups are done.
779204076Spjd	 */
780204076Spjd
781204076Spjd	if (token == NULL) {
782204076Spjd		arc4random_buf(res->hr_token, sizeof(res->hr_token));
783204076Spjd		nvout = nv_alloc();
784204076Spjd		nv_add_uint8_array(nvout, res->hr_token,
785204076Spjd		    sizeof(res->hr_token), "token");
786204076Spjd		if (nv_error(nvout) != 0) {
787204076Spjd			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
788204076Spjd			    "Unable to prepare return header for %s", raddr);
789204076Spjd			nv_add_stringf(nverr, "errmsg",
790204076Spjd			    "Remote node was unable to prepare return header: %s.",
791204076Spjd			    strerror(nv_error(nvout)));
792204076Spjd			goto fail;
793204076Spjd		}
794204076Spjd		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
795204076Spjd			int error = errno;
796204076Spjd
797204076Spjd			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
798204076Spjd			    raddr);
799204076Spjd			nv_add_stringf(nverr, "errmsg",
800204076Spjd			    "Remote node was unable to send response: %s.",
801204076Spjd			    strerror(error));
802204076Spjd			goto fail;
803204076Spjd		}
804204076Spjd		res->hr_remotein = conn;
805204076Spjd		pjdlog_debug(1, "Incoming connection from %s configured.",
806204076Spjd		    raddr);
807204076Spjd	} else {
808204076Spjd		res->hr_remoteout = conn;
809204076Spjd		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
810204076Spjd		hastd_secondary(res, nvin);
811204076Spjd	}
812204076Spjd	nv_free(nvin);
813204076Spjd	nv_free(nvout);
814204076Spjd	nv_free(nverr);
815204076Spjd	pjdlog_prefix_set("%s", "");
816204076Spjd	return;
817204076Spjdfail:
818204076Spjd	if (nv_error(nverr) != 0) {
819204076Spjd		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
820204076Spjd		    "Unable to prepare error header for %s", raddr);
821204076Spjd		goto close;
822204076Spjd	}
823204076Spjd	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
824204076Spjd		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
825204076Spjd		goto close;
826204076Spjd	}
827204076Spjdclose:
828204076Spjd	if (nvin != NULL)
829204076Spjd		nv_free(nvin);
830204076Spjd	if (nvout != NULL)
831204076Spjd		nv_free(nvout);
832204076Spjd	if (nverr != NULL)
833204076Spjd		nv_free(nverr);
834204076Spjd	proto_close(conn);
835204076Spjd	pjdlog_prefix_set("%s", "");
836204076Spjd}
837204076Spjd
838204076Spjdstatic void
839218218Spjdconnection_migrate(struct hast_resource *res)
840218218Spjd{
841218218Spjd	struct proto_conn *conn;
842218218Spjd	int16_t val = 0;
843218218Spjd
844218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
845218218Spjd		pjdlog_errno(LOG_WARNING,
846218218Spjd		    "Unable to receive connection command");
847218218Spjd		return;
848218218Spjd	}
849218218Spjd	if (proto_client(res->hr_remoteaddr, &conn) < 0) {
850218218Spjd		val = errno;
851218218Spjd		pjdlog_errno(LOG_WARNING,
852218218Spjd		    "Unable to create outgoing connection to %s",
853218218Spjd		    res->hr_remoteaddr);
854218218Spjd		goto out;
855218218Spjd	}
856218218Spjd	if (proto_connect(conn, -1) < 0) {
857218218Spjd		val = errno;
858218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
859218218Spjd		    res->hr_remoteaddr);
860218218Spjd		proto_close(conn);
861218218Spjd		goto out;
862218218Spjd	}
863218218Spjd	val = 0;
864218218Spjdout:
865218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
866218218Spjd		pjdlog_errno(LOG_WARNING,
867218218Spjd		    "Unable to send reply to connection request");
868218218Spjd	}
869218218Spjd	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
870218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to send connection");
871218218Spjd}
872218218Spjd
873218218Spjdstatic void
874204076Spjdmain_loop(void)
875204076Spjd{
876212038Spjd	struct hast_resource *res;
877213009Spjd	struct timeval seltimeout;
878213009Spjd	struct timespec sigtimeout;
879213009Spjd	int fd, maxfd, ret, signo;
880213009Spjd	sigset_t mask;
881212037Spjd	fd_set rfds;
882204076Spjd
883213009Spjd	seltimeout.tv_sec = REPORT_INTERVAL;
884213009Spjd	seltimeout.tv_usec = 0;
885213009Spjd	sigtimeout.tv_sec = 0;
886213009Spjd	sigtimeout.tv_nsec = 0;
887211977Spjd
888213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
889213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
890213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
891213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
892213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
893213009Spjd
894216477Spjd	pjdlog_info("Started successfully, running protocol version %d.",
895216477Spjd	    HAST_PROTO_VERSION);
896216477Spjd
897204076Spjd	for (;;) {
898213009Spjd		while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
899213009Spjd			switch (signo) {
900213009Spjd			case SIGINT:
901213009Spjd			case SIGTERM:
902213009Spjd				sigexit_received = true;
903213009Spjd				terminate_workers();
904217967Spjd				proto_close(cfg->hc_controlconn);
905213009Spjd				exit(EX_OK);
906213009Spjd				break;
907213009Spjd			case SIGCHLD:
908213009Spjd				child_exit();
909213009Spjd				break;
910213009Spjd			case SIGHUP:
911213009Spjd				hastd_reload();
912213009Spjd				break;
913213009Spjd			default:
914218138Spjd				PJDLOG_ABORT("Unexpected signal (%d).", signo);
915213009Spjd			}
916211899Spjd		}
917204076Spjd
918209177Spjd		/* Setup descriptors for select(2). */
919204076Spjd		FD_ZERO(&rfds);
920212038Spjd		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
921218138Spjd		PJDLOG_ASSERT(fd >= 0);
922212038Spjd		FD_SET(fd, &rfds);
923212038Spjd		fd = proto_descriptor(cfg->hc_listenconn);
924218138Spjd		PJDLOG_ASSERT(fd >= 0);
925212038Spjd		FD_SET(fd, &rfds);
926212038Spjd		maxfd = fd > maxfd ? fd : maxfd;
927212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
928212038Spjd			if (res->hr_event == NULL)
929212038Spjd				continue;
930218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
931212038Spjd			fd = proto_descriptor(res->hr_event);
932218138Spjd			PJDLOG_ASSERT(fd >= 0);
933212038Spjd			FD_SET(fd, &rfds);
934212038Spjd			maxfd = fd > maxfd ? fd : maxfd;
935218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY) {
936218218Spjd				/* Only primary workers asks for connections. */
937218218Spjd				fd = proto_descriptor(res->hr_conn);
938218218Spjd				PJDLOG_ASSERT(fd >= 0);
939218218Spjd				FD_SET(fd, &rfds);
940218218Spjd				maxfd = fd > maxfd ? fd : maxfd;
941218218Spjd			}
942212038Spjd		}
943204076Spjd
944218138Spjd		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
945213009Spjd		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
946211977Spjd		if (ret == 0)
947213429Spjd			hook_check();
948211977Spjd		else if (ret == -1) {
949204076Spjd			if (errno == EINTR)
950204076Spjd				continue;
951204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
952204076Spjd			pjdlog_exit(EX_OSERR, "select() failed");
953204076Spjd		}
954204076Spjd
955212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
956204076Spjd			control_handle(cfg);
957212038Spjd		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
958204076Spjd			listen_accept();
959212038Spjd		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
960212038Spjd			if (res->hr_event == NULL)
961212038Spjd				continue;
962218218Spjd			PJDLOG_ASSERT(res->hr_conn != NULL);
963212038Spjd			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
964212038Spjd				if (event_recv(res) == 0)
965212038Spjd					continue;
966212038Spjd				/* The worker process exited? */
967212038Spjd				proto_close(res->hr_event);
968212038Spjd				res->hr_event = NULL;
969218218Spjd				proto_close(res->hr_conn);
970218218Spjd				res->hr_conn = NULL;
971218218Spjd				continue;
972212038Spjd			}
973218218Spjd			if (res->hr_role == HAST_ROLE_PRIMARY &&
974218218Spjd			    FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) {
975218218Spjd				connection_migrate(res);
976218218Spjd			}
977212038Spjd		}
978204076Spjd	}
979204076Spjd}
980204076Spjd
981213428Spjdstatic void
982213428Spjddummy_sighandler(int sig __unused)
983213428Spjd{
984213428Spjd	/* Nothing to do. */
985213428Spjd}
986213428Spjd
987204076Spjdint
988204076Spjdmain(int argc, char *argv[])
989204076Spjd{
990204076Spjd	const char *pidfile;
991204076Spjd	pid_t otherpid;
992204076Spjd	bool foreground;
993204076Spjd	int debuglevel;
994213009Spjd	sigset_t mask;
995204076Spjd
996204076Spjd	foreground = false;
997204076Spjd	debuglevel = 0;
998204076Spjd	pidfile = HASTD_PIDFILE;
999204076Spjd
1000204076Spjd	for (;;) {
1001204076Spjd		int ch;
1002204076Spjd
1003204076Spjd		ch = getopt(argc, argv, "c:dFhP:");
1004204076Spjd		if (ch == -1)
1005204076Spjd			break;
1006204076Spjd		switch (ch) {
1007204076Spjd		case 'c':
1008204076Spjd			cfgpath = optarg;
1009204076Spjd			break;
1010204076Spjd		case 'd':
1011204076Spjd			debuglevel++;
1012204076Spjd			break;
1013204076Spjd		case 'F':
1014204076Spjd			foreground = true;
1015204076Spjd			break;
1016204076Spjd		case 'P':
1017204076Spjd			pidfile = optarg;
1018204076Spjd			break;
1019204076Spjd		case 'h':
1020204076Spjd		default:
1021204076Spjd			usage();
1022204076Spjd		}
1023204076Spjd	}
1024204076Spjd	argc -= optind;
1025204076Spjd	argv += optind;
1026204076Spjd
1027217965Spjd	pjdlog_init(PJDLOG_MODE_STD);
1028204076Spjd	pjdlog_debug_set(debuglevel);
1029204076Spjd
1030214273Spjd	g_gate_load();
1031214273Spjd
1032204076Spjd	pfh = pidfile_open(pidfile, 0600, &otherpid);
1033204076Spjd	if (pfh == NULL) {
1034204076Spjd		if (errno == EEXIST) {
1035204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
1036204076Spjd			    "Another hastd is already running, pid: %jd.",
1037204076Spjd			    (intmax_t)otherpid);
1038204076Spjd		}
1039204076Spjd		/* If we cannot create pidfile from other reasons, only warn. */
1040210879Spjd		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1041204076Spjd	}
1042204076Spjd
1043210883Spjd	cfg = yy_config_parse(cfgpath, true);
1044218138Spjd	PJDLOG_ASSERT(cfg != NULL);
1045204076Spjd
1046213428Spjd	/*
1047217307Spjd	 * Restore default actions for interesting signals in case parent
1048217307Spjd	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1049217307Spjd	 */
1050217307Spjd	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1051217307Spjd	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1052217307Spjd	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1053217307Spjd	/*
1054213428Spjd	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1055213428Spjd	 * so we can mask it.
1056213428Spjd	 */
1057213428Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1058217307Spjd
1059213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1060213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1061213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1062213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1063213009Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1064213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1065204076Spjd
1066204076Spjd	/* Listen on control address. */
1067204076Spjd	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1068204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1069204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1070204076Spjd		    cfg->hc_controladdr);
1071204076Spjd	}
1072204076Spjd	/* Listen for remote connections. */
1073204076Spjd	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1074204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
1075204076Spjd		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1076204076Spjd		    cfg->hc_listenaddr);
1077204076Spjd	}
1078204076Spjd
1079204076Spjd	if (!foreground) {
1080204076Spjd		if (daemon(0, 0) < 0) {
1081204076Spjd			KEEP_ERRNO((void)pidfile_remove(pfh));
1082204076Spjd			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1083204076Spjd		}
1084204076Spjd
1085204076Spjd		/* Start logging to syslog. */
1086204076Spjd		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1087204076Spjd
1088204076Spjd		/* Write PID to a file. */
1089204076Spjd		if (pidfile_write(pfh) < 0) {
1090204076Spjd			pjdlog_errno(LOG_WARNING,
1091204076Spjd			    "Unable to write PID to a file");
1092204076Spjd		}
1093204076Spjd	}
1094204076Spjd
1095211977Spjd	hook_init();
1096211977Spjd
1097204076Spjd	main_loop();
1098204076Spjd
1099204076Spjd	exit(0);
1100204076Spjd}
1101