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