xref: /freebsd/sbin/hastd/hastd.c (revision 06c3fb27)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009-2010 The FreeBSD Foundation
5  * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
6  * All rights reserved.
7  *
8  * This software was developed by Pawel Jakub Dawidek under sponsorship from
9  * the FreeBSD Foundation.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/param.h>
34 #include <sys/linker.h>
35 #include <sys/module.h>
36 #include <sys/stat.h>
37 #include <sys/wait.h>
38 
39 #include <err.h>
40 #include <errno.h>
41 #include <libutil.h>
42 #include <signal.h>
43 #include <stdbool.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <sysexits.h>
48 #include <time.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 /* Path to pidfile. */
69 static const char *pidfile;
70 /* Pidfile handle. */
71 struct pidfh *pfh;
72 /* Do we run in foreground? */
73 static bool foreground;
74 
75 /* How often check for hooks running for too long. */
76 #define	REPORT_INTERVAL	5
77 
78 static void
79 usage(void)
80 {
81 
82 	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
83 }
84 
85 static void
86 g_gate_load(void)
87 {
88 
89 	if (modfind("g_gate") == -1) {
90 		/* Not present in kernel, try loading it. */
91 		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
92 			if (errno != EEXIST) {
93 				pjdlog_exit(EX_OSERR,
94 				    "Unable to load geom_gate module");
95 			}
96 		}
97 	}
98 }
99 
100 void
101 descriptors_cleanup(struct hast_resource *res)
102 {
103 	struct hast_resource *tres, *tmres;
104 	struct hastd_listen *lst;
105 
106 	TAILQ_FOREACH_SAFE(tres, &cfg->hc_resources, hr_next, tmres) {
107 		if (tres == res) {
108 			PJDLOG_VERIFY(res->hr_role == HAST_ROLE_SECONDARY ||
109 			    (res->hr_remotein == NULL &&
110 			     res->hr_remoteout == NULL));
111 			continue;
112 		}
113 		if (tres->hr_remotein != NULL)
114 			proto_close(tres->hr_remotein);
115 		if (tres->hr_remoteout != NULL)
116 			proto_close(tres->hr_remoteout);
117 		if (tres->hr_ctrl != NULL)
118 			proto_close(tres->hr_ctrl);
119 		if (tres->hr_event != NULL)
120 			proto_close(tres->hr_event);
121 		if (tres->hr_conn != NULL)
122 			proto_close(tres->hr_conn);
123 		TAILQ_REMOVE(&cfg->hc_resources, tres, hr_next);
124 		free(tres);
125 	}
126 	if (cfg->hc_controlin != NULL)
127 		proto_close(cfg->hc_controlin);
128 	proto_close(cfg->hc_controlconn);
129 	while ((lst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
130 		TAILQ_REMOVE(&cfg->hc_listen, lst, hl_next);
131 		if (lst->hl_conn != NULL)
132 			proto_close(lst->hl_conn);
133 		free(lst);
134 	}
135 	(void)pidfile_close(pfh);
136 	hook_fini();
137 	pjdlog_fini();
138 }
139 
140 static const char *
141 dtype2str(mode_t mode)
142 {
143 
144 	if (S_ISBLK(mode))
145 		return ("block device");
146 	else if (S_ISCHR(mode))
147 		return ("character device");
148 	else if (S_ISDIR(mode))
149 		return ("directory");
150 	else if (S_ISFIFO(mode))
151 		return ("pipe or FIFO");
152 	else if (S_ISLNK(mode))
153 		return ("symbolic link");
154 	else if (S_ISREG(mode))
155 		return ("regular file");
156 	else if (S_ISSOCK(mode))
157 		return ("socket");
158 	else if (S_ISWHT(mode))
159 		return ("whiteout");
160 	else
161 		return ("unknown");
162 }
163 
164 void
165 descriptors_assert(const struct hast_resource *res, int pjdlogmode)
166 {
167 	char msg[256];
168 	struct stat sb;
169 	long maxfd;
170 	bool isopen;
171 	mode_t mode;
172 	int fd;
173 
174 	/*
175 	 * At this point descriptor to syslog socket is closed, so if we want
176 	 * to log assertion message, we have to first store it in 'msg' local
177 	 * buffer and then open syslog socket and log it.
178 	 */
179 	msg[0] = '\0';
180 
181 	maxfd = sysconf(_SC_OPEN_MAX);
182 	if (maxfd == -1) {
183 		pjdlog_init(pjdlogmode);
184 		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
185 		    role2str(res->hr_role));
186 		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
187 		pjdlog_fini();
188 		maxfd = 16384;
189 	}
190 	for (fd = 0; fd <= maxfd; fd++) {
191 		if (fstat(fd, &sb) == 0) {
192 			isopen = true;
193 			mode = sb.st_mode;
194 		} else if (errno == EBADF) {
195 			isopen = false;
196 			mode = 0;
197 		} else {
198 			(void)snprintf(msg, sizeof(msg),
199 			    "Unable to fstat descriptor %d: %s", fd,
200 			    strerror(errno));
201 			break;
202 		}
203 		if (fd == STDIN_FILENO || fd == STDOUT_FILENO ||
204 		    fd == STDERR_FILENO) {
205 			if (!isopen) {
206 				(void)snprintf(msg, sizeof(msg),
207 				    "Descriptor %d (%s) is closed, but should be open.",
208 				    fd, (fd == STDIN_FILENO ? "stdin" :
209 				    (fd == STDOUT_FILENO ? "stdout" : "stderr")));
210 				break;
211 			}
212 		} else if (fd == proto_descriptor(res->hr_event)) {
213 			if (!isopen) {
214 				(void)snprintf(msg, sizeof(msg),
215 				    "Descriptor %d (event) is closed, but should be open.",
216 				    fd);
217 				break;
218 			}
219 			if (!S_ISSOCK(mode)) {
220 				(void)snprintf(msg, sizeof(msg),
221 				    "Descriptor %d (event) is %s, but should be %s.",
222 				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
223 				break;
224 			}
225 		} else if (fd == proto_descriptor(res->hr_ctrl)) {
226 			if (!isopen) {
227 				(void)snprintf(msg, sizeof(msg),
228 				    "Descriptor %d (ctrl) is closed, but should be open.",
229 				    fd);
230 				break;
231 			}
232 			if (!S_ISSOCK(mode)) {
233 				(void)snprintf(msg, sizeof(msg),
234 				    "Descriptor %d (ctrl) is %s, but should be %s.",
235 				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
236 				break;
237 			}
238 		} else if (res->hr_role == HAST_ROLE_PRIMARY &&
239 		    fd == proto_descriptor(res->hr_conn)) {
240 			if (!isopen) {
241 				(void)snprintf(msg, sizeof(msg),
242 				    "Descriptor %d (conn) is closed, but should be open.",
243 				    fd);
244 				break;
245 			}
246 			if (!S_ISSOCK(mode)) {
247 				(void)snprintf(msg, sizeof(msg),
248 				    "Descriptor %d (conn) is %s, but should be %s.",
249 				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
250 				break;
251 			}
252 		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
253 		    res->hr_conn != NULL &&
254 		    fd == proto_descriptor(res->hr_conn)) {
255 			if (isopen) {
256 				(void)snprintf(msg, sizeof(msg),
257 				    "Descriptor %d (conn) is open, but should be closed.",
258 				    fd);
259 				break;
260 			}
261 		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
262 		    fd == proto_descriptor(res->hr_remotein)) {
263 			if (!isopen) {
264 				(void)snprintf(msg, sizeof(msg),
265 				    "Descriptor %d (remote in) is closed, but should be open.",
266 				    fd);
267 				break;
268 			}
269 			if (!S_ISSOCK(mode)) {
270 				(void)snprintf(msg, sizeof(msg),
271 				    "Descriptor %d (remote in) is %s, but should be %s.",
272 				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
273 				break;
274 			}
275 		} else if (res->hr_role == HAST_ROLE_SECONDARY &&
276 		    fd == proto_descriptor(res->hr_remoteout)) {
277 			if (!isopen) {
278 				(void)snprintf(msg, sizeof(msg),
279 				    "Descriptor %d (remote out) is closed, but should be open.",
280 				    fd);
281 				break;
282 			}
283 			if (!S_ISSOCK(mode)) {
284 				(void)snprintf(msg, sizeof(msg),
285 				    "Descriptor %d (remote out) is %s, but should be %s.",
286 				    fd, dtype2str(mode), dtype2str(S_IFSOCK));
287 				break;
288 			}
289 		} else {
290 			if (isopen) {
291 				(void)snprintf(msg, sizeof(msg),
292 				    "Descriptor %d is open (%s), but should be closed.",
293 				    fd, dtype2str(mode));
294 				break;
295 			}
296 		}
297 	}
298 	if (msg[0] != '\0') {
299 		pjdlog_init(pjdlogmode);
300 		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
301 		    role2str(res->hr_role));
302 		PJDLOG_ABORT("%s", msg);
303 	}
304 }
305 
306 static void
307 child_exit_log(unsigned int pid, int status)
308 {
309 
310 	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
311 		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
312 		    pid);
313 	} else if (WIFSIGNALED(status)) {
314 		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
315 		    pid, WTERMSIG(status));
316 	} else {
317 		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
318 		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
319 	}
320 }
321 
322 static void
323 child_exit(void)
324 {
325 	struct hast_resource *res;
326 	int status;
327 	pid_t pid;
328 
329 	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
330 		/* Find resource related to the process that just exited. */
331 		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
332 			if (pid == res->hr_workerpid)
333 				break;
334 		}
335 		if (res == NULL) {
336 			/*
337 			 * This can happen when new connection arrives and we
338 			 * cancel child responsible for the old one or if this
339 			 * was hook which we executed.
340 			 */
341 			hook_check_one(pid, status);
342 			continue;
343 		}
344 		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
345 		    role2str(res->hr_role));
346 		child_exit_log(pid, status);
347 		child_cleanup(res);
348 		if (res->hr_role == HAST_ROLE_PRIMARY) {
349 			/*
350 			 * Restart child process if it was killed by signal
351 			 * or exited because of temporary problem.
352 			 */
353 			if (WIFSIGNALED(status) ||
354 			    (WIFEXITED(status) &&
355 			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
356 				sleep(1);
357 				pjdlog_info("Restarting worker process.");
358 				hastd_primary(res);
359 			} else {
360 				res->hr_role = HAST_ROLE_INIT;
361 				pjdlog_info("Changing resource role back to %s.",
362 				    role2str(res->hr_role));
363 			}
364 		}
365 		pjdlog_prefix_set("%s", "");
366 	}
367 }
368 
369 static bool
370 resource_needs_restart(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 
376 	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
377 		return (true);
378 	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
379 		return (true);
380 	if (res0->hr_role == HAST_ROLE_INIT ||
381 	    res0->hr_role == HAST_ROLE_SECONDARY) {
382 		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
383 			return (true);
384 		if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
385 			return (true);
386 		if (res0->hr_replication != res1->hr_replication)
387 			return (true);
388 		if (res0->hr_checksum != res1->hr_checksum)
389 			return (true);
390 		if (res0->hr_compression != res1->hr_compression)
391 			return (true);
392 		if (res0->hr_timeout != res1->hr_timeout)
393 			return (true);
394 		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
395 			return (true);
396 		/*
397 		 * When metaflush has changed we don't really need restart,
398 		 * but it is just easier this way.
399 		 */
400 		if (res0->hr_metaflush != res1->hr_metaflush)
401 			return (true);
402 	}
403 	return (false);
404 }
405 
406 static bool
407 resource_needs_reload(const struct hast_resource *res0,
408     const struct hast_resource *res1)
409 {
410 
411 	PJDLOG_ASSERT(strcmp(res0->hr_name, res1->hr_name) == 0);
412 	PJDLOG_ASSERT(strcmp(res0->hr_provname, res1->hr_provname) == 0);
413 	PJDLOG_ASSERT(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
414 
415 	if (res0->hr_role != HAST_ROLE_PRIMARY)
416 		return (false);
417 
418 	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
419 		return (true);
420 	if (strcmp(res0->hr_sourceaddr, res1->hr_sourceaddr) != 0)
421 		return (true);
422 	if (res0->hr_replication != res1->hr_replication)
423 		return (true);
424 	if (res0->hr_checksum != res1->hr_checksum)
425 		return (true);
426 	if (res0->hr_compression != res1->hr_compression)
427 		return (true);
428 	if (res0->hr_timeout != res1->hr_timeout)
429 		return (true);
430 	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
431 		return (true);
432 	if (res0->hr_metaflush != res1->hr_metaflush)
433 		return (true);
434 	return (false);
435 }
436 
437 static void
438 resource_reload(const struct hast_resource *res)
439 {
440 	struct nv *nvin, *nvout;
441 	int error;
442 
443 	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
444 
445 	nvout = nv_alloc();
446 	nv_add_uint8(nvout, CONTROL_RELOAD, "cmd");
447 	nv_add_string(nvout, res->hr_remoteaddr, "remoteaddr");
448 	nv_add_string(nvout, res->hr_sourceaddr, "sourceaddr");
449 	nv_add_int32(nvout, (int32_t)res->hr_replication, "replication");
450 	nv_add_int32(nvout, (int32_t)res->hr_checksum, "checksum");
451 	nv_add_int32(nvout, (int32_t)res->hr_compression, "compression");
452 	nv_add_int32(nvout, (int32_t)res->hr_timeout, "timeout");
453 	nv_add_string(nvout, res->hr_exec, "exec");
454 	nv_add_int32(nvout, (int32_t)res->hr_metaflush, "metaflush");
455 	if (nv_error(nvout) != 0) {
456 		nv_free(nvout);
457 		pjdlog_error("Unable to allocate header for reload message.");
458 		return;
459 	}
460 	if (hast_proto_send(res, res->hr_ctrl, nvout, NULL, 0) == -1) {
461 		pjdlog_errno(LOG_ERR, "Unable to send reload message");
462 		nv_free(nvout);
463 		return;
464 	}
465 	nv_free(nvout);
466 
467 	/* Receive response. */
468 	if (hast_proto_recv_hdr(res->hr_ctrl, &nvin) == -1) {
469 		pjdlog_errno(LOG_ERR, "Unable to receive reload reply");
470 		return;
471 	}
472 	error = nv_get_int16(nvin, "error");
473 	nv_free(nvin);
474 	if (error != 0) {
475 		pjdlog_common(LOG_ERR, 0, error, "Reload failed");
476 		return;
477 	}
478 }
479 
480 static void
481 hastd_reload(void)
482 {
483 	struct hastd_config *newcfg;
484 	struct hast_resource *nres, *cres, *tres;
485 	struct hastd_listen *nlst, *clst;
486 	struct pidfh *newpfh;
487 	unsigned int nlisten;
488 	uint8_t role;
489 	pid_t otherpid;
490 
491 	pjdlog_info("Reloading configuration...");
492 
493 	newpfh = NULL;
494 
495 	newcfg = yy_config_parse(cfgpath, false);
496 	if (newcfg == NULL)
497 		goto failed;
498 
499 	/*
500 	 * Check if control address has changed.
501 	 */
502 	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
503 		if (proto_server(newcfg->hc_controladdr,
504 		    &newcfg->hc_controlconn) == -1) {
505 			pjdlog_errno(LOG_ERR,
506 			    "Unable to listen on control address %s",
507 			    newcfg->hc_controladdr);
508 			goto failed;
509 		}
510 	}
511 	/*
512 	 * Check if any listen address has changed.
513 	 */
514 	nlisten = 0;
515 	TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
516 		TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
517 			if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
518 				break;
519 		}
520 		if (clst != NULL && clst->hl_conn != NULL) {
521 			pjdlog_info("Keep listening on address %s.",
522 			    nlst->hl_addr);
523 			nlst->hl_conn = clst->hl_conn;
524 			nlisten++;
525 		} else if (proto_server(nlst->hl_addr, &nlst->hl_conn) == 0) {
526 			pjdlog_info("Listening on new address %s.",
527 			    nlst->hl_addr);
528 			nlisten++;
529 		} else {
530 			pjdlog_errno(LOG_WARNING,
531 			    "Unable to listen on address %s", nlst->hl_addr);
532 		}
533 	}
534 	if (nlisten == 0) {
535 		pjdlog_error("No addresses to listen on.");
536 		goto failed;
537 	}
538 	/*
539 	 * Check if pidfile's path has changed.
540 	 */
541 	if (!foreground && pidfile == NULL &&
542 	    strcmp(cfg->hc_pidfile, newcfg->hc_pidfile) != 0) {
543 		newpfh = pidfile_open(newcfg->hc_pidfile, 0600, &otherpid);
544 		if (newpfh == NULL) {
545 			if (errno == EEXIST) {
546 				pjdlog_errno(LOG_WARNING,
547 				    "Another hastd is already running, pidfile: %s, pid: %jd.",
548 				    newcfg->hc_pidfile, (intmax_t)otherpid);
549 			} else {
550 				pjdlog_errno(LOG_WARNING,
551 				    "Unable to open or create pidfile %s",
552 				    newcfg->hc_pidfile);
553 			}
554 		} else if (pidfile_write(newpfh) == -1) {
555 			/* Write PID to a file. */
556 			pjdlog_errno(LOG_WARNING,
557 			    "Unable to write PID to file %s",
558 			    newcfg->hc_pidfile);
559 		} else {
560 			pjdlog_debug(1, "PID stored in %s.",
561 			    newcfg->hc_pidfile);
562 		}
563 	}
564 
565 	/* No failures from now on. */
566 
567 	/*
568 	 * Switch to new control socket.
569 	 */
570 	if (newcfg->hc_controlconn != NULL) {
571 		pjdlog_info("Control socket changed from %s to %s.",
572 		    cfg->hc_controladdr, newcfg->hc_controladdr);
573 		proto_close(cfg->hc_controlconn);
574 		cfg->hc_controlconn = newcfg->hc_controlconn;
575 		newcfg->hc_controlconn = NULL;
576 		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
577 		    sizeof(cfg->hc_controladdr));
578 	}
579 	/*
580 	 * Switch to new pidfile.
581 	 */
582 	if (newpfh != NULL) {
583 		pjdlog_info("Pidfile changed from %s to %s.", cfg->hc_pidfile,
584 		    newcfg->hc_pidfile);
585 		(void)pidfile_remove(pfh);
586 		pfh = newpfh;
587 		(void)strlcpy(cfg->hc_pidfile, newcfg->hc_pidfile,
588 		    sizeof(cfg->hc_pidfile));
589 	}
590 	/*
591 	 * Switch to new listen addresses. Close all that were removed.
592 	 */
593 	while ((clst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
594 		TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
595 			if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
596 				break;
597 		}
598 		if (nlst == NULL && clst->hl_conn != NULL) {
599 			proto_close(clst->hl_conn);
600 			pjdlog_info("No longer listening on address %s.",
601 			    clst->hl_addr);
602 		}
603 		TAILQ_REMOVE(&cfg->hc_listen, clst, hl_next);
604 		free(clst);
605 	}
606 	TAILQ_CONCAT(&cfg->hc_listen, &newcfg->hc_listen, hl_next);
607 
608 	/*
609 	 * Stop and remove resources that were removed from the configuration.
610 	 */
611 	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
612 		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
613 			if (strcmp(cres->hr_name, nres->hr_name) == 0)
614 				break;
615 		}
616 		if (nres == NULL) {
617 			control_set_role(cres, HAST_ROLE_INIT);
618 			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
619 			pjdlog_info("Resource %s removed.", cres->hr_name);
620 			free(cres);
621 		}
622 	}
623 	/*
624 	 * Move new resources to the current configuration.
625 	 */
626 	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
627 		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
628 			if (strcmp(cres->hr_name, nres->hr_name) == 0)
629 				break;
630 		}
631 		if (cres == NULL) {
632 			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
633 			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
634 			pjdlog_info("Resource %s added.", nres->hr_name);
635 		}
636 	}
637 	/*
638 	 * Deal with modified resources.
639 	 * Depending on what has changed exactly we might want to perform
640 	 * different actions.
641 	 *
642 	 * We do full resource restart in the following situations:
643 	 * Resource role is INIT or SECONDARY.
644 	 * Resource role is PRIMARY and path to local component or provider
645 	 * name has changed.
646 	 * In case of PRIMARY, the worker process will be killed and restarted,
647 	 * which also means removing /dev/hast/<name> provider and
648 	 * recreating it.
649 	 *
650 	 * We do just reload (send SIGHUP to worker process) if we act as
651 	 * PRIMARY, but only if remote address, source address, replication
652 	 * mode, timeout, execution path or metaflush has changed.
653 	 * For those, there is no need to restart worker process.
654 	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
655 	 * source address has changed or it will set new timeout if only timeout
656 	 * has changed or it will update metaflush if only metaflush has
657 	 * changed.
658 	 */
659 	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
660 		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
661 			if (strcmp(cres->hr_name, nres->hr_name) == 0)
662 				break;
663 		}
664 		PJDLOG_ASSERT(cres != NULL);
665 		if (resource_needs_restart(cres, nres)) {
666 			pjdlog_info("Resource %s configuration was modified, restarting it.",
667 			    cres->hr_name);
668 			role = cres->hr_role;
669 			control_set_role(cres, HAST_ROLE_INIT);
670 			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
671 			free(cres);
672 			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
673 			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
674 			control_set_role(nres, role);
675 		} else if (resource_needs_reload(cres, nres)) {
676 			pjdlog_info("Resource %s configuration was modified, reloading it.",
677 			    cres->hr_name);
678 			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
679 			    sizeof(cres->hr_remoteaddr));
680 			strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
681 			    sizeof(cres->hr_sourceaddr));
682 			cres->hr_replication = nres->hr_replication;
683 			cres->hr_checksum = nres->hr_checksum;
684 			cres->hr_compression = nres->hr_compression;
685 			cres->hr_timeout = nres->hr_timeout;
686 			strlcpy(cres->hr_exec, nres->hr_exec,
687 			    sizeof(cres->hr_exec));
688 			cres->hr_metaflush = nres->hr_metaflush;
689 			if (cres->hr_workerpid != 0)
690 				resource_reload(cres);
691 		}
692 	}
693 
694 	yy_config_free(newcfg);
695 	pjdlog_info("Configuration reloaded successfully.");
696 	return;
697 failed:
698 	if (newcfg != NULL) {
699 		if (newcfg->hc_controlconn != NULL)
700 			proto_close(newcfg->hc_controlconn);
701 		while ((nlst = TAILQ_FIRST(&newcfg->hc_listen)) != NULL) {
702 			if (nlst->hl_conn != NULL) {
703 				TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
704 					if (strcmp(nlst->hl_addr,
705 					    clst->hl_addr) == 0) {
706 						break;
707 					}
708 				}
709 				if (clst == NULL || clst->hl_conn == NULL)
710 					proto_close(nlst->hl_conn);
711 			}
712 			TAILQ_REMOVE(&newcfg->hc_listen, nlst, hl_next);
713 			free(nlst);
714 		}
715 		yy_config_free(newcfg);
716 	}
717 	if (newpfh != NULL)
718 		(void)pidfile_remove(newpfh);
719 	pjdlog_warning("Configuration not reloaded.");
720 }
721 
722 static void
723 terminate_workers(void)
724 {
725 	struct hast_resource *res;
726 
727 	pjdlog_info("Termination signal received, exiting.");
728 	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
729 		if (res->hr_workerpid == 0)
730 			continue;
731 		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
732 		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
733 		if (kill(res->hr_workerpid, SIGTERM) == 0)
734 			continue;
735 		pjdlog_errno(LOG_WARNING,
736 		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
737 		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
738 	}
739 }
740 
741 static void
742 listen_accept(struct hastd_listen *lst)
743 {
744 	struct hast_resource *res;
745 	struct proto_conn *conn;
746 	struct nv *nvin, *nvout, *nverr;
747 	const char *resname;
748 	const unsigned char *token;
749 	char laddr[256], raddr[256];
750 	uint8_t version;
751 	size_t size;
752 	pid_t pid;
753 	int status;
754 
755 	proto_local_address(lst->hl_conn, laddr, sizeof(laddr));
756 	pjdlog_debug(1, "Accepting connection to %s.", laddr);
757 
758 	if (proto_accept(lst->hl_conn, &conn) == -1) {
759 		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
760 		return;
761 	}
762 
763 	proto_local_address(conn, laddr, sizeof(laddr));
764 	proto_remote_address(conn, raddr, sizeof(raddr));
765 	pjdlog_info("Connection from %s to %s.", raddr, laddr);
766 
767 	/* Error in setting timeout is not critical, but why should it fail? */
768 	if (proto_timeout(conn, HAST_TIMEOUT) == -1)
769 		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
770 
771 	nvin = nvout = nverr = NULL;
772 
773 	/*
774 	 * Before receiving any data see if remote host have access to any
775 	 * resource.
776 	 */
777 	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
778 		if (proto_address_match(conn, res->hr_remoteaddr))
779 			break;
780 	}
781 	if (res == NULL) {
782 		pjdlog_error("Client %s isn't known.", raddr);
783 		goto close;
784 	}
785 	/* Ok, remote host can access at least one resource. */
786 
787 	if (hast_proto_recv_hdr(conn, &nvin) == -1) {
788 		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
789 		    raddr);
790 		goto close;
791 	}
792 
793 	resname = nv_get_string(nvin, "resource");
794 	if (resname == NULL) {
795 		pjdlog_error("No 'resource' field in the header received from %s.",
796 		    raddr);
797 		goto close;
798 	}
799 	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
800 	version = nv_get_uint8(nvin, "version");
801 	pjdlog_debug(2, "%s: version=%hhu", raddr, version);
802 	if (version == 0) {
803 		/*
804 		 * If no version is sent, it means this is protocol version 1.
805 		 */
806 		version = 1;
807 	}
808 	token = nv_get_uint8_array(nvin, &size, "token");
809 	/*
810 	 * NULL token means that this is first connection.
811 	 */
812 	if (token != NULL && size != sizeof(res->hr_token)) {
813 		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
814 		    raddr, sizeof(res->hr_token), size);
815 		goto close;
816 	}
817 
818 	/*
819 	 * From now on we want to send errors to the remote node.
820 	 */
821 	nverr = nv_alloc();
822 
823 	/* Find resource related to this connection. */
824 	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
825 		if (strcmp(resname, res->hr_name) == 0)
826 			break;
827 	}
828 	/* Have we found the resource? */
829 	if (res == NULL) {
830 		pjdlog_error("No resource '%s' as requested by %s.",
831 		    resname, raddr);
832 		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
833 		goto fail;
834 	}
835 
836 	/* Now that we know resource name setup log prefix. */
837 	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
838 
839 	/* Does the remote host have access to this resource? */
840 	if (!proto_address_match(conn, res->hr_remoteaddr)) {
841 		pjdlog_error("Client %s has no access to the resource.", raddr);
842 		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
843 		goto fail;
844 	}
845 	/* Is the resource marked as secondary? */
846 	if (res->hr_role != HAST_ROLE_SECONDARY) {
847 		pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
848 		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
849 		    raddr);
850 		nv_add_stringf(nverr, "errmsg",
851 		    "Remote node acts as %s for the resource and not as %s.",
852 		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
853 		if (res->hr_role == HAST_ROLE_PRIMARY) {
854 			/*
855 			 * If we act as primary request the other side to wait
856 			 * for us a bit, as we might be finishing cleanups.
857 			 */
858 			nv_add_uint8(nverr, 1, "wait");
859 		}
860 		goto fail;
861 	}
862 	/* Does token (if exists) match? */
863 	if (token != NULL && memcmp(token, res->hr_token,
864 	    sizeof(res->hr_token)) != 0) {
865 		pjdlog_error("Token received from %s doesn't match.", raddr);
866 		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
867 		goto fail;
868 	}
869 	/*
870 	 * If there is no token, but we have half-open connection
871 	 * (only remotein) or full connection (worker process is running)
872 	 * we have to cancel those and accept the new connection.
873 	 */
874 	if (token == NULL) {
875 		PJDLOG_ASSERT(res->hr_remoteout == NULL);
876 		pjdlog_debug(1, "Initial connection from %s.", raddr);
877 		if (res->hr_workerpid != 0) {
878 			PJDLOG_ASSERT(res->hr_remotein == NULL);
879 			pjdlog_debug(1,
880 			    "Worker process exists (pid=%u), stopping it.",
881 			    (unsigned int)res->hr_workerpid);
882 			/* Stop child process. */
883 			if (kill(res->hr_workerpid, SIGINT) == -1) {
884 				pjdlog_errno(LOG_ERR,
885 				    "Unable to stop worker process (pid=%u)",
886 				    (unsigned int)res->hr_workerpid);
887 				/*
888 				 * Other than logging the problem we
889 				 * ignore it - nothing smart to do.
890 				 */
891 			}
892 			/* Wait for it to exit. */
893 			else if ((pid = waitpid(res->hr_workerpid,
894 			    &status, 0)) != res->hr_workerpid) {
895 				/* We can only log the problem. */
896 				pjdlog_errno(LOG_ERR,
897 				    "Waiting for worker process (pid=%u) failed",
898 				    (unsigned int)res->hr_workerpid);
899 			} else {
900 				child_exit_log(res->hr_workerpid, status);
901 			}
902 			child_cleanup(res);
903 		} else if (res->hr_remotein != NULL) {
904 			char oaddr[256];
905 
906 			proto_remote_address(res->hr_remotein, oaddr,
907 			    sizeof(oaddr));
908 			pjdlog_debug(1,
909 			    "Canceling half-open connection from %s on connection from %s.",
910 			    oaddr, raddr);
911 			proto_close(res->hr_remotein);
912 			res->hr_remotein = NULL;
913 		}
914 	}
915 
916 	/*
917 	 * Checks and cleanups are done.
918 	 */
919 
920 	if (token == NULL) {
921 		if (version > HAST_PROTO_VERSION) {
922 			pjdlog_info("Remote protocol version %hhu is not supported, falling back to version %hhu.",
923 			    version, (unsigned char)HAST_PROTO_VERSION);
924 			version = HAST_PROTO_VERSION;
925 		}
926 		pjdlog_debug(1, "Negotiated protocol version %hhu.", version);
927 		res->hr_version = version;
928 		arc4random_buf(res->hr_token, sizeof(res->hr_token));
929 		nvout = nv_alloc();
930 		nv_add_uint8(nvout, version, "version");
931 		nv_add_uint8_array(nvout, res->hr_token,
932 		    sizeof(res->hr_token), "token");
933 		if (nv_error(nvout) != 0) {
934 			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
935 			    "Unable to prepare return header for %s", raddr);
936 			nv_add_stringf(nverr, "errmsg",
937 			    "Remote node was unable to prepare return header: %s.",
938 			    strerror(nv_error(nvout)));
939 			goto fail;
940 		}
941 		if (hast_proto_send(res, conn, nvout, NULL, 0) == -1) {
942 			int error = errno;
943 
944 			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
945 			    raddr);
946 			nv_add_stringf(nverr, "errmsg",
947 			    "Remote node was unable to send response: %s.",
948 			    strerror(error));
949 			goto fail;
950 		}
951 		res->hr_remotein = conn;
952 		pjdlog_debug(1, "Incoming connection from %s configured.",
953 		    raddr);
954 	} else {
955 		res->hr_remoteout = conn;
956 		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
957 		hastd_secondary(res, nvin);
958 	}
959 	nv_free(nvin);
960 	nv_free(nvout);
961 	nv_free(nverr);
962 	pjdlog_prefix_set("%s", "");
963 	return;
964 fail:
965 	if (nv_error(nverr) != 0) {
966 		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
967 		    "Unable to prepare error header for %s", raddr);
968 		goto close;
969 	}
970 	if (hast_proto_send(NULL, conn, nverr, NULL, 0) == -1) {
971 		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
972 		goto close;
973 	}
974 close:
975 	if (nvin != NULL)
976 		nv_free(nvin);
977 	if (nvout != NULL)
978 		nv_free(nvout);
979 	if (nverr != NULL)
980 		nv_free(nverr);
981 	proto_close(conn);
982 	pjdlog_prefix_set("%s", "");
983 }
984 
985 static void
986 connection_migrate(struct hast_resource *res)
987 {
988 	struct proto_conn *conn;
989 	int16_t val = 0;
990 
991 	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
992 
993 	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
994 
995 	if (proto_recv(res->hr_conn, &val, sizeof(val)) == -1) {
996 		pjdlog_errno(LOG_WARNING,
997 		    "Unable to receive connection command");
998 		return;
999 	}
1000 	if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
1001 	    res->hr_remoteaddr, &conn) == -1) {
1002 		val = errno;
1003 		pjdlog_errno(LOG_WARNING,
1004 		    "Unable to create outgoing connection to %s",
1005 		    res->hr_remoteaddr);
1006 		goto out;
1007 	}
1008 	if (proto_connect(conn, -1) == -1) {
1009 		val = errno;
1010 		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
1011 		    res->hr_remoteaddr);
1012 		proto_close(conn);
1013 		goto out;
1014 	}
1015 	val = 0;
1016 out:
1017 	if (proto_send(res->hr_conn, &val, sizeof(val)) == -1) {
1018 		pjdlog_errno(LOG_WARNING,
1019 		    "Unable to send reply to connection request");
1020 	}
1021 	if (val == 0 && proto_connection_send(res->hr_conn, conn) == -1)
1022 		pjdlog_errno(LOG_WARNING, "Unable to send connection");
1023 
1024 	pjdlog_prefix_set("%s", "");
1025 }
1026 
1027 static void
1028 check_signals(void)
1029 {
1030 	struct timespec sigtimeout;
1031 	sigset_t mask;
1032 	int signo;
1033 
1034 	sigtimeout.tv_sec = 0;
1035 	sigtimeout.tv_nsec = 0;
1036 
1037 	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1038 	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1039 	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1040 	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1041 	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1042 
1043 	while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
1044 		switch (signo) {
1045 		case SIGINT:
1046 		case SIGTERM:
1047 			sigexit_received = true;
1048 			terminate_workers();
1049 			proto_close(cfg->hc_controlconn);
1050 			exit(EX_OK);
1051 			break;
1052 		case SIGCHLD:
1053 			child_exit();
1054 			break;
1055 		case SIGHUP:
1056 			hastd_reload();
1057 			break;
1058 		default:
1059 			PJDLOG_ABORT("Unexpected signal (%d).", signo);
1060 		}
1061 	}
1062 }
1063 
1064 static void
1065 main_loop(void)
1066 {
1067 	struct hast_resource *res;
1068 	struct hastd_listen *lst;
1069 	struct timeval seltimeout;
1070 	int fd, maxfd, ret;
1071 	time_t lastcheck, now;
1072 	fd_set rfds;
1073 
1074 	lastcheck = time(NULL);
1075 	seltimeout.tv_sec = REPORT_INTERVAL;
1076 	seltimeout.tv_usec = 0;
1077 
1078 	for (;;) {
1079 		check_signals();
1080 
1081 		/* Setup descriptors for select(2). */
1082 		FD_ZERO(&rfds);
1083 		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
1084 		PJDLOG_ASSERT(fd >= 0);
1085 		FD_SET(fd, &rfds);
1086 		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1087 			if (lst->hl_conn == NULL)
1088 				continue;
1089 			fd = proto_descriptor(lst->hl_conn);
1090 			PJDLOG_ASSERT(fd >= 0);
1091 			FD_SET(fd, &rfds);
1092 			maxfd = MAX(fd, maxfd);
1093 		}
1094 		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1095 			if (res->hr_event == NULL)
1096 				continue;
1097 			fd = proto_descriptor(res->hr_event);
1098 			PJDLOG_ASSERT(fd >= 0);
1099 			FD_SET(fd, &rfds);
1100 			maxfd = MAX(fd, maxfd);
1101 			if (res->hr_role == HAST_ROLE_PRIMARY) {
1102 				/* Only primary workers asks for connections. */
1103 				PJDLOG_ASSERT(res->hr_conn != NULL);
1104 				fd = proto_descriptor(res->hr_conn);
1105 				PJDLOG_ASSERT(fd >= 0);
1106 				FD_SET(fd, &rfds);
1107 				maxfd = MAX(fd, maxfd);
1108 			} else {
1109 				PJDLOG_ASSERT(res->hr_conn == NULL);
1110 			}
1111 		}
1112 
1113 		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
1114 		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
1115 		now = time(NULL);
1116 		if (lastcheck + REPORT_INTERVAL <= now) {
1117 			hook_check();
1118 			lastcheck = now;
1119 		}
1120 		if (ret == 0) {
1121 			/*
1122 			 * select(2) timed out, so there should be no
1123 			 * descriptors to check.
1124 			 */
1125 			continue;
1126 		} else if (ret == -1) {
1127 			if (errno == EINTR)
1128 				continue;
1129 			KEEP_ERRNO((void)pidfile_remove(pfh));
1130 			pjdlog_exit(EX_OSERR, "select() failed");
1131 		}
1132 
1133 		/*
1134 		 * Check for signals before we do anything to update our
1135 		 * info about terminated workers in the meantime.
1136 		 */
1137 		check_signals();
1138 
1139 		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1140 			control_handle(cfg);
1141 		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1142 			if (lst->hl_conn == NULL)
1143 				continue;
1144 			if (FD_ISSET(proto_descriptor(lst->hl_conn), &rfds))
1145 				listen_accept(lst);
1146 		}
1147 		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1148 			if (res->hr_event == NULL)
1149 				continue;
1150 			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1151 				if (event_recv(res) == 0)
1152 					continue;
1153 				/* The worker process exited? */
1154 				proto_close(res->hr_event);
1155 				res->hr_event = NULL;
1156 				if (res->hr_conn != NULL) {
1157 					proto_close(res->hr_conn);
1158 					res->hr_conn = NULL;
1159 				}
1160 				continue;
1161 			}
1162 			if (res->hr_role == HAST_ROLE_PRIMARY) {
1163 				PJDLOG_ASSERT(res->hr_conn != NULL);
1164 				if (FD_ISSET(proto_descriptor(res->hr_conn),
1165 				    &rfds)) {
1166 					connection_migrate(res);
1167 				}
1168 			} else {
1169 				PJDLOG_ASSERT(res->hr_conn == NULL);
1170 			}
1171 		}
1172 	}
1173 }
1174 
1175 static void
1176 dummy_sighandler(int sig __unused)
1177 {
1178 	/* Nothing to do. */
1179 }
1180 
1181 int
1182 main(int argc, char *argv[])
1183 {
1184 	struct hastd_listen *lst;
1185 	pid_t otherpid;
1186 	int debuglevel;
1187 	sigset_t mask;
1188 
1189 	foreground = false;
1190 	debuglevel = 0;
1191 
1192 	for (;;) {
1193 		int ch;
1194 
1195 		ch = getopt(argc, argv, "c:dFhP:");
1196 		if (ch == -1)
1197 			break;
1198 		switch (ch) {
1199 		case 'c':
1200 			cfgpath = optarg;
1201 			break;
1202 		case 'd':
1203 			debuglevel++;
1204 			break;
1205 		case 'F':
1206 			foreground = true;
1207 			break;
1208 		case 'P':
1209 			pidfile = optarg;
1210 			break;
1211 		case 'h':
1212 		default:
1213 			usage();
1214 		}
1215 	}
1216 	argc -= optind;
1217 	argv += optind;
1218 
1219 	pjdlog_init(PJDLOG_MODE_STD);
1220 	pjdlog_debug_set(debuglevel);
1221 
1222 	closefrom(MAX(MAX(STDIN_FILENO, STDOUT_FILENO), STDERR_FILENO) + 1);
1223 	g_gate_load();
1224 
1225 	/*
1226 	 * When path to the configuration file is relative, obtain full path,
1227 	 * so we can always find the file, even after daemonizing and changing
1228 	 * working directory to /.
1229 	 */
1230 	if (cfgpath[0] != '/') {
1231 		const char *newcfgpath;
1232 
1233 		newcfgpath = realpath(cfgpath, NULL);
1234 		if (newcfgpath == NULL) {
1235 			pjdlog_exit(EX_CONFIG,
1236 			    "Unable to obtain full path of %s", cfgpath);
1237 		}
1238 		cfgpath = newcfgpath;
1239 	}
1240 
1241 	cfg = yy_config_parse(cfgpath, true);
1242 	PJDLOG_ASSERT(cfg != NULL);
1243 
1244 	if (pidfile != NULL) {
1245 		if (strlcpy(cfg->hc_pidfile, pidfile,
1246 		    sizeof(cfg->hc_pidfile)) >= sizeof(cfg->hc_pidfile)) {
1247 			pjdlog_exitx(EX_CONFIG, "Pidfile path is too long.");
1248 		}
1249 	}
1250 
1251 	if (pidfile != NULL || !foreground) {
1252 		pfh = pidfile_open(cfg->hc_pidfile, 0600, &otherpid);
1253 		if (pfh == NULL) {
1254 			if (errno == EEXIST) {
1255 				pjdlog_exitx(EX_TEMPFAIL,
1256 				    "Another hastd is already running, pidfile: %s, pid: %jd.",
1257 				    cfg->hc_pidfile, (intmax_t)otherpid);
1258 			}
1259 			/*
1260 			 * If we cannot create pidfile for other reasons,
1261 			 * only warn.
1262 			 */
1263 			pjdlog_errno(LOG_WARNING,
1264 			    "Unable to open or create pidfile %s",
1265 			    cfg->hc_pidfile);
1266 		}
1267 	}
1268 
1269 	/*
1270 	 * Restore default actions for interesting signals in case parent
1271 	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1272 	 */
1273 	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1274 	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1275 	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1276 	/*
1277 	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1278 	 * so we can mask it.
1279 	 */
1280 	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1281 
1282 	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1283 	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1284 	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1285 	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1286 	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1287 	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1288 
1289 	/* Listen on control address. */
1290 	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) == -1) {
1291 		KEEP_ERRNO((void)pidfile_remove(pfh));
1292 		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1293 		    cfg->hc_controladdr);
1294 	}
1295 	/* Listen for remote connections. */
1296 	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1297 		if (proto_server(lst->hl_addr, &lst->hl_conn) == -1) {
1298 			KEEP_ERRNO((void)pidfile_remove(pfh));
1299 			pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1300 			    lst->hl_addr);
1301 		}
1302 	}
1303 
1304 	if (!foreground) {
1305 		if (daemon(0, 0) == -1) {
1306 			KEEP_ERRNO((void)pidfile_remove(pfh));
1307 			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1308 		}
1309 
1310 		/* Start logging to syslog. */
1311 		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1312 	}
1313 	if (pidfile != NULL || !foreground) {
1314 		/* Write PID to a file. */
1315 		if (pidfile_write(pfh) == -1) {
1316 			pjdlog_errno(LOG_WARNING,
1317 			    "Unable to write PID to a file %s",
1318 			    cfg->hc_pidfile);
1319 		} else {
1320 			pjdlog_debug(1, "PID stored in %s.", cfg->hc_pidfile);
1321 		}
1322 	}
1323 
1324 	pjdlog_info("Started successfully, running protocol version %d.",
1325 	    HAST_PROTO_VERSION);
1326 
1327 	pjdlog_debug(1, "Listening on control address %s.",
1328 	    cfg->hc_controladdr);
1329 	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next)
1330 		pjdlog_info("Listening on address %s.", lst->hl_addr);
1331 
1332 	hook_init();
1333 
1334 	main_loop();
1335 
1336 	exit(0);
1337 }
1338