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