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