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