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