hastd.c revision 218218
1/*-
2 * Copyright (c) 2009-2010 The FreeBSD Foundation
3 * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4 * All rights reserved.
5 *
6 * This software was developed by Pawel Jakub Dawidek under sponsorship from
7 * the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 */
30
31#include <sys/cdefs.h>
32__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 218218 2011-02-03 11:39:49Z pjd $");
33
34#include <sys/param.h>
35#include <sys/linker.h>
36#include <sys/module.h>
37#include <sys/stat.h>
38#include <sys/wait.h>
39
40#include <err.h>
41#include <errno.h>
42#include <libutil.h>
43#include <signal.h>
44#include <stdbool.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48#include <sysexits.h>
49#include <unistd.h>
50
51#include <activemap.h>
52#include <pjdlog.h>
53
54#include "control.h"
55#include "event.h"
56#include "hast.h"
57#include "hast_proto.h"
58#include "hastd.h"
59#include "hooks.h"
60#include "subr.h"
61
62/* Path to configuration file. */
63const char *cfgpath = HAST_CONFIG;
64/* Hastd configuration. */
65static struct hastd_config *cfg;
66/* Was SIGINT or SIGTERM signal received? */
67bool sigexit_received = false;
68/* PID file handle. */
69struct pidfh *pfh;
70
71/* How often check for hooks running for too long. */
72#define	REPORT_INTERVAL	5
73
74static void
75usage(void)
76{
77
78	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
79}
80
81static void
82g_gate_load(void)
83{
84
85	if (modfind("g_gate") == -1) {
86		/* Not present in kernel, try loading it. */
87		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
88			if (errno != EEXIST) {
89				pjdlog_exit(EX_OSERR,
90				    "Unable to load geom_gate module");
91			}
92		}
93	}
94}
95
96void
97descriptors_cleanup(struct hast_resource *res)
98{
99	struct hast_resource *tres;
100
101	TAILQ_FOREACH(tres, &cfg->hc_resources, hr_next) {
102		if (tres == res) {
103			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
104			    (res->hr_remotein == NULL &&
105			     res->hr_remoteout == NULL));
106			continue;
107		}
108		if (tres->hr_remotein != NULL)
109			proto_close(tres->hr_remotein);
110		if (tres->hr_remoteout != NULL)
111			proto_close(tres->hr_remoteout);
112	}
113	if (cfg->hc_controlin != NULL)
114		proto_close(cfg->hc_controlin);
115	proto_close(cfg->hc_controlconn);
116	proto_close(cfg->hc_listenconn);
117	(void)pidfile_close(pfh);
118	hook_fini();
119	pjdlog_fini();
120}
121
122static const char *
123dtype2str(mode_t mode)
124{
125
126	if (S_ISBLK(mode))
127		return ("block device");
128	else if (S_ISCHR(mode))
129		return ("character device");
130	else if (S_ISDIR(mode))
131		return ("directory");
132	else if (S_ISFIFO(mode))
133		return ("pipe or FIFO");
134	else if (S_ISLNK(mode))
135		return ("symbolic link");
136	else if (S_ISREG(mode))
137		return ("regular file");
138	else if (S_ISSOCK(mode))
139		return ("socket");
140	else if (S_ISWHT(mode))
141		return ("whiteout");
142	else
143		return ("unknown");
144}
145
146void
147descriptors_assert(const struct hast_resource *res, int pjdlogmode)
148{
149	char msg[256];
150	struct stat sb;
151	long maxfd;
152	bool isopen;
153	mode_t mode;
154	int fd;
155
156	/*
157	 * At this point descriptor to syslog socket is closed, so if we want
158	 * to log assertion message, we have to first store it in 'msg' local
159	 * buffer and then open syslog socket and log it.
160	 */
161	msg[0] = '\0';
162
163	maxfd = sysconf(_SC_OPEN_MAX);
164	if (maxfd < 0) {
165		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
166		maxfd = 16384;
167	}
168	for (fd = 0; fd <= maxfd; fd++) {
169		if (fstat(fd, &sb) == 0) {
170			isopen = true;
171			mode = sb.st_mode;
172		} else if (errno == EBADF) {
173			isopen = false;
174			mode = 0;
175		} else {
176			isopen = true;	/* silence gcc */
177			mode = 0;	/* silence gcc */
178			snprintf(msg, sizeof(msg),
179			    "Unable to fstat descriptor %d: %s", fd,
180			    strerror(errno));
181		}
182		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
183		    fd == STDERR_FILENO) {
184			if (!isopen) {
185				snprintf(msg, sizeof(msg),
186				    "Descriptor %d (%s) is closed, but should be open.",
187				    fd, (fd == STDIN_FILENO ? "stdin" :
188				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
189				break;
190			}
191		} else if (fd == proto_descriptor(res->hr_event)) {
192			if (!isopen) {
193				snprintf(msg, sizeof(msg),
194				    "Descriptor %d (event) is closed, but should be open.",
195				    fd);
196				break;
197			}
198			if (!S_ISSOCK(mode)) {
199				snprintf(msg, sizeof(msg),
200				    "Descriptor %d (event) is %s, but should be %s.",
201				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
202				break;
203			}
204		} else if (fd == proto_descriptor(res->hr_ctrl)) {
205			if (!isopen) {
206				snprintf(msg, sizeof(msg),
207				    "Descriptor %d (ctrl) is closed, but should be open.",
208				    fd);
209				break;
210			}
211			if (!S_ISSOCK(mode)) {
212				snprintf(msg, sizeof(msg),
213				    "Descriptor %d (ctrl) is %s, but should be %s.",
214				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
215				break;
216			}
217		} else if (fd == proto_descriptor(res->hr_conn)) {
218			if (!isopen) {
219				snprintf(msg, sizeof(msg),
220				    "Descriptor %d (conn) is closed, but should be open.",
221				    fd);
222				break;
223			}
224			if (!S_ISSOCK(mode)) {
225				snprintf(msg, sizeof(msg),
226				    "Descriptor %d (conn) is %s, but should be %s.",
227				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
228				break;
229			}
230		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
231		    fd == proto_descriptor(res->hr_remotein)) {
232			if (!isopen) {
233				snprintf(msg, sizeof(msg),
234				    "Descriptor %d (remote in) is closed, but should be open.",
235				    fd);
236				break;
237			}
238			if (!S_ISSOCK(mode)) {
239				snprintf(msg, sizeof(msg),
240				    "Descriptor %d (remote in) is %s, but should be %s.",
241				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
242				break;
243			}
244		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
245		    fd == proto_descriptor(res->hr_remoteout)) {
246			if (!isopen) {
247				snprintf(msg, sizeof(msg),
248				    "Descriptor %d (remote out) is closed, but should be open.",
249				    fd);
250				break;
251			}
252			if (!S_ISSOCK(mode)) {
253				snprintf(msg, sizeof(msg),
254				    "Descriptor %d (remote out) is %s, but should be %s.",
255				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
256				break;
257			}
258		} else {
259			if (isopen) {
260				snprintf(msg, sizeof(msg),
261				    "Descriptor %d is open (%s), but should be closed.",
262				    fd, dtype2str(mode));
263				break;
264			}
265		}
266	}
267	if (msg[0] != '\0') {
268		pjdlog_init(pjdlogmode);
269		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
270		    role2str(res->hr_role));
271		PJDLOG_ABORT("%s", msg);
272	}
273}
274
275static void
276child_exit_log(unsigned int pid, int status)
277{
278
279	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
280		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
281		    pid);
282	} else if (WIFSIGNALED(status)) {
283		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
284		    pid, WTERMSIG(status));
285	} else {
286		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
287		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
288	}
289}
290
291static void
292child_exit(void)
293{
294	struct hast_resource *res;
295	int status;
296	pid_t pid;
297
298	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
299		/* Find resource related to the process that just exited. */
300		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
301			if (pid == res->hr_workerpid)
302				break;
303		}
304		if (res == NULL) {
305			/*
306			 * This can happen when new connection arrives and we
307			 * cancel child responsible for the old one or if this
308			 * was hook which we executed.
309			 */
310			hook_check_one(pid, status);
311			continue;
312		}
313		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
314		    role2str(res->hr_role));
315		child_exit_log(pid, status);
316		child_cleanup(res);
317		if (res->hr_role == HAST_ROLE_PRIMARY) {
318			/*
319			 * Restart child process if it was killed by signal
320			 * or exited because of temporary problem.
321			 */
322			if (WIFSIGNALED(status) ||
323			    (WIFEXITED(status) &&
324			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
325				sleep(1);
326				pjdlog_info("Restarting worker process.");
327				hastd_primary(res);
328			} else {
329				res->hr_role = HAST_ROLE_INIT;
330				pjdlog_info("Changing resource role back to %s.",
331				    role2str(res->hr_role));
332			}
333		}
334		pjdlog_prefix_set("%s", "");
335	}
336}
337
338static bool
339resource_needs_restart(const struct hast_resource *res0,
340    const struct hast_resource *res1)
341{
342
343	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
344
345	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
346		return (true);
347	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
348		return (true);
349	if (res0->hr_role == HAST_ROLE_INIT ||
350	    res0->hr_role == HAST_ROLE_SECONDARY) {
351		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
352			return (true);
353		if (res0->hr_replication != res1->hr_replication)
354			return (true);
355		if (res0->hr_timeout != res1->hr_timeout)
356			return (true);
357		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
358			return (true);
359	}
360	return (false);
361}
362
363static bool
364resource_needs_reload(const struct hast_resource *res0,
365    const struct hast_resource *res1)
366{
367
368	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
369	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
370	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
371
372	if (res0->hr_role != HAST_ROLE_PRIMARY)
373		return (false);
374
375	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
376		return (true);
377	if (res0->hr_replication != res1->hr_replication)
378		return (true);
379	if (res0->hr_timeout != res1->hr_timeout)
380		return (true);
381	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
382		return (true);
383	return (false);
384}
385
386static void
387resource_reload(const struct hast_resource *res)
388{
389	struct nv *nvin, *nvout;
390	int error;
391
392	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
393
394	nvout = nv_alloc();
395	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
396	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
397	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
398	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
399	nv_add_string(nvout, res->hr_exec, "exec");
400	if (nv_error(nvout) != 0) {
401		nv_free(nvout);
402		pjdlog_error("Unable to allocate header for reload message.");
403		return;
404	}
405	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
406		pjdlog_errno(LOG_ERR, "Unable to send reload message");
407		nv_free(nvout);
408		return;
409	}
410	nv_free(nvout);
411
412	/* Receive response. */
413	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
414		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
415		return;
416	}
417	error = nv_get_int16(nvin, "error");
418	nv_free(nvin);
419	if (error != 0) {
420		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
421		return;
422	}
423}
424
425static void
426hastd_reload(void)
427{
428	struct hastd_config *newcfg;
429	struct hast_resource *nres, *cres, *tres;
430	uint8_t role;
431
432	pjdlog_info("Reloading configuration...");
433
434	newcfg = yy_config_parse(cfgpath, false);
435	if (newcfg == NULL)
436		goto failed;
437
438	/*
439	 * Check if control address has changed.
440	 */
441	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
442		if (proto_server(newcfg->hc_controladdr,
443		    &newcfg->hc_controlconn) < 0) {
444			pjdlog_errno(LOG_ERR,
445			    "Unable to listen on control address %s",
446			    newcfg->hc_controladdr);
447			goto failed;
448		}
449	}
450	/*
451	 * Check if listen address has changed.
452	 */
453	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
454		if (proto_server(newcfg->hc_listenaddr,
455		    &newcfg->hc_listenconn) < 0) {
456			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
457			    newcfg->hc_listenaddr);
458			goto failed;
459		}
460	}
461	/*
462	 * Only when both control and listen sockets are successfully
463	 * initialized switch them to new configuration.
464	 */
465	if (newcfg->hc_controlconn != NULL) {
466		pjdlog_info("Control socket changed from %s to %s.",
467		    cfg->hc_controladdr, newcfg->hc_controladdr);
468		proto_close(cfg->hc_controlconn);
469		cfg->hc_controlconn = newcfg->hc_controlconn;
470		newcfg->hc_controlconn = NULL;
471		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
472		    sizeof(cfg->hc_controladdr));
473	}
474	if (newcfg->hc_listenconn != NULL) {
475		pjdlog_info("Listen socket changed from %s to %s.",
476		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
477		proto_close(cfg->hc_listenconn);
478		cfg->hc_listenconn = newcfg->hc_listenconn;
479		newcfg->hc_listenconn = NULL;
480		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
481		    sizeof(cfg->hc_listenaddr));
482	}
483
484	/*
485	 * Stop and remove resources that were removed from the configuration.
486	 */
487	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
488		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
489			if (strcmp(cres->hr_name, nres->hr_name) == 0)
490				break;
491		}
492		if (nres == NULL) {
493			control_set_role(cres, HAST_ROLE_INIT);
494			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
495			pjdlog_info("Resource %s removed.", cres->hr_name);
496			free(cres);
497		}
498	}
499	/*
500	 * Move new resources to the current configuration.
501	 */
502	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
503		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
504			if (strcmp(cres->hr_name, nres->hr_name) == 0)
505				break;
506		}
507		if (cres == NULL) {
508			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
509			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
510			pjdlog_info("Resource %s added.", nres->hr_name);
511		}
512	}
513	/*
514	 * Deal with modified resources.
515	 * Depending on what has changed exactly we might want to perform
516	 * different actions.
517	 *
518	 * We do full resource restart in the following situations:
519	 * Resource role is INIT or SECONDARY.
520	 * Resource role is PRIMARY and path to local component or provider
521	 * name has changed.
522	 * In case of PRIMARY, the worker process will be killed and restarted,
523	 * which also means removing /dev/hast/<name> provider and
524	 * recreating it.
525	 *
526	 * We do just reload (send SIGHUP to worker process) if we act as
527	 * PRIMARY, but only if remote address, replication mode, timeout or
528	 * execution path has changed. For those, there is no need to restart
529	 * worker process.
530	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
531	 * replication mode has changed or simply set new timeout if only
532	 * timeout has changed.
533	 */
534	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
535		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
536			if (strcmp(cres->hr_name, nres->hr_name) == 0)
537				break;
538		}
539		PJDLOG_ASSERT(cres != NULL);
540		if (resource_needs_restart(cres, nres)) {
541			pjdlog_info("Resource %s configuration was modified, restarting it.",
542			    cres->hr_name);
543			role = cres->hr_role;
544			control_set_role(cres, HAST_ROLE_INIT);
545			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
546			free(cres);
547			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
548			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
549			control_set_role(nres, role);
550		} else if (resource_needs_reload(cres, nres)) {
551			pjdlog_info("Resource %s configuration was modified, reloading it.",
552			    cres->hr_name);
553			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
554			    sizeof(cres->hr_remoteaddr));
555			cres->hr_replication = nres->hr_replication;
556			cres->hr_timeout = nres->hr_timeout;
557			strlcpy(cres->hr_exec, nres->hr_exec,
558			    sizeof(cres->hr_exec));
559			if (cres->hr_workerpid != 0)
560				resource_reload(cres);
561		}
562	}
563
564	yy_config_free(newcfg);
565	pjdlog_info("Configuration reloaded successfully.");
566	return;
567failed:
568	if (newcfg != NULL) {
569		if (newcfg->hc_controlconn != NULL)
570			proto_close(newcfg->hc_controlconn);
571		if (newcfg->hc_listenconn != NULL)
572			proto_close(newcfg->hc_listenconn);
573		yy_config_free(newcfg);
574	}
575	pjdlog_warning("Configuration not reloaded.");
576}
577
578static void
579terminate_workers(void)
580{
581	struct hast_resource *res;
582
583	pjdlog_info("Termination signal received, exiting.");
584	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
585		if (res->hr_workerpid == 0)
586			continue;
587		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
588		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
589		if (kill(res->hr_workerpid, SIGTERM) == 0)
590			continue;
591		pjdlog_errno(LOG_WARNING,
592		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
593		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
594	}
595}
596
597static void
598listen_accept(void)
599{
600	struct hast_resource *res;
601	struct proto_conn *conn;
602	struct nv *nvin, *nvout, *nverr;
603	const char *resname;
604	const unsigned char *token;
605	char laddr[256], raddr[256];
606	size_t size;
607	pid_t pid;
608	int status;
609
610	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
611	pjdlog_debug(1, "Accepting connection to %s.", laddr);
612
613	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
614		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
615		return;
616	}
617
618	proto_local_address(conn, laddr, sizeof(laddr));
619	proto_remote_address(conn, raddr, sizeof(raddr));
620	pjdlog_info("Connection from %s to %s.", raddr, laddr);
621
622	/* Error in setting timeout is not critical, but why should it fail? */
623	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
624		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
625
626	nvin = nvout = nverr = NULL;
627
628	/*
629	 * Before receiving any data see if remote host have access to any
630	 * resource.
631	 */
632	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
633		if (proto_address_match(conn, res->hr_remoteaddr))
634			break;
635	}
636	if (res == NULL) {
637		pjdlog_error("Client %s isn't known.", raddr);
638		goto close;
639	}
640	/* Ok, remote host can access at least one resource. */
641
642	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
643		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
644		    raddr);
645		goto close;
646	}
647
648	resname = nv_get_string(nvin, "resource");
649	if (resname == NULL) {
650		pjdlog_error("No 'resource' field in the header received from %s.",
651		    raddr);
652		goto close;
653	}
654	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
655	token = nv_get_uint8_array(nvin, &size, "token");
656	/*
657	 * NULL token means that this is first conection.
658	 */
659	if (token != NULL && size != sizeof(res->hr_token)) {
660		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
661		    raddr, sizeof(res->hr_token), size);
662		goto close;
663	}
664
665	/*
666	 * From now on we want to send errors to the remote node.
667	 */
668	nverr = nv_alloc();
669
670	/* Find resource related to this connection. */
671	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
672		if (strcmp(resname, res->hr_name) == 0)
673			break;
674	}
675	/* Have we found the resource? */
676	if (res == NULL) {
677		pjdlog_error("No resource '%s' as requested by %s.",
678		    resname, raddr);
679		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
680		goto fail;
681	}
682
683	/* Now that we know resource name setup log prefix. */
684	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
685
686	/* Does the remote host have access to this resource? */
687	if (!proto_address_match(conn, res->hr_remoteaddr)) {
688		pjdlog_error("Client %s has no access to the resource.", raddr);
689		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
690		goto fail;
691	}
692	/* Is the resource marked as secondary? */
693	if (res->hr_role != HAST_ROLE_SECONDARY) {
694		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
695		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
696		    raddr);
697		nv_add_stringf(nverr, "errmsg",
698		    "Remote node acts as %s for the resource and not as %s.",
699		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
700		goto fail;
701	}
702	/* Does token (if exists) match? */
703	if (token != NULL && memcmp(token, res->hr_token,
704	    sizeof(res->hr_token)) != 0) {
705		pjdlog_error("Token received from %s doesn't match.", raddr);
706		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
707		goto fail;
708	}
709	/*
710	 * If there is no token, but we have half-open connection
711	 * (only remotein) or full connection (worker process is running)
712	 * we have to cancel those and accept the new connection.
713	 */
714	if (token == NULL) {
715		PJDLOG_ASSERT(res->hr_remoteout == NULL);
716		pjdlog_debug(1, "Initial connection from %s.", raddr);
717		if (res->hr_workerpid != 0) {
718			PJDLOG_ASSERT(res->hr_remotein == NULL);
719			pjdlog_debug(1,
720			    "Worker process exists (pid=%u), stopping it.",
721			    (unsigned int)res->hr_workerpid);
722			/* Stop child process. */
723			if (kill(res->hr_workerpid, SIGINT) < 0) {
724				pjdlog_errno(LOG_ERR,
725				    "Unable to stop worker process (pid=%u)",
726				    (unsigned int)res->hr_workerpid);
727				/*
728				 * Other than logging the problem we
729				 * ignore it - nothing smart to do.
730				 */
731			}
732			/* Wait for it to exit. */
733			else if ((pid = waitpid(res->hr_workerpid,
734			    &status, 0)) != res->hr_workerpid) {
735				/* We can only log the problem. */
736				pjdlog_errno(LOG_ERR,
737				    "Waiting for worker process (pid=%u) failed",
738				    (unsigned int)res->hr_workerpid);
739			} else {
740				child_exit_log(res->hr_workerpid, status);
741			}
742			child_cleanup(res);
743		} else if (res->hr_remotein != NULL) {
744			char oaddr[256];
745
746			proto_remote_address(res->hr_remotein, oaddr,
747			    sizeof(oaddr));
748			pjdlog_debug(1,
749			    "Canceling half-open connection from %s on connection from %s.",
750			    oaddr, raddr);
751			proto_close(res->hr_remotein);
752			res->hr_remotein = NULL;
753		}
754	}
755
756	/*
757	 * Checks and cleanups are done.
758	 */
759
760	if (token == NULL) {
761		arc4random_buf(res->hr_token, sizeof(res->hr_token));
762		nvout = nv_alloc();
763		nv_add_uint8_array(nvout, res->hr_token,
764		    sizeof(res->hr_token), "token");
765		if (nv_error(nvout) != 0) {
766			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
767			    "Unable to prepare return header for %s", raddr);
768			nv_add_stringf(nverr, "errmsg",
769			    "Remote node was unable to prepare return header: %s.",
770			    strerror(nv_error(nvout)));
771			goto fail;
772		}
773		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
774			int error = errno;
775
776			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
777			    raddr);
778			nv_add_stringf(nverr, "errmsg",
779			    "Remote node was unable to send response: %s.",
780			    strerror(error));
781			goto fail;
782		}
783		res->hr_remotein = conn;
784		pjdlog_debug(1, "Incoming connection from %s configured.",
785		    raddr);
786	} else {
787		res->hr_remoteout = conn;
788		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
789		hastd_secondary(res, nvin);
790	}
791	nv_free(nvin);
792	nv_free(nvout);
793	nv_free(nverr);
794	pjdlog_prefix_set("%s", "");
795	return;
796fail:
797	if (nv_error(nverr) != 0) {
798		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
799		    "Unable to prepare error header for %s", raddr);
800		goto close;
801	}
802	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
803		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
804		goto close;
805	}
806close:
807	if (nvin != NULL)
808		nv_free(nvin);
809	if (nvout != NULL)
810		nv_free(nvout);
811	if (nverr != NULL)
812		nv_free(nverr);
813	proto_close(conn);
814	pjdlog_prefix_set("%s", "");
815}
816
817static void
818connection_migrate(struct hast_resource *res)
819{
820	struct proto_conn *conn;
821	int16_t val = 0;
822
823	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
824		pjdlog_errno(LOG_WARNING,
825		    "Unable to receive connection command");
826		return;
827	}
828	if (proto_client(res->hr_remoteaddr, &conn) < 0) {
829		val = errno;
830		pjdlog_errno(LOG_WARNING,
831		    "Unable to create outgoing connection to %s",
832		    res->hr_remoteaddr);
833		goto out;
834	}
835	if (proto_connect(conn, -1) < 0) {
836		val = errno;
837		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
838		    res->hr_remoteaddr);
839		proto_close(conn);
840		goto out;
841	}
842	val = 0;
843out:
844	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
845		pjdlog_errno(LOG_WARNING,
846		    "Unable to send reply to connection request");
847	}
848	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
849		pjdlog_errno(LOG_WARNING, "Unable to send connection");
850}
851
852static void
853main_loop(void)
854{
855	struct hast_resource *res;
856	struct timeval seltimeout;
857	struct timespec sigtimeout;
858	int fd, maxfd, ret, signo;
859	sigset_t mask;
860	fd_set rfds;
861
862	seltimeout.tv_sec = REPORT_INTERVAL;
863	seltimeout.tv_usec = 0;
864	sigtimeout.tv_sec = 0;
865	sigtimeout.tv_nsec = 0;
866
867	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
868	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
869	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
870	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
871	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
872
873	pjdlog_info("Started successfully, running protocol version %d.",
874	    HAST_PROTO_VERSION);
875
876	for (;;) {
877		while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
878			switch (signo) {
879			case SIGINT:
880			case SIGTERM:
881				sigexit_received = true;
882				terminate_workers();
883				proto_close(cfg->hc_controlconn);
884				exit(EX_OK);
885				break;
886			case SIGCHLD:
887				child_exit();
888				break;
889			case SIGHUP:
890				hastd_reload();
891				break;
892			default:
893				PJDLOG_ABORT("Unexpected signal (%d).", signo);
894			}
895		}
896
897		/* Setup descriptors for select(2). */
898		FD_ZERO(&rfds);
899		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
900		PJDLOG_ASSERT(fd >= 0);
901		FD_SET(fd, &rfds);
902		fd = proto_descriptor(cfg->hc_listenconn);
903		PJDLOG_ASSERT(fd >= 0);
904		FD_SET(fd, &rfds);
905		maxfd = fd > maxfd ? fd : maxfd;
906		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
907			if (res->hr_event == NULL)
908				continue;
909			PJDLOG_ASSERT(res->hr_conn != NULL);
910			fd = proto_descriptor(res->hr_event);
911			PJDLOG_ASSERT(fd >= 0);
912			FD_SET(fd, &rfds);
913			maxfd = fd > maxfd ? fd : maxfd;
914			if (res->hr_role == HAST_ROLE_PRIMARY) {
915				/* Only primary workers asks for connections. */
916				fd = proto_descriptor(res->hr_conn);
917				PJDLOG_ASSERT(fd >= 0);
918				FD_SET(fd, &rfds);
919				maxfd = fd > maxfd ? fd : maxfd;
920			}
921		}
922
923		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
924		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
925		if (ret == 0)
926			hook_check();
927		else if (ret == -1) {
928			if (errno == EINTR)
929				continue;
930			KEEP_ERRNO((void)pidfile_remove(pfh));
931			pjdlog_exit(EX_OSERR, "select() failed");
932		}
933
934		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
935			control_handle(cfg);
936		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
937			listen_accept();
938		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
939			if (res->hr_event == NULL)
940				continue;
941			PJDLOG_ASSERT(res->hr_conn != NULL);
942			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
943				if (event_recv(res) == 0)
944					continue;
945				/* The worker process exited? */
946				proto_close(res->hr_event);
947				res->hr_event = NULL;
948				proto_close(res->hr_conn);
949				res->hr_conn = NULL;
950				continue;
951			}
952			if (res->hr_role == HAST_ROLE_PRIMARY &&
953			    FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) {
954				connection_migrate(res);
955			}
956		}
957	}
958}
959
960static void
961dummy_sighandler(int sig __unused)
962{
963	/* Nothing to do. */
964}
965
966int
967main(int argc, char *argv[])
968{
969	const char *pidfile;
970	pid_t otherpid;
971	bool foreground;
972	int debuglevel;
973	sigset_t mask;
974
975	foreground = false;
976	debuglevel = 0;
977	pidfile = HASTD_PIDFILE;
978
979	for (;;) {
980		int ch;
981
982		ch = getopt(argc, argv, "c:dFhP:");
983		if (ch == -1)
984			break;
985		switch (ch) {
986		case 'c':
987			cfgpath = optarg;
988			break;
989		case 'd':
990			debuglevel++;
991			break;
992		case 'F':
993			foreground = true;
994			break;
995		case 'P':
996			pidfile = optarg;
997			break;
998		case 'h':
999		default:
1000			usage();
1001		}
1002	}
1003	argc -= optind;
1004	argv += optind;
1005
1006	pjdlog_init(PJDLOG_MODE_STD);
1007	pjdlog_debug_set(debuglevel);
1008
1009	g_gate_load();
1010
1011	pfh = pidfile_open(pidfile, 0600, &otherpid);
1012	if (pfh == NULL) {
1013		if (errno == EEXIST) {
1014			pjdlog_exitx(EX_TEMPFAIL,
1015			    "Another hastd is already running, pid: %jd.",
1016			    (intmax_t)otherpid);
1017		}
1018		/* If we cannot create pidfile from other reasons, only warn. */
1019		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1020	}
1021
1022	cfg = yy_config_parse(cfgpath, true);
1023	PJDLOG_ASSERT(cfg != NULL);
1024
1025	/*
1026	 * Restore default actions for interesting signals in case parent
1027	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1028	 */
1029	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1030	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1031	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1032	/*
1033	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1034	 * so we can mask it.
1035	 */
1036	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1037
1038	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1039	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1040	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1041	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1042	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1043	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1044
1045	/* Listen on control address. */
1046	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1047		KEEP_ERRNO((void)pidfile_remove(pfh));
1048		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1049		    cfg->hc_controladdr);
1050	}
1051	/* Listen for remote connections. */
1052	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1053		KEEP_ERRNO((void)pidfile_remove(pfh));
1054		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1055		    cfg->hc_listenaddr);
1056	}
1057
1058	if (!foreground) {
1059		if (daemon(0, 0) < 0) {
1060			KEEP_ERRNO((void)pidfile_remove(pfh));
1061			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1062		}
1063
1064		/* Start logging to syslog. */
1065		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1066
1067		/* Write PID to a file. */
1068		if (pidfile_write(pfh) < 0) {
1069			pjdlog_errno(LOG_WARNING,
1070			    "Unable to write PID to a file");
1071		}
1072	}
1073
1074	hook_init();
1075
1076	main_loop();
1077
1078	exit(0);
1079}
1080