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