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