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