hastd.c revision 229945
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: head/sbin/hastd/hastd.c 229945 2012-01-10 22:39:07Z pjd $");
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. */
64const char *cfgpath = HAST_CONFIG;
65/* Hastd configuration. */
66static struct hastd_config *cfg;
67/* Was SIGINT or SIGTERM signal received? */
68bool sigexit_received = false;
69/* PID file handle. */
70struct pidfh *pfh;
71/* Do we run in foreground? */
72static bool foreground;
73
74/* How often check for hooks running for too long. */
75#define	REPORT_INTERVAL	5
76
77static void
78usage(void)
79{
80
81	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
82}
83
84static void
85g_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
99void
100descriptors_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
135static const char *
136dtype2str(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
159void
160descriptors_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
301static void
302child_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
317static void
318child_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
364static bool
365resource_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
401static bool
402resource_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
432static void
433resource_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
475static void
476hastd_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	(void)pidfile_remove(pfh);
577	pfh = newpfh;
578	(void)strlcpy(cfg->hc_pidfile, newcfg->hc_pidfile,
579	    sizeof(cfg->hc_pidfile));
580	/*
581	 * Switch to new listen addresses. Close all that were removed.
582	 */
583	while ((clst = TAILQ_FIRST(&cfg->hc_listen)) != NULL) {
584		TAILQ_FOREACH(nlst, &newcfg->hc_listen, hl_next) {
585			if (strcmp(nlst->hl_addr, clst->hl_addr) == 0)
586				break;
587		}
588		if (nlst == NULL && clst->hl_conn != NULL) {
589			proto_close(clst->hl_conn);
590			pjdlog_info("No longer listening on address %s.",
591			    clst->hl_addr);
592		}
593		TAILQ_REMOVE(&cfg->hc_listen, clst, hl_next);
594		free(clst);
595	}
596	TAILQ_CONCAT(&cfg->hc_listen, &newcfg->hc_listen, hl_next);
597
598	/*
599	 * Stop and remove resources that were removed from the configuration.
600	 */
601	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
602		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
603			if (strcmp(cres->hr_name, nres->hr_name) == 0)
604				break;
605		}
606		if (nres == NULL) {
607			control_set_role(cres, HAST_ROLE_INIT);
608			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
609			pjdlog_info("Resource %s removed.", cres->hr_name);
610			free(cres);
611		}
612	}
613	/*
614	 * Move new resources to the current configuration.
615	 */
616	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
617		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
618			if (strcmp(cres->hr_name, nres->hr_name) == 0)
619				break;
620		}
621		if (cres == NULL) {
622			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
623			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
624			pjdlog_info("Resource %s added.", nres->hr_name);
625		}
626	}
627	/*
628	 * Deal with modified resources.
629	 * Depending on what has changed exactly we might want to perform
630	 * different actions.
631	 *
632	 * We do full resource restart in the following situations:
633	 * Resource role is INIT or SECONDARY.
634	 * Resource role is PRIMARY and path to local component or provider
635	 * name has changed.
636	 * In case of PRIMARY, the worker process will be killed and restarted,
637	 * which also means removing /dev/hast/<name> provider and
638	 * recreating it.
639	 *
640	 * We do just reload (send SIGHUP to worker process) if we act as
641	 * PRIMARY, but only if remote address, source address, replication
642	 * mode, timeout, execution path or metaflush has changed.
643	 * For those, there is no need to restart worker process.
644	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
645	 * source address has changed or it will set new timeout if only timeout
646	 * has changed or it will update metaflush if only metaflush has
647	 * changed.
648	 */
649	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
650		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
651			if (strcmp(cres->hr_name, nres->hr_name) == 0)
652				break;
653		}
654		PJDLOG_ASSERT(cres != NULL);
655		if (resource_needs_restart(cres, nres)) {
656			pjdlog_info("Resource %s configuration was modified, restarting it.",
657			    cres->hr_name);
658			role = cres->hr_role;
659			control_set_role(cres, HAST_ROLE_INIT);
660			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
661			free(cres);
662			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
663			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
664			control_set_role(nres, role);
665		} else if (resource_needs_reload(cres, nres)) {
666			pjdlog_info("Resource %s configuration was modified, reloading it.",
667			    cres->hr_name);
668			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
669			    sizeof(cres->hr_remoteaddr));
670			strlcpy(cres->hr_sourceaddr, nres->hr_sourceaddr,
671			    sizeof(cres->hr_sourceaddr));
672			cres->hr_replication = nres->hr_replication;
673			cres->hr_checksum = nres->hr_checksum;
674			cres->hr_compression = nres->hr_compression;
675			cres->hr_timeout = nres->hr_timeout;
676			strlcpy(cres->hr_exec, nres->hr_exec,
677			    sizeof(cres->hr_exec));
678			cres->hr_metaflush = nres->hr_metaflush;
679			if (cres->hr_workerpid != 0)
680				resource_reload(cres);
681		}
682	}
683
684	yy_config_free(newcfg);
685	pjdlog_info("Configuration reloaded successfully.");
686	return;
687failed:
688	if (newcfg != NULL) {
689		if (newcfg->hc_controlconn != NULL)
690			proto_close(newcfg->hc_controlconn);
691		while ((nlst = TAILQ_FIRST(&newcfg->hc_listen)) != NULL) {
692			if (nlst->hl_conn != NULL) {
693				TAILQ_FOREACH(clst, &cfg->hc_listen, hl_next) {
694					if (strcmp(nlst->hl_addr,
695					    clst->hl_addr) == 0) {
696						break;
697					}
698				}
699				if (clst == NULL || clst->hl_conn == NULL)
700					proto_close(nlst->hl_conn);
701			}
702			TAILQ_REMOVE(&newcfg->hc_listen, nlst, hl_next);
703			free(nlst);
704		}
705		yy_config_free(newcfg);
706	}
707	if (newpfh != NULL)
708		(void)pidfile_remove(newpfh);
709	pjdlog_warning("Configuration not reloaded.");
710}
711
712static void
713terminate_workers(void)
714{
715	struct hast_resource *res;
716
717	pjdlog_info("Termination signal received, exiting.");
718	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
719		if (res->hr_workerpid == 0)
720			continue;
721		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
722		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
723		if (kill(res->hr_workerpid, SIGTERM) == 0)
724			continue;
725		pjdlog_errno(LOG_WARNING,
726		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
727		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
728	}
729}
730
731static void
732listen_accept(struct hastd_listen *lst)
733{
734	struct hast_resource *res;
735	struct proto_conn *conn;
736	struct nv *nvin, *nvout, *nverr;
737	const char *resname;
738	const unsigned char *token;
739	char laddr[256], raddr[256];
740	size_t size;
741	pid_t pid;
742	int status;
743
744	proto_local_address(lst->hl_conn, laddr, sizeof(laddr));
745	pjdlog_debug(1, "Accepting connection to %s.", laddr);
746
747	if (proto_accept(lst->hl_conn, &conn) == -1) {
748		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
749		return;
750	}
751
752	proto_local_address(conn, laddr, sizeof(laddr));
753	proto_remote_address(conn, raddr, sizeof(raddr));
754	pjdlog_info("Connection from %s to %s.", raddr, laddr);
755
756	/* Error in setting timeout is not critical, but why should it fail? */
757	if (proto_timeout(conn, HAST_TIMEOUT) == -1)
758		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
759
760	nvin = nvout = nverr = NULL;
761
762	/*
763	 * Before receiving any data see if remote host have access to any
764	 * resource.
765	 */
766	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
767		if (proto_address_match(conn, res->hr_remoteaddr))
768			break;
769	}
770	if (res == NULL) {
771		pjdlog_error("Client %s isn't known.", raddr);
772		goto close;
773	}
774	/* Ok, remote host can access at least one resource. */
775
776	if (hast_proto_recv_hdr(conn, &nvin) == -1) {
777		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
778		    raddr);
779		goto close;
780	}
781
782	resname = nv_get_string(nvin, "resource");
783	if (resname == NULL) {
784		pjdlog_error("No 'resource' field in the header received from %s.",
785		    raddr);
786		goto close;
787	}
788	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
789	token = nv_get_uint8_array(nvin, &size, "token");
790	/*
791	 * NULL token means that this is first connection.
792	 */
793	if (token != NULL && size != sizeof(res->hr_token)) {
794		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
795		    raddr, sizeof(res->hr_token), size);
796		goto close;
797	}
798
799	/*
800	 * From now on we want to send errors to the remote node.
801	 */
802	nverr = nv_alloc();
803
804	/* Find resource related to this connection. */
805	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
806		if (strcmp(resname, res->hr_name) == 0)
807			break;
808	}
809	/* Have we found the resource? */
810	if (res == NULL) {
811		pjdlog_error("No resource '%s' as requested by %s.",
812		    resname, raddr);
813		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
814		goto fail;
815	}
816
817	/* Now that we know resource name setup log prefix. */
818	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
819
820	/* Does the remote host have access to this resource? */
821	if (!proto_address_match(conn, res->hr_remoteaddr)) {
822		pjdlog_error("Client %s has no access to the resource.", raddr);
823		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
824		goto fail;
825	}
826	/* Is the resource marked as secondary? */
827	if (res->hr_role != HAST_ROLE_SECONDARY) {
828		pjdlog_warning("We act as %s for the resource and not as %s as requested by %s.",
829		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
830		    raddr);
831		nv_add_stringf(nverr, "errmsg",
832		    "Remote node acts as %s for the resource and not as %s.",
833		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
834		if (res->hr_role == HAST_ROLE_PRIMARY) {
835			/*
836			 * If we act as primary request the other side to wait
837			 * for us a bit, as we might be finishing cleanups.
838			 */
839			nv_add_uint8(nverr, 1, "wait");
840		}
841		goto fail;
842	}
843	/* Does token (if exists) match? */
844	if (token != NULL && memcmp(token, res->hr_token,
845	    sizeof(res->hr_token)) != 0) {
846		pjdlog_error("Token received from %s doesn't match.", raddr);
847		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
848		goto fail;
849	}
850	/*
851	 * If there is no token, but we have half-open connection
852	 * (only remotein) or full connection (worker process is running)
853	 * we have to cancel those and accept the new connection.
854	 */
855	if (token == NULL) {
856		PJDLOG_ASSERT(res->hr_remoteout == NULL);
857		pjdlog_debug(1, "Initial connection from %s.", raddr);
858		if (res->hr_workerpid != 0) {
859			PJDLOG_ASSERT(res->hr_remotein == NULL);
860			pjdlog_debug(1,
861			    "Worker process exists (pid=%u), stopping it.",
862			    (unsigned int)res->hr_workerpid);
863			/* Stop child process. */
864			if (kill(res->hr_workerpid, SIGINT) == -1) {
865				pjdlog_errno(LOG_ERR,
866				    "Unable to stop worker process (pid=%u)",
867				    (unsigned int)res->hr_workerpid);
868				/*
869				 * Other than logging the problem we
870				 * ignore it - nothing smart to do.
871				 */
872			}
873			/* Wait for it to exit. */
874			else if ((pid = waitpid(res->hr_workerpid,
875			    &status, 0)) != res->hr_workerpid) {
876				/* We can only log the problem. */
877				pjdlog_errno(LOG_ERR,
878				    "Waiting for worker process (pid=%u) failed",
879				    (unsigned int)res->hr_workerpid);
880			} else {
881				child_exit_log(res->hr_workerpid, status);
882			}
883			child_cleanup(res);
884		} else if (res->hr_remotein != NULL) {
885			char oaddr[256];
886
887			proto_remote_address(res->hr_remotein, oaddr,
888			    sizeof(oaddr));
889			pjdlog_debug(1,
890			    "Canceling half-open connection from %s on connection from %s.",
891			    oaddr, raddr);
892			proto_close(res->hr_remotein);
893			res->hr_remotein = NULL;
894		}
895	}
896
897	/*
898	 * Checks and cleanups are done.
899	 */
900
901	if (token == NULL) {
902		arc4random_buf(res->hr_token, sizeof(res->hr_token));
903		nvout = nv_alloc();
904		nv_add_uint8_array(nvout, res->hr_token,
905		    sizeof(res->hr_token), "token");
906		if (nv_error(nvout) != 0) {
907			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
908			    "Unable to prepare return header for %s", raddr);
909			nv_add_stringf(nverr, "errmsg",
910			    "Remote node was unable to prepare return header: %s.",
911			    strerror(nv_error(nvout)));
912			goto fail;
913		}
914		if (hast_proto_send(NULL, conn, nvout, NULL, 0) == -1) {
915			int error = errno;
916
917			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
918			    raddr);
919			nv_add_stringf(nverr, "errmsg",
920			    "Remote node was unable to send response: %s.",
921			    strerror(error));
922			goto fail;
923		}
924		res->hr_remotein = conn;
925		pjdlog_debug(1, "Incoming connection from %s configured.",
926		    raddr);
927	} else {
928		res->hr_remoteout = conn;
929		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
930		hastd_secondary(res, nvin);
931	}
932	nv_free(nvin);
933	nv_free(nvout);
934	nv_free(nverr);
935	pjdlog_prefix_set("%s", "");
936	return;
937fail:
938	if (nv_error(nverr) != 0) {
939		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
940		    "Unable to prepare error header for %s", raddr);
941		goto close;
942	}
943	if (hast_proto_send(NULL, conn, nverr, NULL, 0) == -1) {
944		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
945		goto close;
946	}
947close:
948	if (nvin != NULL)
949		nv_free(nvin);
950	if (nvout != NULL)
951		nv_free(nvout);
952	if (nverr != NULL)
953		nv_free(nverr);
954	proto_close(conn);
955	pjdlog_prefix_set("%s", "");
956}
957
958static void
959connection_migrate(struct hast_resource *res)
960{
961	struct proto_conn *conn;
962	int16_t val = 0;
963
964	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
965
966	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
967
968	if (proto_recv(res->hr_conn, &val, sizeof(val)) == -1) {
969		pjdlog_errno(LOG_WARNING,
970		    "Unable to receive connection command");
971		return;
972	}
973	if (proto_client(res->hr_sourceaddr[0] != '\0' ? res->hr_sourceaddr : NULL,
974	    res->hr_remoteaddr, &conn) == -1) {
975		val = errno;
976		pjdlog_errno(LOG_WARNING,
977		    "Unable to create outgoing connection to %s",
978		    res->hr_remoteaddr);
979		goto out;
980	}
981	if (proto_connect(conn, -1) == -1) {
982		val = errno;
983		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
984		    res->hr_remoteaddr);
985		proto_close(conn);
986		goto out;
987	}
988	val = 0;
989out:
990	if (proto_send(res->hr_conn, &val, sizeof(val)) == -1) {
991		pjdlog_errno(LOG_WARNING,
992		    "Unable to send reply to connection request");
993	}
994	if (val == 0 && proto_connection_send(res->hr_conn, conn) == -1)
995		pjdlog_errno(LOG_WARNING, "Unable to send connection");
996
997	pjdlog_prefix_set("%s", "");
998}
999
1000static void
1001check_signals(void)
1002{
1003	struct timespec sigtimeout;
1004	sigset_t mask;
1005	int signo;
1006
1007	sigtimeout.tv_sec = 0;
1008	sigtimeout.tv_nsec = 0;
1009
1010	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1011	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1012	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1013	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1014	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1015
1016	while ((signo = sigtimedwait(&mask, NULL, &sigtimeout)) != -1) {
1017		switch (signo) {
1018		case SIGINT:
1019		case SIGTERM:
1020			sigexit_received = true;
1021			terminate_workers();
1022			proto_close(cfg->hc_controlconn);
1023			exit(EX_OK);
1024			break;
1025		case SIGCHLD:
1026			child_exit();
1027			break;
1028		case SIGHUP:
1029			hastd_reload();
1030			break;
1031		default:
1032			PJDLOG_ABORT("Unexpected signal (%d).", signo);
1033		}
1034	}
1035}
1036
1037static void
1038main_loop(void)
1039{
1040	struct hast_resource *res;
1041	struct hastd_listen *lst;
1042	struct timeval seltimeout;
1043	int fd, maxfd, ret;
1044	time_t lastcheck, now;
1045	fd_set rfds;
1046
1047	lastcheck = time(NULL);
1048	seltimeout.tv_sec = REPORT_INTERVAL;
1049	seltimeout.tv_usec = 0;
1050
1051	for (;;) {
1052		check_signals();
1053
1054		/* Setup descriptors for select(2). */
1055		FD_ZERO(&rfds);
1056		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
1057		PJDLOG_ASSERT(fd >= 0);
1058		FD_SET(fd, &rfds);
1059		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1060			if (lst->hl_conn == NULL)
1061				continue;
1062			fd = proto_descriptor(lst->hl_conn);
1063			PJDLOG_ASSERT(fd >= 0);
1064			FD_SET(fd, &rfds);
1065			maxfd = fd > maxfd ? fd : maxfd;
1066		}
1067		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1068			if (res->hr_event == NULL)
1069				continue;
1070			fd = proto_descriptor(res->hr_event);
1071			PJDLOG_ASSERT(fd >= 0);
1072			FD_SET(fd, &rfds);
1073			maxfd = fd > maxfd ? fd : maxfd;
1074			if (res->hr_role == HAST_ROLE_PRIMARY) {
1075				/* Only primary workers asks for connections. */
1076				PJDLOG_ASSERT(res->hr_conn != NULL);
1077				fd = proto_descriptor(res->hr_conn);
1078				PJDLOG_ASSERT(fd >= 0);
1079				FD_SET(fd, &rfds);
1080				maxfd = fd > maxfd ? fd : maxfd;
1081			} else {
1082				PJDLOG_ASSERT(res->hr_conn == NULL);
1083			}
1084		}
1085
1086		PJDLOG_ASSERT(maxfd + 1 <= (int)FD_SETSIZE);
1087		ret = select(maxfd + 1, &rfds, NULL, NULL, &seltimeout);
1088		now = time(NULL);
1089		if (lastcheck + REPORT_INTERVAL <= now) {
1090			hook_check();
1091			lastcheck = now;
1092		}
1093		if (ret == 0) {
1094			/*
1095			 * select(2) timed out, so there should be no
1096			 * descriptors to check.
1097			 */
1098			continue;
1099		} else if (ret == -1) {
1100			if (errno == EINTR)
1101				continue;
1102			KEEP_ERRNO((void)pidfile_remove(pfh));
1103			pjdlog_exit(EX_OSERR, "select() failed");
1104		}
1105
1106		/*
1107		 * Check for signals before we do anything to update our
1108		 * info about terminated workers in the meantime.
1109		 */
1110		check_signals();
1111
1112		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
1113			control_handle(cfg);
1114		TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1115			if (lst->hl_conn == NULL)
1116				continue;
1117			if (FD_ISSET(proto_descriptor(lst->hl_conn), &rfds))
1118				listen_accept(lst);
1119		}
1120		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
1121			if (res->hr_event == NULL)
1122				continue;
1123			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
1124				if (event_recv(res) == 0)
1125					continue;
1126				/* The worker process exited? */
1127				proto_close(res->hr_event);
1128				res->hr_event = NULL;
1129				if (res->hr_conn != NULL) {
1130					proto_close(res->hr_conn);
1131					res->hr_conn = NULL;
1132				}
1133				continue;
1134			}
1135			if (res->hr_role == HAST_ROLE_PRIMARY) {
1136				PJDLOG_ASSERT(res->hr_conn != NULL);
1137				if (FD_ISSET(proto_descriptor(res->hr_conn),
1138				    &rfds)) {
1139					connection_migrate(res);
1140				}
1141			} else {
1142				PJDLOG_ASSERT(res->hr_conn == NULL);
1143			}
1144		}
1145	}
1146}
1147
1148static void
1149dummy_sighandler(int sig __unused)
1150{
1151	/* Nothing to do. */
1152}
1153
1154int
1155main(int argc, char *argv[])
1156{
1157	struct hastd_listen *lst;
1158	const char *pidfile;
1159	pid_t otherpid;
1160	int debuglevel;
1161	sigset_t mask;
1162
1163	foreground = false;
1164	debuglevel = 0;
1165	pidfile = NULL;
1166
1167	for (;;) {
1168		int ch;
1169
1170		ch = getopt(argc, argv, "c:dFhP:");
1171		if (ch == -1)
1172			break;
1173		switch (ch) {
1174		case 'c':
1175			cfgpath = optarg;
1176			break;
1177		case 'd':
1178			debuglevel++;
1179			break;
1180		case 'F':
1181			foreground = true;
1182			break;
1183		case 'P':
1184			pidfile = optarg;
1185			break;
1186		case 'h':
1187		default:
1188			usage();
1189		}
1190	}
1191	argc -= optind;
1192	argv += optind;
1193
1194	pjdlog_init(PJDLOG_MODE_STD);
1195	pjdlog_debug_set(debuglevel);
1196
1197	g_gate_load();
1198
1199	/*
1200	 * When path to the configuration file is relative, obtain full path,
1201	 * so we can always find the file, even after daemonizing and changing
1202	 * working directory to /.
1203	 */
1204	if (cfgpath[0] != '/') {
1205		const char *newcfgpath;
1206
1207		newcfgpath = realpath(cfgpath, NULL);
1208		if (newcfgpath == NULL) {
1209			pjdlog_exit(EX_CONFIG,
1210			    "Unable to obtain full path of %s", cfgpath);
1211		}
1212		cfgpath = newcfgpath;
1213	}
1214
1215	cfg = yy_config_parse(cfgpath, true);
1216	PJDLOG_ASSERT(cfg != NULL);
1217
1218	if (pidfile != NULL) {
1219		if (strlcpy(cfg->hc_pidfile, pidfile,
1220		    sizeof(cfg->hc_pidfile)) >= sizeof(cfg->hc_pidfile)) {
1221			pjdlog_exitx(EX_CONFIG, "Pidfile path is too long.");
1222		}
1223	}
1224
1225	if (!foreground) {
1226		pfh = pidfile_open(cfg->hc_pidfile, 0600, &otherpid);
1227		if (pfh == NULL) {
1228			if (errno == EEXIST) {
1229				pjdlog_exitx(EX_TEMPFAIL,
1230				    "Another hastd is already running, pidfile: %s, pid: %jd.",
1231				    cfg->hc_pidfile, (intmax_t)otherpid);
1232			}
1233			/*
1234			 * If we cannot create pidfile for other reasons,
1235			 * only warn.
1236			 */
1237			pjdlog_errno(LOG_WARNING,
1238			    "Unable to open or create pidfile %s",
1239			    cfg->hc_pidfile);
1240		}
1241	}
1242
1243	/*
1244	 * Restore default actions for interesting signals in case parent
1245	 * process (like init(8)) decided to ignore some of them (like SIGHUP).
1246	 */
1247	PJDLOG_VERIFY(signal(SIGHUP, SIG_DFL) != SIG_ERR);
1248	PJDLOG_VERIFY(signal(SIGINT, SIG_DFL) != SIG_ERR);
1249	PJDLOG_VERIFY(signal(SIGTERM, SIG_DFL) != SIG_ERR);
1250	/*
1251	 * Because SIGCHLD is ignored by default, setup dummy handler for it,
1252	 * so we can mask it.
1253	 */
1254	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
1255
1256	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1257	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1258	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1259	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1260	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1261	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
1262
1263	/* Listen on control address. */
1264	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) == -1) {
1265		KEEP_ERRNO((void)pidfile_remove(pfh));
1266		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
1267		    cfg->hc_controladdr);
1268	}
1269	/* Listen for remote connections. */
1270	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next) {
1271		if (proto_server(lst->hl_addr, &lst->hl_conn) == -1) {
1272			KEEP_ERRNO((void)pidfile_remove(pfh));
1273			pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
1274			    lst->hl_addr);
1275		}
1276	}
1277
1278	if (!foreground) {
1279		if (daemon(0, 0) == -1) {
1280			KEEP_ERRNO((void)pidfile_remove(pfh));
1281			pjdlog_exit(EX_OSERR, "Unable to daemonize");
1282		}
1283
1284		/* Start logging to syslog. */
1285		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
1286
1287		/* Write PID to a file. */
1288		if (pidfile_write(pfh) == -1) {
1289			pjdlog_errno(LOG_WARNING,
1290			    "Unable to write PID to a file %s",
1291			    cfg->hc_pidfile);
1292		} else {
1293			pjdlog_debug(1, "PID stored in %s.", cfg->hc_pidfile);
1294		}
1295	}
1296
1297	pjdlog_info("Started successfully, running protocol version %d.",
1298	    HAST_PROTO_VERSION);
1299
1300	pjdlog_debug(1, "Listening on control address %s.",
1301	    cfg->hc_controladdr);
1302	TAILQ_FOREACH(lst, &cfg->hc_listen, hl_next)
1303		pjdlog_info("Listening on address %s.", lst->hl_addr);
1304
1305	hook_init();
1306
1307	main_loop();
1308
1309	exit(0);
1310}
1311