xref: /freebsd/sbin/hastd/hastd.c (revision 01ded8b942effbbb4d9225c4227f264e499e9698)
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$");
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. */
63 const char *cfgpath = HAST_CONFIG;
64 /* Hastd configuration. */
65 static struct hastd_config *cfg;
66 /* Was SIGINT or SIGTERM signal received? */
67 bool sigexit_received = false;
68 /* PID file handle. */
69 struct pidfh *pfh;
70 
71 /* How often check for hooks running for too long. */
72 #define	REPORT_INTERVAL	5
73 
74 static void
75 usage(void)
76 {
77 
78 	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
79 }
80 
81 static void
82 g_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 
96 void
97 descriptors_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 
128 static const char *
129 dtype2str(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 
152 void
153 descriptors_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 
284 static void
285 child_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 
300 static void
301 child_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 
347 static bool
348 resource_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_compression != res1->hr_compression)
367 			return (true);
368 		if (res0->hr_timeout != res1->hr_timeout)
369 			return (true);
370 		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
371 			return (true);
372 	}
373 	return (false);
374 }
375 
376 static bool
377 resource_needs_reload(const struct hast_resource *res0,
378     const struct hast_resource *res1)
379 {
380 
381 	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
382 	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
383 	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
384 
385 	if (res0->hr_role != HAST_ROLE_PRIMARY)
386 		return (false);
387 
388 	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
389 		return (true);
390 	if (res0->hr_replication != res1->hr_replication)
391 		return (true);
392 	if (res0->hr_checksum != res1->hr_checksum)
393 		return (true);
394 	if (res0->hr_compression != res1->hr_compression)
395 		return (true);
396 	if (res0->hr_timeout != res1->hr_timeout)
397 		return (true);
398 	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
399 		return (true);
400 	return (false);
401 }
402 
403 static void
404 resource_reload(const struct hast_resource *res)
405 {
406 	struct nv *nvin, *nvout;
407 	int error;
408 
409 	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
410 
411 	nvout = nv_alloc();
412 	nv_add_uint8(nvout, HASTCTL_RELOAD, "cmd");
413 	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
414 	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
415 	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
416 	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
417 	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
418 	nv_add_string(nvout, res->hr_exec, "exec");
419 	if (nv_error(nvout) != 0) {
420 		nv_free(nvout);
421 		pjdlog_error("Unable to allocate header for reload message.");
422 		return;
423 	}
424 	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) < 0) {
425 		pjdlog_errno(LOG_ERR, "Unable to send reload message");
426 		nv_free(nvout);
427 		return;
428 	}
429 	nv_free(nvout);
430 
431 	/* Receive response. */
432 	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) < 0) {
433 		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
434 		return;
435 	}
436 	error = nv_get_int16(nvin, "error");
437 	nv_free(nvin);
438 	if (error != 0) {
439 		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
440 		return;
441 	}
442 }
443 
444 static void
445 hastd_reload(void)
446 {
447 	struct hastd_config *newcfg;
448 	struct hast_resource *nres, *cres, *tres;
449 	uint8_t role;
450 
451 	pjdlog_info("Reloading configuration...");
452 
453 	newcfg = yy_config_parse(cfgpath, false);
454 	if (newcfg == NULL)
455 		goto failed;
456 
457 	/*
458 	 * Check if control address has changed.
459 	 */
460 	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
461 		if (proto_server(newcfg->hc_controladdr,
462 		    &newcfg->hc_controlconn) < 0) {
463 			pjdlog_errno(LOG_ERR,
464 			    "Unable to listen on control address %s",
465 			    newcfg->hc_controladdr);
466 			goto failed;
467 		}
468 	}
469 	/*
470 	 * Check if listen address has changed.
471 	 */
472 	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
473 		if (proto_server(newcfg->hc_listenaddr,
474 		    &newcfg->hc_listenconn) < 0) {
475 			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
476 			    newcfg->hc_listenaddr);
477 			goto failed;
478 		}
479 	}
480 	/*
481 	 * Only when both control and listen sockets are successfully
482 	 * initialized switch them to new configuration.
483 	 */
484 	if (newcfg->hc_controlconn != NULL) {
485 		pjdlog_info("Control socket changed from %s to %s.",
486 		    cfg->hc_controladdr, newcfg->hc_controladdr);
487 		proto_close(cfg->hc_controlconn);
488 		cfg->hc_controlconn = newcfg->hc_controlconn;
489 		newcfg->hc_controlconn = NULL;
490 		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
491 		    sizeof(cfg->hc_controladdr));
492 	}
493 	if (newcfg->hc_listenconn != NULL) {
494 		pjdlog_info("Listen socket changed from %s to %s.",
495 		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
496 		proto_close(cfg->hc_listenconn);
497 		cfg->hc_listenconn = newcfg->hc_listenconn;
498 		newcfg->hc_listenconn = NULL;
499 		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
500 		    sizeof(cfg->hc_listenaddr));
501 	}
502 
503 	/*
504 	 * Stop and remove resources that were removed from the configuration.
505 	 */
506 	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
507 		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
508 			if (strcmp(cres->hr_name, nres->hr_name) == 0)
509 				break;
510 		}
511 		if (nres == NULL) {
512 			control_set_role(cres, HAST_ROLE_INIT);
513 			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
514 			pjdlog_info("Resource %s removed.", cres->hr_name);
515 			free(cres);
516 		}
517 	}
518 	/*
519 	 * Move new resources to the current configuration.
520 	 */
521 	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
522 		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
523 			if (strcmp(cres->hr_name, nres->hr_name) == 0)
524 				break;
525 		}
526 		if (cres == NULL) {
527 			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
528 			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
529 			pjdlog_info("Resource %s added.", nres->hr_name);
530 		}
531 	}
532 	/*
533 	 * Deal with modified resources.
534 	 * Depending on what has changed exactly we might want to perform
535 	 * different actions.
536 	 *
537 	 * We do full resource restart in the following situations:
538 	 * Resource role is INIT or SECONDARY.
539 	 * Resource role is PRIMARY and path to local component or provider
540 	 * name has changed.
541 	 * In case of PRIMARY, the worker process will be killed and restarted,
542 	 * which also means removing /dev/hast/<name> provider and
543 	 * recreating it.
544 	 *
545 	 * We do just reload (send SIGHUP to worker process) if we act as
546 	 * PRIMARY, but only if remote address, replication mode, timeout or
547 	 * execution path has changed. For those, there is no need to restart
548 	 * worker process.
549 	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
550 	 * replication mode has changed or simply set new timeout if only
551 	 * timeout has changed.
552 	 */
553 	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
554 		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
555 			if (strcmp(cres->hr_name, nres->hr_name) == 0)
556 				break;
557 		}
558 		PJDLOG_ASSERT(cres != NULL);
559 		if (resource_needs_restart(cres, nres)) {
560 			pjdlog_info("Resource %s configuration was modified, restarting it.",
561 			    cres->hr_name);
562 			role = cres->hr_role;
563 			control_set_role(cres, HAST_ROLE_INIT);
564 			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
565 			free(cres);
566 			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
567 			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
568 			control_set_role(nres, role);
569 		} else if (resource_needs_reload(cres, nres)) {
570 			pjdlog_info("Resource %s configuration was modified, reloading it.",
571 			    cres->hr_name);
572 			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
573 			    sizeof(cres->hr_remoteaddr));
574 			cres->hr_replication = nres->hr_replication;
575 			cres->hr_checksum = nres->hr_checksum;
576 			cres->hr_compression = nres->hr_compression;
577 			cres->hr_timeout = nres->hr_timeout;
578 			strlcpy(cres->hr_exec, nres->hr_exec,
579 			    sizeof(cres->hr_exec));
580 			if (cres->hr_workerpid != 0)
581 				resource_reload(cres);
582 		}
583 	}
584 
585 	yy_config_free(newcfg);
586 	pjdlog_info("Configuration reloaded successfully.");
587 	return;
588 failed:
589 	if (newcfg != NULL) {
590 		if (newcfg->hc_controlconn != NULL)
591 			proto_close(newcfg->hc_controlconn);
592 		if (newcfg->hc_listenconn != NULL)
593 			proto_close(newcfg->hc_listenconn);
594 		yy_config_free(newcfg);
595 	}
596 	pjdlog_warning("Configuration not reloaded.");
597 }
598 
599 static void
600 terminate_workers(void)
601 {
602 	struct hast_resource *res;
603 
604 	pjdlog_info("Termination signal received, exiting.");
605 	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
606 		if (res->hr_workerpid == 0)
607 			continue;
608 		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
609 		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
610 		if (kill(res->hr_workerpid, SIGTERM) == 0)
611 			continue;
612 		pjdlog_errno(LOG_WARNING,
613 		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
614 		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
615 	}
616 }
617 
618 static void
619 listen_accept(void)
620 {
621 	struct hast_resource *res;
622 	struct proto_conn *conn;
623 	struct nv *nvin, *nvout, *nverr;
624 	const char *resname;
625 	const unsigned char *token;
626 	char laddr[256], raddr[256];
627 	size_t size;
628 	pid_t pid;
629 	int status;
630 
631 	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
632 	pjdlog_debug(1, "Accepting connection to %s.", laddr);
633 
634 	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
635 		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
636 		return;
637 	}
638 
639 	proto_local_address(conn, laddr, sizeof(laddr));
640 	proto_remote_address(conn, raddr, sizeof(raddr));
641 	pjdlog_info("Connection from %s to %s.", raddr, laddr);
642 
643 	/* Error in setting timeout is not critical, but why should it fail? */
644 	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
645 		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
646 
647 	nvin = nvout = nverr = NULL;
648 
649 	/*
650 	 * Before receiving any data see if remote host have access to any
651 	 * resource.
652 	 */
653 	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
654 		if (proto_address_match(conn, res->hr_remoteaddr))
655 			break;
656 	}
657 	if (res == NULL) {
658 		pjdlog_error("Client %s isn't known.", raddr);
659 		goto close;
660 	}
661 	/* Ok, remote host can access at least one resource. */
662 
663 	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
664 		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
665 		    raddr);
666 		goto close;
667 	}
668 
669 	resname = nv_get_string(nvin, "resource");
670 	if (resname == NULL) {
671 		pjdlog_error("No 'resource' field in the header received from %s.",
672 		    raddr);
673 		goto close;
674 	}
675 	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
676 	token = nv_get_uint8_array(nvin, &size, "token");
677 	/*
678 	 * NULL token means that this is first conection.
679 	 */
680 	if (token != NULL && size != sizeof(res->hr_token)) {
681 		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
682 		    raddr, sizeof(res->hr_token), size);
683 		goto close;
684 	}
685 
686 	/*
687 	 * From now on we want to send errors to the remote node.
688 	 */
689 	nverr = nv_alloc();
690 
691 	/* Find resource related to this connection. */
692 	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
693 		if (strcmp(resname, res->hr_name) == 0)
694 			break;
695 	}
696 	/* Have we found the resource? */
697 	if (res == NULL) {
698 		pjdlog_error("No resource '%s' as requested by %s.",
699 		    resname, raddr);
700 		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
701 		goto fail;
702 	}
703 
704 	/* Now that we know resource name setup log prefix. */
705 	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
706 
707 	/* Does the remote host have access to this resource? */
708 	if (!proto_address_match(conn, res->hr_remoteaddr)) {
709 		pjdlog_error("Client %s has no access to the resource.", raddr);
710 		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
711 		goto fail;
712 	}
713 	/* Is the resource marked as secondary? */
714 	if (res->hr_role != HAST_ROLE_SECONDARY) {
715 		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
716 		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
717 		    raddr);
718 		nv_add_stringf(nverr, "errmsg",
719 		    "Remote node acts as %s for the resource and not as %s.",
720 		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
721 		goto fail;
722 	}
723 	/* Does token (if exists) match? */
724 	if (token != NULL && memcmp(token, res->hr_token,
725 	    sizeof(res->hr_token)) != 0) {
726 		pjdlog_error("Token received from %s doesn't match.", raddr);
727 		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
728 		goto fail;
729 	}
730 	/*
731 	 * If there is no token, but we have half-open connection
732 	 * (only remotein) or full connection (worker process is running)
733 	 * we have to cancel those and accept the new connection.
734 	 */
735 	if (token == NULL) {
736 		PJDLOG_ASSERT(res->hr_remoteout == NULL);
737 		pjdlog_debug(1, "Initial connection from %s.", raddr);
738 		if (res->hr_workerpid != 0) {
739 			PJDLOG_ASSERT(res->hr_remotein == NULL);
740 			pjdlog_debug(1,
741 			    "Worker process exists (pid=%u), stopping it.",
742 			    (unsigned int)res->hr_workerpid);
743 			/* Stop child process. */
744 			if (kill(res->hr_workerpid, SIGINT) < 0) {
745 				pjdlog_errno(LOG_ERR,
746 				    "Unable to stop worker process (pid=%u)",
747 				    (unsigned int)res->hr_workerpid);
748 				/*
749 				 * Other than logging the problem we
750 				 * ignore it - nothing smart to do.
751 				 */
752 			}
753 			/* Wait for it to exit. */
754 			else if ((pid = waitpid(res->hr_workerpid,
755 			    &status, 0)) != res->hr_workerpid) {
756 				/* We can only log the problem. */
757 				pjdlog_errno(LOG_ERR,
758 				    "Waiting for worker process (pid=%u) failed",
759 				    (unsigned int)res->hr_workerpid);
760 			} else {
761 				child_exit_log(res->hr_workerpid, status);
762 			}
763 			child_cleanup(res);
764 		} else if (res->hr_remotein != NULL) {
765 			char oaddr[256];
766 
767 			proto_remote_address(res->hr_remotein, oaddr,
768 			    sizeof(oaddr));
769 			pjdlog_debug(1,
770 			    "Canceling half-open connection from %s on connection from %s.",
771 			    oaddr, raddr);
772 			proto_close(res->hr_remotein);
773 			res->hr_remotein = NULL;
774 		}
775 	}
776 
777 	/*
778 	 * Checks and cleanups are done.
779 	 */
780 
781 	if (token == NULL) {
782 		arc4random_buf(res->hr_token, sizeof(res->hr_token));
783 		nvout = nv_alloc();
784 		nv_add_uint8_array(nvout, res->hr_token,
785 		    sizeof(res->hr_token), "token");
786 		if (nv_error(nvout) != 0) {
787 			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
788 			    "Unable to prepare return header for %s", raddr);
789 			nv_add_stringf(nverr, "errmsg",
790 			    "Remote node was unable to prepare return header: %s.",
791 			    strerror(nv_error(nvout)));
792 			goto fail;
793 		}
794 		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
795 			int error = errno;
796 
797 			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
798 			    raddr);
799 			nv_add_stringf(nverr, "errmsg",
800 			    "Remote node was unable to send response: %s.",
801 			    strerror(error));
802 			goto fail;
803 		}
804 		res->hr_remotein = conn;
805 		pjdlog_debug(1, "Incoming connection from %s configured.",
806 		    raddr);
807 	} else {
808 		res->hr_remoteout = conn;
809 		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
810 		hastd_secondary(res, nvin);
811 	}
812 	nv_free(nvin);
813 	nv_free(nvout);
814 	nv_free(nverr);
815 	pjdlog_prefix_set("%s", "");
816 	return;
817 fail:
818 	if (nv_error(nverr) != 0) {
819 		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
820 		    "Unable to prepare error header for %s", raddr);
821 		goto close;
822 	}
823 	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
824 		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
825 		goto close;
826 	}
827 close:
828 	if (nvin != NULL)
829 		nv_free(nvin);
830 	if (nvout != NULL)
831 		nv_free(nvout);
832 	if (nverr != NULL)
833 		nv_free(nverr);
834 	proto_close(conn);
835 	pjdlog_prefix_set("%s", "");
836 }
837 
838 static void
839 connection_migrate(struct hast_resource *res)
840 {
841 	struct proto_conn *conn;
842 	int16_t val = 0;
843 
844 	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
845 		pjdlog_errno(LOG_WARNING,
846 		    "Unable to receive connection command");
847 		return;
848 	}
849 	if (proto_client(res->hr_remoteaddr, &conn) < 0) {
850 		val = errno;
851 		pjdlog_errno(LOG_WARNING,
852 		    "Unable to create outgoing connection to %s",
853 		    res->hr_remoteaddr);
854 		goto out;
855 	}
856 	if (proto_connect(conn, -1) < 0) {
857 		val = errno;
858 		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
859 		    res->hr_remoteaddr);
860 		proto_close(conn);
861 		goto out;
862 	}
863 	val = 0;
864 out:
865 	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
866 		pjdlog_errno(LOG_WARNING,
867 		    "Unable to send reply to connection request");
868 	}
869 	if (val == 0 && proto_connection_send(res->hr_conn, conn) < 0)
870 		pjdlog_errno(LOG_WARNING, "Unable to send connection");
871 }
872 
873 static void
874 main_loop(void)
875 {
876 	struct hast_resource *res;
877 	struct timeval seltimeout;
878 	struct timespec sigtimeout;
879 	int fd, maxfd, ret, signo;
880 	sigset_t mask;
881 	fd_set rfds;
882 
883 	seltimeout.tv_sec = REPORT_INTERVAL;
884 	seltimeout.tv_usec = 0;
885 	sigtimeout.tv_sec = 0;
886 	sigtimeout.tv_nsec = 0;
887 
888 	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
889 	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
890 	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
891 	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
892 	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
893 
894 	pjdlog_info("Started successfully, running protocol version %d.",
895 	    HAST_PROTO_VERSION);
896 
897 	for (;;) {
898 		while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
899 			switch (signo) {
900 			case SIGINT:
901 			case SIGTERM:
902 				sigexit_received = true;
903 				terminate_workers();
904 				proto_close(cfg->hc_controlconn);
905 				exit(EX_OK);
906 				break;
907 			case SIGCHLD:
908 				child_exit();
909 				break;
910 			case SIGHUP:
911 				hastd_reload();
912 				break;
913 			default:
914 				PJDLOG_ABORT("Unexpected signal (%d).", signo);
915 			}
916 		}
917 
918 		/* Setup descriptors for select(2). */
919 		FD_ZERO(&rfds);
920 		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
921 		PJDLOG_ASSERT(fd >= 0);
922 		FD_SET(fd, &rfds);
923 		fd = proto_descriptor(cfg->hc_listenconn);
924 		PJDLOG_ASSERT(fd >= 0);
925 		FD_SET(fd, &rfds);
926 		maxfd = fd > maxfd ? fd : maxfd;
927 		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
928 			if (res->hr_event == NULL)
929 				continue;
930 			PJDLOG_ASSERT(res->hr_conn != NULL);
931 			fd = proto_descriptor(res->hr_event);
932 			PJDLOG_ASSERT(fd >= 0);
933 			FD_SET(fd, &rfds);
934 			maxfd = fd > maxfd ? fd : maxfd;
935 			if (res->hr_role == HAST_ROLE_PRIMARY) {
936 				/* Only primary workers asks for connections. */
937 				fd = proto_descriptor(res->hr_conn);
938 				PJDLOG_ASSERT(fd >= 0);
939 				FD_SET(fd, &rfds);
940 				maxfd = fd > maxfd ? fd : maxfd;
941 			}
942 		}
943 
944 		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
945 		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
946 		if (ret == 0)
947 			hook_check();
948 		else if (ret == -1) {
949 			if (errno == EINTR)
950 				continue;
951 			KEEP_ERRNO((void)pidfile_remove(pfh));
952 			pjdlog_exit(EX_OSERR, "select() failed");
953 		}
954 
955 		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
956 			control_handle(cfg);
957 		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
958 			listen_accept();
959 		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
960 			if (res->hr_event == NULL)
961 				continue;
962 			PJDLOG_ASSERT(res->hr_conn != NULL);
963 			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
964 				if (event_recv(res) == 0)
965 					continue;
966 				/* The worker process exited? */
967 				proto_close(res->hr_event);
968 				res->hr_event = NULL;
969 				proto_close(res->hr_conn);
970 				res->hr_conn = NULL;
971 				continue;
972 			}
973 			if (res->hr_role == HAST_ROLE_PRIMARY &&
974 			    FD_ISSET(proto_descriptor(res->hr_conn), &rfds)) {
975 				connection_migrate(res);
976 			}
977 		}
978 	}
979 }
980 
981 static void
982 dummy_sighandler(int sig __unused)
983 {
984 	/* Nothing to do. */
985 }
986 
987 int
988 main(int argc, char *argv[])
989 {
990 	const char *pidfile;
991 	pid_t otherpid;
992 	bool foreground;
993 	int debuglevel;
994 	sigset_t mask;
995 
996 	foreground = false;
997 	debuglevel = 0;
998 	pidfile = HASTD_PIDFILE;
999 
1000 	for (;;) {
1001 		int ch;
1002 
1003 		ch = getopt(argc, argv, "c:dFhP:");
1004 		if (ch == -1)
1005 			break;
1006 		switch (ch) {
1007 		case 'c':
1008 			cfgpath = optarg;
1009 			break;
1010 		case 'd':
1011 			debuglevel++;
1012 			break;
1013 		case 'F':
1014 			foreground = true;
1015 			break;
1016 		case 'P':
1017 			pidfile = optarg;
1018 			break;
1019 		case 'h':
1020 		default:
1021 			usage();
1022 		}
1023 	}
1024 	argc -= optind;
1025 	argv += optind;
1026 
1027 	pjdlog_init(PJDLOG_MODE_STD);
1028 	pjdlog_debug_set(debuglevel);
1029 
1030 	g_gate_load();
1031 
1032 	pfh = pidfile_open(pidfile, 0600, &otherpid);
1033 	if (pfh == NULL) {
1034 		if (errno == EEXIST) {
1035 			pjdlog_exitx(EX_TEMPFAIL,
1036 			    "Another hastd is already running, pid: %jd.",
1037 			    (intmax_t)otherpid);
1038 		}
1039 		/* If we cannot create pidfile from other reasons, only warn. */
1040 		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
1041 	}
1042 
1043 	cfg = yy_config_parse(cfgpath, true);
1044 	PJDLOG_ASSERT(cfg != NULL);
1045 
1046 	/*
1047 	 * Restore default actions for interesting signals in case parent
1048 	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1049 	 */
1050 	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1051 	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1052 	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1053 	/*
1054 	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1055 	 * so we can mask it.
1056 	 */
1057 	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1058 
1059 	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1060 	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1061 	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1062 	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1063 	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1064 	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1065 
1066 	/* Listen on control address. */
1067 	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
1068 		KEEP_ERRNO((void)pidfile_remove(pfh));
1069 		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1070 		    cfg->hc_controladdr);
1071 	}
1072 	/* Listen for remote connections. */
1073 	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
1074 		KEEP_ERRNO((void)pidfile_remove(pfh));
1075 		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1076 		    cfg->hc_listenaddr);
1077 	}
1078 
1079 	if (!foreground) {
1080 		if (daemon(0, 0) < 0) {
1081 			KEEP_ERRNO((void)pidfile_remove(pfh));
1082 			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1083 		}
1084 
1085 		/* Start logging to syslog. */
1086 		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1087 
1088 		/* Write PID to a file. */
1089 		if (pidfile_write(pfh) < 0) {
1090 			pjdlog_errno(LOG_WARNING,
1091 			    "Unable to write PID to a file");
1092 		}
1093 	}
1094 
1095 	hook_init();
1096 
1097 	main_loop();
1098 
1099 	exit(0);
1100 }
1101