hastd.c revision 213981
180708Sjake/*-
280708Sjake * Copyright (c) 2009-2010 The FreeBSD Foundation
385586Sjake * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
485586Sjake * All rights reserved.
580708Sjake *
680708Sjake * This software was developed by Pawel Jakub Dawidek under sponsorship from
785586Sjake * the FreeBSD Foundation.
885586Sjake *
985586Sjake * Redistribution and use in source and binary forms, with or without
1080708Sjake * modification, are permitted provided that the following conditions
1180708Sjake * are met:
1280708Sjake * 1. Redistributions of source code must retain the above copyright
1380708Sjake *    notice, this list of conditions and the following disclaimer.
1480708Sjake * 2. Redistributions in binary form must reproduce the above copyright
1580708Sjake *    notice, this list of conditions and the following disclaimer in the
1680708Sjake *    documentation and/or other materials provided with the distribution.
1780708Sjake *
1885586Sjake * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
1985586Sjake * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2085586Sjake * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2185586Sjake * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
2285586Sjake * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2385586Sjake * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2485586Sjake * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2580708Sjake * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2685586Sjake * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2785586Sjake * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2885586Sjake * SUCH DAMAGE.
2985586Sjake */
3085586Sjake
3185586Sjake#include <sys/cdefs.h>
3285586Sjake__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 213981 2010-10-17 15:47:27Z pjd $");
3385586Sjake
3485586Sjake#include <sys/param.h>
3585586Sjake#include <sys/linker.h>
3685586Sjake#include <sys/module.h>
3780708Sjake#include <sys/wait.h>
3885586Sjake
3980708Sjake#include <assert.h>
4080708Sjake#include <err.h>
4180708Sjake#include <errno.h>
4280708Sjake#include <libutil.h>
43100384Speter#include <signal.h>
4480708Sjake#include <stdbool.h>
45102808Sjake#include <stdio.h>
46102808Sjake#include <stdlib.h>
4780708Sjake#include <string.h>
48100384Speter#include <sysexits.h>
49100384Speter#include <unistd.h>
50100384Speter
51100384Speter#include <activemap.h>
52100384Speter#include <pjdlog.h>
53102808Sjake
54102808Sjake#include "control.h"
55102808Sjake#include "event.h"
56102808Sjake#include "hast.h"
5780708Sjake#include "hast_proto.h"
5880708Sjake#include "hastd.h"
5985586Sjake#include "hooks.h"
6085586Sjake#include "subr.h"
61100384Speter
62100384Speter/* Path to configuration file. */
63100384Speterconst char *cfgpath = HAST_CONFIG;
64100384Speter/* Hastd configuration. */
65100384Speterstatic struct hastd_config *cfg;
66102808Sjake/* Was SIGINT or SIGTERM signal received? */
67100384Speterbool sigexit_received = false;
68102808Sjake/* PID file handle. */
69102808Sjakestruct pidfh *pfh;
70102808Sjake
71100384Speter/* How often check for hooks running for too long. */
72102555Sjake#define	REPORT_INTERVAL	5
73102555Sjake
74102808Sjakestatic void
75100384Speterusage(void)
76100384Speter{
77100384Speter
78102808Sjake	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
79102808Sjake}
80102808Sjake
81102808Sjakestatic void
82102808Sjakeg_gate_load(void)
83102808Sjake{
84102808Sjake
85102808Sjake	if (modfind("g_gate") == -1) {
86102808Sjake		/* Not present in kernel, try loading it. */
87100384Speter		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
88100384Speter			if (errno != EEXIST) {
89100384Speter				pjdlog_exit(EX_OSERR,
90100384Speter				    "Unable to load geom_gate module");
91100384Speter			}
92100384Speter		}
93100384Speter	}
94100384Speter}
95100384Speter
96100384Speterstatic void
97100384Speterchild_exit_log(unsigned int pid, int status)
98100384Speter{
99100384Speter
100100384Speter	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
101100384Speter		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
10285586Sjake		    pid);
10385586Sjake	} else if (WIFSIGNALED(status)) {
10485586Sjake		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
10585586Sjake		    pid, WTERMSIG(status));
10685586Sjake	} else {
10785586Sjake		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
10885586Sjake		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
10985586Sjake	}
11085586Sjake}
11185586Sjake
11285586Sjakestatic void
11385586Sjakechild_exit(void)
11485586Sjake{
11585586Sjake	struct hast_resource *res;
11685586Sjake	int status;
11785586Sjake	pid_t pid;
11885586Sjake
11985586Sjake	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
12085586Sjake		/* Find resource related to the process that just exited. */
12185586Sjake		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
12285586Sjake			if (pid == res->hr_workerpid)
12385586Sjake				break;
12485586Sjake		}
12585586Sjake		if (res == NULL) {
12685586Sjake			/*
12785586Sjake			 * This can happen when new connection arrives and we
12885586Sjake			 * cancel child responsible for the old one or if this
12985586Sjake			 * was hook which we executed.
13085586Sjake			 */
13185586Sjake			hook_check_one(pid, status);
13285586Sjake			continue;
13385586Sjake		}
134104072Sjake		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
13585586Sjake		    role2str(res->hr_role));
13685586Sjake		child_exit_log(pid, status);
137104072Sjake		child_cleanup(res);
13885586Sjake		if (res->hr_role == HAST_ROLE_PRIMARY) {
13985586Sjake			/*
14085586Sjake			 * Restart child process if it was killed by signal
14185586Sjake			 * or exited because of temporary problem.
14285586Sjake			 */
14385586Sjake			if (WIFSIGNALED(status) ||
14485586Sjake			    (WIFEXITED(status) &&
14585586Sjake			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
14685586Sjake				sleep(1);
147104072Sjake				pjdlog_info("Restarting worker process.");
148104072Sjake				hastd_primary(res);
14985586Sjake			} else {
15085586Sjake				res->hr_role = HAST_ROLE_INIT;
15185586Sjake				pjdlog_info("Changing resource role back to %s.",
15285586Sjake				    role2str(res->hr_role));
15385586Sjake			}
15485586Sjake		}
15585586Sjake		pjdlog_prefix_set("%s", "");
15685586Sjake	}
15785586Sjake}
15885586Sjake
15985586Sjakestatic bool
16085586Sjakeresource_needs_restart(const struct hast_resource *res0,
16185586Sjake    const struct hast_resource *res1)
16285586Sjake{
16385586Sjake
16485586Sjake	assert(strcmp(res0->hr_name, res1->hr_name) == 0);
16585586Sjake
16685586Sjake	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
16785586Sjake		return (true);
16885586Sjake	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
16985586Sjake		return (true);
17085586Sjake	if (res0->hr_role == HAST_ROLE_INIT ||
17185586Sjake	    res0->hr_role == HAST_ROLE_SECONDARY) {
17285586Sjake		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
17385586Sjake			return (true);
17485586Sjake		if (res0->hr_replication != res1->hr_replication)
17585586Sjake			return (true);
17685586Sjake		if (res0->hr_timeout != res1->hr_timeout)
17785586Sjake			return (true);
17885586Sjake		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
17985586Sjake			return (true);
18085586Sjake	}
18185586Sjake	return (false);
18285586Sjake}
18385586Sjake
184104072Sjakestatic bool
185104072Sjakeresource_needs_reload(const struct hast_resource *res0,
186104072Sjake    const struct hast_resource *res1)
187104072Sjake{
188104072Sjake
189104072Sjake	assert(strcmp(res0->hr_name, res1->hr_name) == 0);
190104072Sjake	assert(strcmp(res0->hr_provname, res1->hr_provname) == 0);
191104072Sjake	assert(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
192104072Sjake
193104072Sjake	if (res0->hr_role != HAST_ROLE_PRIMARY)
194104072Sjake		return (false);
195104072Sjake
196104072Sjake	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
197104072Sjake		return (true);
198104072Sjake	if (res0->hr_replication != res1->hr_replication)
199104072Sjake		return (true);
20085586Sjake	if (res0->hr_timeout != res1->hr_timeout)
20185586Sjake		return (true);
20285586Sjake	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
20385586Sjake		return (true);
20485586Sjake	return (false);
20585586Sjake}
20685586Sjake
20785586Sjakestatic void
20885586Sjakehastd_reload(void)
20985586Sjake{
21085586Sjake	struct hastd_config *newcfg;
21185586Sjake	struct hast_resource *nres, *cres, *tres;
21285586Sjake	uint8_t role;
21385586Sjake
21485586Sjake	pjdlog_info("Reloading configuration...");
21585586Sjake
21685586Sjake	newcfg = yy_config_parse(cfgpath, false);
21785586Sjake	if (newcfg == NULL)
21885586Sjake		goto failed;
21985586Sjake
22085586Sjake	/*
22185586Sjake	 * Check if control address has changed.
22285586Sjake	 */
22385586Sjake	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
22485586Sjake		if (proto_server(newcfg->hc_controladdr,
22585586Sjake		    &newcfg->hc_controlconn) < 0) {
22685586Sjake			pjdlog_errno(LOG_ERR,
22785586Sjake			    "Unable to listen on control address %s",
22885586Sjake			    newcfg->hc_controladdr);
22985586Sjake			goto failed;
23085586Sjake		}
23185586Sjake	}
23285586Sjake	/*
23385586Sjake	 * Check if listen address has changed.
23485586Sjake	 */
23585586Sjake	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
23685586Sjake		if (proto_server(newcfg->hc_listenaddr,
23785586Sjake		    &newcfg->hc_listenconn) < 0) {
23885586Sjake			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
23980708Sjake			    newcfg->hc_listenaddr);
24095410Smarcel			goto failed;
24180708Sjake		}
24285586Sjake	}
24385586Sjake	/*
24485586Sjake	 * Only when both control and listen sockets are successfully
24585586Sjake	 * initialized switch them to new configuration.
24695410Smarcel	 */
24785586Sjake	if (newcfg->hc_controlconn != NULL) {
24885586Sjake		pjdlog_info("Control socket changed from %s to %s.",
24998635Smux		    cfg->hc_controladdr, newcfg->hc_controladdr);
25085586Sjake		proto_close(cfg->hc_controlconn);
25185586Sjake		cfg->hc_controlconn = newcfg->hc_controlconn;
25285586Sjake		newcfg->hc_controlconn = NULL;
25385586Sjake		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
25485586Sjake		    sizeof(cfg->hc_controladdr));
25585586Sjake	}
25685586Sjake	if (newcfg->hc_listenconn != NULL) {
25785586Sjake		pjdlog_info("Listen socket changed from %s to %s.",
25885586Sjake		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
25995410Smarcel		proto_close(cfg->hc_listenconn);
26085586Sjake		cfg->hc_listenconn = newcfg->hc_listenconn;
26185586Sjake		newcfg->hc_listenconn = NULL;
26285586Sjake		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
26385586Sjake		    sizeof(cfg->hc_listenaddr));
26485586Sjake	}
26585586Sjake
26685586Sjake	/*
26785586Sjake	 * Stop and remove resources that were removed from the configuration.
26885586Sjake	 */
26985586Sjake	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
27085586Sjake		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
27185586Sjake			if (strcmp(cres->hr_name, nres->hr_name) == 0)
27285586Sjake				break;
27385586Sjake		}
274107517Stmm		if (nres == NULL) {
275107517Stmm			control_set_role(cres, HAST_ROLE_INIT);
276107517Stmm			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
277107517Stmm			pjdlog_info("Resource %s removed.", cres->hr_name);
27885586Sjake			free(cres);
27985586Sjake		}
28085586Sjake	}
28185586Sjake	/*
28285586Sjake	 * Move new resources to the current configuration.
28385586Sjake	 */
28498635Smux	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
28585586Sjake		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
28685586Sjake			if (strcmp(cres->hr_name, nres->hr_name) == 0)
28785586Sjake				break;
28885586Sjake		}
28985586Sjake		if (cres == NULL) {
29085586Sjake			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
29185586Sjake			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
29285586Sjake			pjdlog_info("Resource %s added.", nres->hr_name);
29385586Sjake		}
29485586Sjake	}
29585586Sjake	/*
29685586Sjake	 * Deal with modified resources.
29785586Sjake	 * Depending on what has changed exactly we might want to perform
29880708Sjake	 * different actions.
29980708Sjake	 *
300105469Smarcel	 * We do full resource restart in the following situations:
301105469Smarcel	 * Resource role is INIT or SECONDARY.
302105469Smarcel	 * Resource role is PRIMARY and path to local component or provider
303105469Smarcel	 * name has changed.
304105469Smarcel	 * In case of PRIMARY, the worker process will be killed and restarted,
305105469Smarcel	 * which also means removing /dev/hast/<name> provider and
306105469Smarcel	 * recreating it.
307105469Smarcel	 *
308105469Smarcel	 * We do just reload (send SIGHUP to worker process) if we act as
309105469Smarcel	 * PRIMARY, but only remote address, replication mode and timeout
310105469Smarcel	 * has changed. For those, there is no need to restart worker process.
311105469Smarcel	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
312105469Smarcel	 * replication mode has changed or simply set new timeout if only
313105469Smarcel	 * timeout has changed.
314	 */
315	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
316		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
317			if (strcmp(cres->hr_name, nres->hr_name) == 0)
318				break;
319		}
320		assert(cres != NULL);
321		if (resource_needs_restart(cres, nres)) {
322			pjdlog_info("Resource %s configuration was modified, restarting it.",
323			    cres->hr_name);
324			role = cres->hr_role;
325			control_set_role(cres, HAST_ROLE_INIT);
326			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
327			free(cres);
328			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
329			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
330			control_set_role(nres, role);
331		} else if (resource_needs_reload(cres, nres)) {
332			pjdlog_info("Resource %s configuration was modified, reloading it.",
333			    cres->hr_name);
334			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
335			    sizeof(cres->hr_remoteaddr));
336			cres->hr_replication = nres->hr_replication;
337			cres->hr_timeout = nres->hr_timeout;
338			if (cres->hr_workerpid != 0) {
339				if (kill(cres->hr_workerpid, SIGHUP) < 0) {
340					pjdlog_errno(LOG_WARNING,
341					    "Unable to send SIGHUP to worker process %u",
342					    (unsigned int)cres->hr_workerpid);
343				}
344			}
345		}
346	}
347
348	yy_config_free(newcfg);
349	pjdlog_info("Configuration reloaded successfully.");
350	return;
351failed:
352	if (newcfg != NULL) {
353		if (newcfg->hc_controlconn != NULL)
354			proto_close(newcfg->hc_controlconn);
355		if (newcfg->hc_listenconn != NULL)
356			proto_close(newcfg->hc_listenconn);
357		yy_config_free(newcfg);
358	}
359	pjdlog_warning("Configuration not reloaded.");
360}
361
362static void
363terminate_workers(void)
364{
365	struct hast_resource *res;
366
367	pjdlog_info("Termination signal received, exiting.");
368	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
369		if (res->hr_workerpid == 0)
370			continue;
371		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
372		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
373		if (kill(res->hr_workerpid, SIGTERM) == 0)
374			continue;
375		pjdlog_errno(LOG_WARNING,
376		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
377		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
378	}
379}
380
381static void
382listen_accept(void)
383{
384	struct hast_resource *res;
385	struct proto_conn *conn;
386	struct nv *nvin, *nvout, *nverr;
387	const char *resname;
388	const unsigned char *token;
389	char laddr[256], raddr[256];
390	size_t size;
391	pid_t pid;
392	int status;
393
394	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
395	pjdlog_debug(1, "Accepting connection to %s.", laddr);
396
397	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
398		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
399		return;
400	}
401
402	proto_local_address(conn, laddr, sizeof(laddr));
403	proto_remote_address(conn, raddr, sizeof(raddr));
404	pjdlog_info("Connection from %s to %s.", raddr, laddr);
405
406	/* Error in setting timeout is not critical, but why should it fail? */
407	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
408		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
409
410	nvin = nvout = nverr = NULL;
411
412	/*
413	 * Before receiving any data see if remote host have access to any
414	 * resource.
415	 */
416	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
417		if (proto_address_match(conn, res->hr_remoteaddr))
418			break;
419	}
420	if (res == NULL) {
421		pjdlog_error("Client %s isn't known.", raddr);
422		goto close;
423	}
424	/* Ok, remote host can access at least one resource. */
425
426	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
427		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
428		    raddr);
429		goto close;
430	}
431
432	resname = nv_get_string(nvin, "resource");
433	if (resname == NULL) {
434		pjdlog_error("No 'resource' field in the header received from %s.",
435		    raddr);
436		goto close;
437	}
438	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
439	token = nv_get_uint8_array(nvin, &size, "token");
440	/*
441	 * NULL token means that this is first conection.
442	 */
443	if (token != NULL && size != sizeof(res->hr_token)) {
444		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
445		    raddr, sizeof(res->hr_token), size);
446		goto close;
447	}
448
449	/*
450	 * From now on we want to send errors to the remote node.
451	 */
452	nverr = nv_alloc();
453
454	/* Find resource related to this connection. */
455	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
456		if (strcmp(resname, res->hr_name) == 0)
457			break;
458	}
459	/* Have we found the resource? */
460	if (res == NULL) {
461		pjdlog_error("No resource '%s' as requested by %s.",
462		    resname, raddr);
463		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
464		goto fail;
465	}
466
467	/* Now that we know resource name setup log prefix. */
468	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
469
470	/* Does the remote host have access to this resource? */
471	if (!proto_address_match(conn, res->hr_remoteaddr)) {
472		pjdlog_error("Client %s has no access to the resource.", raddr);
473		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
474		goto fail;
475	}
476	/* Is the resource marked as secondary? */
477	if (res->hr_role != HAST_ROLE_SECONDARY) {
478		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
479		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
480		    raddr);
481		nv_add_stringf(nverr, "errmsg",
482		    "Remote node acts as %s for the resource and not as %s.",
483		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
484		goto fail;
485	}
486	/* Does token (if exists) match? */
487	if (token != NULL && memcmp(token, res->hr_token,
488	    sizeof(res->hr_token)) != 0) {
489		pjdlog_error("Token received from %s doesn't match.", raddr);
490		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
491		goto fail;
492	}
493	/*
494	 * If there is no token, but we have half-open connection
495	 * (only remotein) or full connection (worker process is running)
496	 * we have to cancel those and accept the new connection.
497	 */
498	if (token == NULL) {
499		assert(res->hr_remoteout == NULL);
500		pjdlog_debug(1, "Initial connection from %s.", raddr);
501		if (res->hr_workerpid != 0) {
502			assert(res->hr_remotein == NULL);
503			pjdlog_debug(1,
504			    "Worker process exists (pid=%u), stopping it.",
505			    (unsigned int)res->hr_workerpid);
506			/* Stop child process. */
507			if (kill(res->hr_workerpid, SIGINT) < 0) {
508				pjdlog_errno(LOG_ERR,
509				    "Unable to stop worker process (pid=%u)",
510				    (unsigned int)res->hr_workerpid);
511				/*
512				 * Other than logging the problem we
513				 * ignore it - nothing smart to do.
514				 */
515			}
516			/* Wait for it to exit. */
517			else if ((pid = waitpid(res->hr_workerpid,
518			    &status, 0)) != res->hr_workerpid) {
519				/* We can only log the problem. */
520				pjdlog_errno(LOG_ERR,
521				    "Waiting for worker process (pid=%u) failed",
522				    (unsigned int)res->hr_workerpid);
523			} else {
524				child_exit_log(res->hr_workerpid, status);
525			}
526			child_cleanup(res);
527		} else if (res->hr_remotein != NULL) {
528			char oaddr[256];
529
530			proto_remote_address(res->hr_remotein, oaddr,
531			    sizeof(oaddr));
532			pjdlog_debug(1,
533			    "Canceling half-open connection from %s on connection from %s.",
534			    oaddr, raddr);
535			proto_close(res->hr_remotein);
536			res->hr_remotein = NULL;
537		}
538	}
539
540	/*
541	 * Checks and cleanups are done.
542	 */
543
544	if (token == NULL) {
545		arc4random_buf(res->hr_token, sizeof(res->hr_token));
546		nvout = nv_alloc();
547		nv_add_uint8_array(nvout, res->hr_token,
548		    sizeof(res->hr_token), "token");
549		if (nv_error(nvout) != 0) {
550			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
551			    "Unable to prepare return header for %s", raddr);
552			nv_add_stringf(nverr, "errmsg",
553			    "Remote node was unable to prepare return header: %s.",
554			    strerror(nv_error(nvout)));
555			goto fail;
556		}
557		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
558			int error = errno;
559
560			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
561			    raddr);
562			nv_add_stringf(nverr, "errmsg",
563			    "Remote node was unable to send response: %s.",
564			    strerror(error));
565			goto fail;
566		}
567		res->hr_remotein = conn;
568		pjdlog_debug(1, "Incoming connection from %s configured.",
569		    raddr);
570	} else {
571		res->hr_remoteout = conn;
572		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
573		hastd_secondary(res, nvin);
574	}
575	nv_free(nvin);
576	nv_free(nvout);
577	nv_free(nverr);
578	pjdlog_prefix_set("%s", "");
579	return;
580fail:
581	if (nv_error(nverr) != 0) {
582		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
583		    "Unable to prepare error header for %s", raddr);
584		goto close;
585	}
586	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
587		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
588		goto close;
589	}
590close:
591	if (nvin != NULL)
592		nv_free(nvin);
593	if (nvout != NULL)
594		nv_free(nvout);
595	if (nverr != NULL)
596		nv_free(nverr);
597	proto_close(conn);
598	pjdlog_prefix_set("%s", "");
599}
600
601static void
602main_loop(void)
603{
604	struct hast_resource *res;
605	struct timeval seltimeout;
606	struct timespec sigtimeout;
607	int fd, maxfd, ret, signo;
608	sigset_t mask;
609	fd_set rfds;
610
611	seltimeout.tv_sec = REPORT_INTERVAL;
612	seltimeout.tv_usec = 0;
613	sigtimeout.tv_sec = 0;
614	sigtimeout.tv_nsec = 0;
615
616	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
617	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
618	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
619	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
620	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
621
622	for (;;) {
623		while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
624			switch (signo) {
625			case SIGINT:
626			case SIGTERM:
627				sigexit_received = true;
628				terminate_workers();
629				exit(EX_OK);
630				break;
631			case SIGCHLD:
632				child_exit();
633				break;
634			case SIGHUP:
635				hastd_reload();
636				break;
637			default:
638				assert(!"invalid condition");
639			}
640		}
641
642		/* Setup descriptors for select(2). */
643		FD_ZERO(&rfds);
644		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
645		assert(fd >= 0);
646		FD_SET(fd, &rfds);
647		fd = proto_descriptor(cfg->hc_listenconn);
648		assert(fd >= 0);
649		FD_SET(fd, &rfds);
650		maxfd = fd > maxfd ? fd : maxfd;
651		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
652			if (res->hr_event == NULL)
653				continue;
654			fd = proto_descriptor(res->hr_event);
655			assert(fd >= 0);
656			FD_SET(fd, &rfds);
657			maxfd = fd > maxfd ? fd : maxfd;
658		}
659
660		assert(maxfd + 1 <= (int)FD_SETSIZE);
661		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
662		if (ret == 0)
663			hook_check();
664		else if (ret == -1) {
665			if (errno == EINTR)
666				continue;
667			KEEP_ERRNO((void)pidfile_remove(pfh));
668			pjdlog_exit(EX_OSERR, "select() failed");
669		}
670
671		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
672			control_handle(cfg);
673		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
674			listen_accept();
675		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
676			if (res->hr_event == NULL)
677				continue;
678			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
679				if (event_recv(res) == 0)
680					continue;
681				/* The worker process exited? */
682				proto_close(res->hr_event);
683				res->hr_event = NULL;
684			}
685		}
686	}
687}
688
689static void
690dummy_sighandler(int sig __unused)
691{
692	/* Nothing to do. */
693}
694
695int
696main(int argc, char *argv[])
697{
698	const char *pidfile;
699	pid_t otherpid;
700	bool foreground;
701	int debuglevel;
702	sigset_t mask;
703
704	g_gate_load();
705
706	foreground = false;
707	debuglevel = 0;
708	pidfile = HASTD_PIDFILE;
709
710	for (;;) {
711		int ch;
712
713		ch = getopt(argc, argv, "c:dFhP:");
714		if (ch == -1)
715			break;
716		switch (ch) {
717		case 'c':
718			cfgpath = optarg;
719			break;
720		case 'd':
721			debuglevel++;
722			break;
723		case 'F':
724			foreground = true;
725			break;
726		case 'P':
727			pidfile = optarg;
728			break;
729		case 'h':
730		default:
731			usage();
732		}
733	}
734	argc -= optind;
735	argv += optind;
736
737	pjdlog_debug_set(debuglevel);
738
739	pfh = pidfile_open(pidfile, 0600, &otherpid);
740	if (pfh == NULL) {
741		if (errno == EEXIST) {
742			pjdlog_exitx(EX_TEMPFAIL,
743			    "Another hastd is already running, pid: %jd.",
744			    (intmax_t)otherpid);
745		}
746		/* If we cannot create pidfile from other reasons, only warn. */
747		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
748	}
749
750	cfg = yy_config_parse(cfgpath, true);
751	assert(cfg != NULL);
752
753	/*
754	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
755	 * so we can mask it.
756	 */
757	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
758	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
759	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
760	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
761	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
762	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
763	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
764
765	/* Listen on control address. */
766	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
767		KEEP_ERRNO((void)pidfile_remove(pfh));
768		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
769		    cfg->hc_controladdr);
770	}
771	/* Listen for remote connections. */
772	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
773		KEEP_ERRNO((void)pidfile_remove(pfh));
774		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
775		    cfg->hc_listenaddr);
776	}
777
778	if (!foreground) {
779		if (daemon(0, 0) < 0) {
780			KEEP_ERRNO((void)pidfile_remove(pfh));
781			pjdlog_exit(EX_OSERR, "Unable to daemonize");
782		}
783
784		/* Start logging to syslog. */
785		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
786
787		/* Write PID to a file. */
788		if (pidfile_write(pfh) < 0) {
789			pjdlog_errno(LOG_WARNING,
790			    "Unable to write PID to a file");
791		}
792	}
793
794	hook_init();
795
796	main_loop();
797
798	exit(0);
799}
800