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