xref: /freebsd/sbin/hastd/hastd.c (revision c6ec7d31830ab1c80edae95ad5e4b9dba10c47ac)
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 /* PID file 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 	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 	token = nv_get_uint8_array(nvin, &size, "token");
801 	/*
802 	 * NULL token means that this is first connection.
803 	 */
804 	if (token != NULL && size != sizeof(res->hr_token)) {
805 		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
806 		    raddr, sizeof(res->hr_token), size);
807 		goto close;
808 	}
809 
810 	/*
811 	 * From now on we want to send errors to the remote node.
812 	 */
813 	nverr = nv_alloc();
814 
815 	/* Find resource related to this connection. */
816 	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
817 		if (strcmp(resname, res->hr_name) == 0)
818 			break;
819 	}
820 	/* Have we found the resource? */
821 	if (res == NULL) {
822 		pjdlog_error("No resource '%s' as requested by %s.",
823 		    resname, raddr);
824 		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
825 		goto fail;
826 	}
827 
828 	/* Now that we know resource name setup log prefix. */
829 	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
830 
831 	/* Does the remote host have access to this resource? */
832 	if (!proto_address_match(conn, res->hr_remoteaddr)) {
833 		pjdlog_error("Client %s has no access to the resource.", raddr);
834 		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
835 		goto fail;
836 	}
837 	/* Is the resource marked as secondary? */
838 	if (res->hr_role != HAST_ROLE_SECONDARY) {
839 		pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
840 		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
841 		    raddr);
842 		nv_add_stringf(nverr, "errmsg",
843 		    "Remote node acts as %s for the resource and not as %s.",
844 		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
845 		if (res->hr_role == HAST_ROLE_PRIMARY) {
846 			/*
847 			 * If we act as primary request the other side to wait
848 			 * for us a bit, as we might be finishing cleanups.
849 			 */
850 			nv_add_uint8(nverr, 1, "wait");
851 		}
852 		goto fail;
853 	}
854 	/* Does token (if exists) match? */
855 	if (token != NULL && memcmp(token, res->hr_token,
856 	    sizeof(res->hr_token)) != 0) {
857 		pjdlog_error("Token received from %s doesn't match.", raddr);
858 		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
859 		goto fail;
860 	}
861 	/*
862 	 * If there is no token, but we have half-open connection
863 	 * (only remotein) or full connection (worker process is running)
864 	 * we have to cancel those and accept the new connection.
865 	 */
866 	if (token == NULL) {
867 		PJDLOG_ASSERT(res->hr_remoteout == NULL);
868 		pjdlog_debug(1, "Initial connection from %s.", raddr);
869 		if (res->hr_workerpid != 0) {
870 			PJDLOG_ASSERT(res->hr_remotein == NULL);
871 			pjdlog_debug(1,
872 			    "Worker process exists (pid=%u), stopping it.",
873 			    (unsigned int)res->hr_workerpid);
874 			/* Stop child process. */
875 			if (kill(res->hr_workerpid, SIGINT) == -1) {
876 				pjdlog_errno(LOG_ERR,
877 				    "Unable to stop worker process (pid=%u)",
878 				    (unsigned int)res->hr_workerpid);
879 				/*
880 				 * Other than logging the problem we
881 				 * ignore it - nothing smart to do.
882 				 */
883 			}
884 			/* Wait for it to exit. */
885 			else if ((pid = waitpid(res->hr_workerpid,
886 			    &status, 0)) != res->hr_workerpid) {
887 				/* We can only log the problem. */
888 				pjdlog_errno(LOG_ERR,
889 				    "Waiting for worker process (pid=%u) failed",
890 				    (unsigned int)res->hr_workerpid);
891 			} else {
892 				child_exit_log(res->hr_workerpid, status);
893 			}
894 			child_cleanup(res);
895 		} else if (res->hr_remotein != NULL) {
896 			char oaddr[256];
897 
898 			proto_remote_address(res->hr_remotein, oaddr,
899 			    sizeof(oaddr));
900 			pjdlog_debug(1,
901 			    "Canceling half-open connection from %s on connection from %s.",
902 			    oaddr, raddr);
903 			proto_close(res->hr_remotein);
904 			res->hr_remotein = NULL;
905 		}
906 	}
907 
908 	/*
909 	 * Checks and cleanups are done.
910 	 */
911 
912 	if (token == NULL) {
913 		arc4random_buf(res->hr_token, sizeof(res->hr_token));
914 		nvout = nv_alloc();
915 		nv_add_uint8_array(nvout, res->hr_token,
916 		    sizeof(res->hr_token), "token");
917 		if (nv_error(nvout) != 0) {
918 			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
919 			    "Unable to prepare return header for %s", raddr);
920 			nv_add_stringf(nverr, "errmsg",
921 			    "Remote node was unable to prepare return header: %s.",
922 			    strerror(nv_error(nvout)));
923 			goto fail;
924 		}
925 		if (hast_proto_send(NULL, conn, nvout, NULL, 0) == -1) {
926 			int error = errno;
927 
928 			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
929 			    raddr);
930 			nv_add_stringf(nverr, "errmsg",
931 			    "Remote node was unable to send response: %s.",
932 			    strerror(error));
933 			goto fail;
934 		}
935 		res->hr_remotein = conn;
936 		pjdlog_debug(1, "Incoming connection from %s configured.",
937 		    raddr);
938 	} else {
939 		res->hr_remoteout = conn;
940 		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
941 		hastd_secondary(res, nvin);
942 	}
943 	nv_free(nvin);
944 	nv_free(nvout);
945 	nv_free(nverr);
946 	pjdlog_prefix_set("%s", "");
947 	return;
948 fail:
949 	if (nv_error(nverr) != 0) {
950 		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
951 		    "Unable to prepare error header for %s", raddr);
952 		goto close;
953 	}
954 	if (hast_proto_send(NULL, conn, nverr, NULL, 0) == -1) {
955 		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
956 		goto close;
957 	}
958 close:
959 	if (nvin != NULL)
960 		nv_free(nvin);
961 	if (nvout != NULL)
962 		nv_free(nvout);
963 	if (nverr != NULL)
964 		nv_free(nverr);
965 	proto_close(conn);
966 	pjdlog_prefix_set("%s", "");
967 }
968 
969 static void
970 connection_migrate(struct hast_resource *res)
971 {
972 	struct proto_conn *conn;
973 	int16_t val = 0;
974 
975 	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
976 
977 	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
978 
979 	if (proto_recv(res->hr_conn, &val, sizeof(val)) == -1) {
980 		pjdlog_errno(LOG_WARNING,
981 		    "Unable to receive connection command");
982 		return;
983 	}
984 	if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
985 	    res->hr_remoteaddr, &conn) == -1) {
986 		val = errno;
987 		pjdlog_errno(LOG_WARNING,
988 		    "Unable to create outgoing connection to %s",
989 		    res->hr_remoteaddr);
990 		goto out;
991 	}
992 	if (proto_connect(conn, -1) == -1) {
993 		val = errno;
994 		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
995 		    res->hr_remoteaddr);
996 		proto_close(conn);
997 		goto out;
998 	}
999 	val = 0;
1000 out:
1001 	if (proto_send(res->hr_conn, &val, sizeof(val)) == -1) {
1002 		pjdlog_errno(LOG_WARNING,
1003 		    "Unable to send reply to connection request");
1004 	}
1005 	if (val == 0 && proto_connection_send(res->hr_conn, conn) == -1)
1006 		pjdlog_errno(LOG_WARNING, "Unable to send connection");
1007 
1008 	pjdlog_prefix_set("%s", "");
1009 }
1010 
1011 static void
1012 check_signals(void)
1013 {
1014 	struct timespec sigtimeout;
1015 	sigset_t mask;
1016 	int signo;
1017 
1018 	sigtimeout.tv_sec = 0;
1019 	sigtimeout.tv_nsec = 0;
1020 
1021 	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1022 	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1023 	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1024 	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1025 	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1026 
1027 	while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
1028 		switch (signo) {
1029 		case SIGINT:
1030 		case SIGTERM:
1031 			sigexit_received = true;
1032 			terminate_workers();
1033 			proto_close(cfg->hc_controlconn);
1034 			exit(EX_OK);
1035 			break;
1036 		case SIGCHLD:
1037 			child_exit();
1038 			break;
1039 		case SIGHUP:
1040 			hastd_reload();
1041 			break;
1042 		default:
1043 			PJDLOG_ABORT("Unexpected signal (%d).", signo);
1044 		}
1045 	}
1046 }
1047 
1048 static void
1049 main_loop(void)
1050 {
1051 	struct hast_resource *res;
1052 	struct hastd_listen *lst;
1053 	struct timeval seltimeout;
1054 	int fd, maxfd, ret;
1055 	time_t lastcheck, now;
1056 	fd_set rfds;
1057 
1058 	lastcheck = time(NULL);
1059 	seltimeout.tv_sec = REPORT_INTERVAL;
1060 	seltimeout.tv_usec = 0;
1061 
1062 	for (;;) {
1063 		check_signals();
1064 
1065 		/* Setup descriptors for select(2). */
1066 		FD_ZERO(&rfds);
1067 		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
1068 		PJDLOG_ASSERT(fd >= 0);
1069 		FD_SET(fd, &rfds);
1070 		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1071 			if (lst->hl_conn == NULL)
1072 				continue;
1073 			fd = proto_descriptor(lst->hl_conn);
1074 			PJDLOG_ASSERT(fd >= 0);
1075 			FD_SET(fd, &rfds);
1076 			maxfd = fd > maxfd ? fd : maxfd;
1077 		}
1078 		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1079 			if (res->hr_event == NULL)
1080 				continue;
1081 			fd = proto_descriptor(res->hr_event);
1082 			PJDLOG_ASSERT(fd >= 0);
1083 			FD_SET(fd, &rfds);
1084 			maxfd = fd > maxfd ? fd : maxfd;
1085 			if (res->hr_role == HAST_ROLE_PRIMARY) {
1086 				/* Only primary workers asks for connections. */
1087 				PJDLOG_ASSERT(res->hr_conn != NULL);
1088 				fd = proto_descriptor(res->hr_conn);
1089 				PJDLOG_ASSERT(fd >= 0);
1090 				FD_SET(fd, &rfds);
1091 				maxfd = fd > maxfd ? fd : maxfd;
1092 			} else {
1093 				PJDLOG_ASSERT(res->hr_conn == NULL);
1094 			}
1095 		}
1096 
1097 		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
1098 		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
1099 		now = time(NULL);
1100 		if (lastcheck + REPORT_INTERVAL <= now) {
1101 			hook_check();
1102 			lastcheck = now;
1103 		}
1104 		if (ret == 0) {
1105 			/*
1106 			 * select(2) timed out, so there should be no
1107 			 * descriptors to check.
1108 			 */
1109 			continue;
1110 		} else if (ret == -1) {
1111 			if (errno == EINTR)
1112 				continue;
1113 			KEEP_ERRNO((void)pidfile_remove(pfh));
1114 			pjdlog_exit(EX_OSERR, "select() failed");
1115 		}
1116 
1117 		/*
1118 		 * Check for signals before we do anything to update our
1119 		 * info about terminated workers in the meantime.
1120 		 */
1121 		check_signals();
1122 
1123 		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1124 			control_handle(cfg);
1125 		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1126 			if (lst->hl_conn == NULL)
1127 				continue;
1128 			if (FD_ISSET(proto_descriptor(lst->hl_conn), &rfds))
1129 				listen_accept(lst);
1130 		}
1131 		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1132 			if (res->hr_event == NULL)
1133 				continue;
1134 			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1135 				if (event_recv(res) == 0)
1136 					continue;
1137 				/* The worker process exited? */
1138 				proto_close(res->hr_event);
1139 				res->hr_event = NULL;
1140 				if (res->hr_conn != NULL) {
1141 					proto_close(res->hr_conn);
1142 					res->hr_conn = NULL;
1143 				}
1144 				continue;
1145 			}
1146 			if (res->hr_role == HAST_ROLE_PRIMARY) {
1147 				PJDLOG_ASSERT(res->hr_conn != NULL);
1148 				if (FD_ISSET(proto_descriptor(res->hr_conn),
1149 				    &rfds)) {
1150 					connection_migrate(res);
1151 				}
1152 			} else {
1153 				PJDLOG_ASSERT(res->hr_conn == NULL);
1154 			}
1155 		}
1156 	}
1157 }
1158 
1159 static void
1160 dummy_sighandler(int sig __unused)
1161 {
1162 	/* Nothing to do. */
1163 }
1164 
1165 int
1166 main(int argc, char *argv[])
1167 {
1168 	struct hastd_listen *lst;
1169 	pid_t otherpid;
1170 	int debuglevel;
1171 	sigset_t mask;
1172 
1173 	foreground = false;
1174 	debuglevel = 0;
1175 
1176 	for (;;) {
1177 		int ch;
1178 
1179 		ch = getopt(argc, argv, "c:dFhP:");
1180 		if (ch == -1)
1181 			break;
1182 		switch (ch) {
1183 		case 'c':
1184 			cfgpath = optarg;
1185 			break;
1186 		case 'd':
1187 			debuglevel++;
1188 			break;
1189 		case 'F':
1190 			foreground = true;
1191 			break;
1192 		case 'P':
1193 			pidfile = optarg;
1194 			break;
1195 		case 'h':
1196 		default:
1197 			usage();
1198 		}
1199 	}
1200 	argc -= optind;
1201 	argv += optind;
1202 
1203 	pjdlog_init(PJDLOG_MODE_STD);
1204 	pjdlog_debug_set(debuglevel);
1205 
1206 	g_gate_load();
1207 
1208 	/*
1209 	 * When path to the configuration file is relative, obtain full path,
1210 	 * so we can always find the file, even after daemonizing and changing
1211 	 * working directory to /.
1212 	 */
1213 	if (cfgpath[0] != '/') {
1214 		const char *newcfgpath;
1215 
1216 		newcfgpath = realpath(cfgpath, NULL);
1217 		if (newcfgpath == NULL) {
1218 			pjdlog_exit(EX_CONFIG,
1219 			    "Unable to obtain full path of %s", cfgpath);
1220 		}
1221 		cfgpath = newcfgpath;
1222 	}
1223 
1224 	cfg = yy_config_parse(cfgpath, true);
1225 	PJDLOG_ASSERT(cfg != NULL);
1226 
1227 	if (pidfile != NULL) {
1228 		if (strlcpy(cfg->hc_pidfile, pidfile,
1229 		    sizeof(cfg->hc_pidfile)) >= sizeof(cfg->hc_pidfile)) {
1230 			pjdlog_exitx(EX_CONFIG, "Pidfile path is too long.");
1231 		}
1232 	}
1233 
1234 	if (pidfile != NULL || !foreground) {
1235 		pfh = pidfile_open(cfg->hc_pidfile, 0600, &otherpid);
1236 		if (pfh == NULL) {
1237 			if (errno == EEXIST) {
1238 				pjdlog_exitx(EX_TEMPFAIL,
1239 				    "Another hastd is already running, pidfile: %s, pid: %jd.",
1240 				    cfg->hc_pidfile, (intmax_t)otherpid);
1241 			}
1242 			/*
1243 			 * If we cannot create pidfile for other reasons,
1244 			 * only warn.
1245 			 */
1246 			pjdlog_errno(LOG_WARNING,
1247 			    "Unable to open or create pidfile %s",
1248 			    cfg->hc_pidfile);
1249 		}
1250 	}
1251 
1252 	/*
1253 	 * Restore default actions for interesting signals in case parent
1254 	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1255 	 */
1256 	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1257 	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1258 	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1259 	/*
1260 	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1261 	 * so we can mask it.
1262 	 */
1263 	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1264 
1265 	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1266 	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1267 	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1268 	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1269 	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1270 	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1271 
1272 	/* Listen on control address. */
1273 	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) == -1) {
1274 		KEEP_ERRNO((void)pidfile_remove(pfh));
1275 		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1276 		    cfg->hc_controladdr);
1277 	}
1278 	/* Listen for remote connections. */
1279 	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1280 		if (proto_server(lst->hl_addr, &lst->hl_conn) == -1) {
1281 			KEEP_ERRNO((void)pidfile_remove(pfh));
1282 			pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1283 			    lst->hl_addr);
1284 		}
1285 	}
1286 
1287 	if (!foreground) {
1288 		if (daemon(0, 0) == -1) {
1289 			KEEP_ERRNO((void)pidfile_remove(pfh));
1290 			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1291 		}
1292 
1293 		/* Start logging to syslog. */
1294 		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1295 	}
1296 	if (pidfile != NULL || !foreground) {
1297 		/* Write PID to a file. */
1298 		if (pidfile_write(pfh) == -1) {
1299 			pjdlog_errno(LOG_WARNING,
1300 			    "Unable to write PID to a file %s",
1301 			    cfg->hc_pidfile);
1302 		} else {
1303 			pjdlog_debug(1, "PID stored in %s.", cfg->hc_pidfile);
1304 		}
1305 	}
1306 
1307 	pjdlog_info("Started successfully, running protocol version %d.",
1308 	    HAST_PROTO_VERSION);
1309 
1310 	pjdlog_debug(1, "Listening on control address %s.",
1311 	    cfg->hc_controladdr);
1312 	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next)
1313 		pjdlog_info("Listening on address %s.", lst->hl_addr);
1314 
1315 	hook_init();
1316 
1317 	main_loop();
1318 
1319 	exit(0);
1320 }
1321