hastd.c revision 211977
150477Speter/*-
240269Srnordier * Copyright (c) 2009-2010 The FreeBSD Foundation
3125537Sru * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
440326Srnordier * All rights reserved.
580751Sjhb *
680751Sjhb * This software was developed by Pawel Jakub Dawidek under sponsorship from
748919Srnordier * the FreeBSD Foundation.
862138Sjhb *
948919Srnordier * Redistribution and use in source and binary forms, with or without
1042480Srnordier * modification, are permitted provided that the following conditions
1142480Srnordier * are met:
1240541Srnordier * 1. Redistributions of source code must retain the above copyright
1340541Srnordier *    notice, this list of conditions and the following disclaimer.
14104673Sgreen * 2. Redistributions in binary form must reproduce the above copyright
1540269Srnordier *    notice, this list of conditions and the following disclaimer in the
16104683Sjhb *    documentation and/or other materials provided with the distribution.
1740269Srnordier *
18125537Sru * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19108000Simp * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20125537Sru * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21125537Sru * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22104635Sphk * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23125566Sru * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24108000Simp * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25108149Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2696327Sjhb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27107879Sphk * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28125932Sru * SUCH DAMAGE.
29125932Sru */
30125932Sru
31125932Sru#include <sys/cdefs.h>
3297860Sphk__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 211977 2010-08-29 21:41:53Z pjd $");
3396306Sobrien
3440269Srnordier#include <sys/param.h>
3540269Srnordier#include <sys/linker.h>
3640269Srnordier#include <sys/module.h>
3740269Srnordier#include <sys/wait.h>
38125621Sru
3940269Srnordier#include <assert.h>
40125537Sru#include <err.h>
41125537Sru#include <errno.h>
4240269Srnordier#include <libutil.h>
43125537Sru#include <signal.h>
44125537Sru#include <stdbool.h>
45109886Sphk#include <stdio.h>
46109886Sphk#include <stdlib.h>
47109886Sphk#include <string.h>
48125537Sru#include <sysexits.h>
49125537Sru#include <unistd.h>
5040269Srnordier
5140308Srnordier#include <activemap.h>
5240269Srnordier#include <pjdlog.h>
5340269Srnordier
5440269Srnordier#include "control.h"
5540269Srnordier#include "hast.h"
56125537Sru#include "hast_proto.h"
57125537Sru#include "hastd.h"
5896424Speter#include "hooks.h"
59125537Sru#include "subr.h"
60125537Sru
61125537Sru/* Path to configuration file. */
62125537Sruconst char *cfgpath = HAST_CONFIG;
6380751Sjhb/* Hastd configuration. */
64125537Srustatic struct hastd_config *cfg;
65125537Sru/* Was SIGCHLD signal received? */
66125537Srubool sigchld_received = false;
6740269Srnordier/* Was SIGHUP signal received? */
6840269Srnordierbool sighup_received = false;
69125537Sru/* Was SIGINT or SIGTERM signal received? */
7040269Srnordierbool sigexit_received = false;
7140269Srnordier/* PID file handle. */
7240308Srnordierstruct pidfh *pfh;
7340269Srnordier
74125537Sru/* How often check for hooks running for too long. */
75125537Sru#define	REPORT_INTERVAL	10
7640269Srnordier
77125537Srustatic void
7880751Sjhbusage(void)
79125564Sru{
80125564Sru
81125537Sru	errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
82125537Sru}
83125537Sru
84125537Srustatic void
8540404Srnordiersighandler(int sig)
86125537Sru{
87125537Sru
88125537Sru	switch (sig) {
89125537Sru	case SIGINT:
90125537Sru	case SIGTERM:
91125537Sru		sigexit_received = true;
9240326Srnordier		break;
93125556Sru	case SIGCHLD:
94125581Sru		sigchld_received = true;
95125556Sru		break;
96116864Speter	case SIGHUP:
97116864Speter		sighup_received = true;
98116864Speter		break;
99116864Speter	default:
100125537Sru		assert(!"invalid condition");
101	}
102}
103
104static void
105g_gate_load(void)
106{
107
108	if (modfind("g_gate") == -1) {
109		/* Not present in kernel, try loading it. */
110		if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
111			if (errno != EEXIST) {
112				pjdlog_exit(EX_OSERR,
113				    "Unable to load geom_gate module");
114			}
115		}
116	}
117}
118
119static void
120child_exit_log(unsigned int pid, int status)
121{
122
123	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
124		pjdlog_debug(1, "Worker process exited gracefully (pid=%u).",
125		    pid);
126	} else if (WIFSIGNALED(status)) {
127		pjdlog_error("Worker process killed (pid=%u, signal=%d).",
128		    pid, WTERMSIG(status));
129	} else {
130		pjdlog_error("Worker process exited ungracefully (pid=%u, exitcode=%d).",
131		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1);
132	}
133}
134
135static void
136child_exit(void)
137{
138	struct hast_resource *res;
139	int status;
140	pid_t pid;
141
142	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
143		/* Find resource related to the process that just exited. */
144		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
145			if (pid == res->hr_workerpid)
146				break;
147		}
148		if (res == NULL) {
149			/*
150			 * This can happen when new connection arrives and we
151			 * cancel child responsible for the old one or if this
152			 * was hook which we executed.
153			 */
154			hook_check_one(pid, status);
155			continue;
156		}
157		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
158		    role2str(res->hr_role));
159		child_exit_log(pid, status);
160		proto_close(res->hr_ctrl);
161		res->hr_workerpid = 0;
162		if (res->hr_role == HAST_ROLE_PRIMARY) {
163			/*
164			 * Restart child process if it was killed by signal
165			 * or exited because of temporary problem.
166			 */
167			if (WIFSIGNALED(status) ||
168			    (WIFEXITED(status) &&
169			     WEXITSTATUS(status) == EX_TEMPFAIL)) {
170				sleep(1);
171				pjdlog_info("Restarting worker process.");
172				hastd_primary(res);
173			} else {
174				res->hr_role = HAST_ROLE_INIT;
175				pjdlog_info("Changing resource role back to %s.",
176				    role2str(res->hr_role));
177			}
178		}
179		pjdlog_prefix_set("%s", "");
180	}
181}
182
183static bool
184resource_needs_restart(const struct hast_resource *res0,
185    const struct hast_resource *res1)
186{
187
188	assert(strcmp(res0->hr_name, res1->hr_name) == 0);
189
190	if (strcmp(res0->hr_provname, res1->hr_provname) != 0)
191		return (true);
192	if (strcmp(res0->hr_localpath, res1->hr_localpath) != 0)
193		return (true);
194	if (res0->hr_role == HAST_ROLE_INIT ||
195	    res0->hr_role == HAST_ROLE_SECONDARY) {
196		if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
197			return (true);
198		if (res0->hr_replication != res1->hr_replication)
199			return (true);
200		if (res0->hr_timeout != res1->hr_timeout)
201			return (true);
202		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
203			return (true);
204	}
205	return (false);
206}
207
208static bool
209resource_needs_reload(const struct hast_resource *res0,
210    const struct hast_resource *res1)
211{
212
213	assert(strcmp(res0->hr_name, res1->hr_name) == 0);
214	assert(strcmp(res0->hr_provname, res1->hr_provname) == 0);
215	assert(strcmp(res0->hr_localpath, res1->hr_localpath) == 0);
216
217	if (res0->hr_role != HAST_ROLE_PRIMARY)
218		return (false);
219
220	if (strcmp(res0->hr_remoteaddr, res1->hr_remoteaddr) != 0)
221		return (true);
222	if (res0->hr_replication != res1->hr_replication)
223		return (true);
224	if (res0->hr_timeout != res1->hr_timeout)
225		return (true);
226	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
227		return (true);
228	return (false);
229}
230
231static void
232hastd_reload(void)
233{
234	struct hastd_config *newcfg;
235	struct hast_resource *nres, *cres, *tres;
236	uint8_t role;
237
238	pjdlog_info("Reloading configuration...");
239
240	newcfg = yy_config_parse(cfgpath, false);
241	if (newcfg == NULL)
242		goto failed;
243
244	/*
245	 * Check if control address has changed.
246	 */
247	if (strcmp(cfg->hc_controladdr, newcfg->hc_controladdr) != 0) {
248		if (proto_server(newcfg->hc_controladdr,
249		    &newcfg->hc_controlconn) < 0) {
250			pjdlog_errno(LOG_ERR,
251			    "Unable to listen on control address %s",
252			    newcfg->hc_controladdr);
253			goto failed;
254		}
255	}
256	/*
257	 * Check if listen address has changed.
258	 */
259	if (strcmp(cfg->hc_listenaddr, newcfg->hc_listenaddr) != 0) {
260		if (proto_server(newcfg->hc_listenaddr,
261		    &newcfg->hc_listenconn) < 0) {
262			pjdlog_errno(LOG_ERR, "Unable to listen on address %s",
263			    newcfg->hc_listenaddr);
264			goto failed;
265		}
266	}
267	/*
268	 * Only when both control and listen sockets are successfully
269	 * initialized switch them to new configuration.
270	 */
271	if (newcfg->hc_controlconn != NULL) {
272		pjdlog_info("Control socket changed from %s to %s.",
273		    cfg->hc_controladdr, newcfg->hc_controladdr);
274		proto_close(cfg->hc_controlconn);
275		cfg->hc_controlconn = newcfg->hc_controlconn;
276		newcfg->hc_controlconn = NULL;
277		strlcpy(cfg->hc_controladdr, newcfg->hc_controladdr,
278		    sizeof(cfg->hc_controladdr));
279	}
280	if (newcfg->hc_listenconn != NULL) {
281		pjdlog_info("Listen socket changed from %s to %s.",
282		    cfg->hc_listenaddr, newcfg->hc_listenaddr);
283		proto_close(cfg->hc_listenconn);
284		cfg->hc_listenconn = newcfg->hc_listenconn;
285		newcfg->hc_listenconn = NULL;
286		strlcpy(cfg->hc_listenaddr, newcfg->hc_listenaddr,
287		    sizeof(cfg->hc_listenaddr));
288	}
289
290	/*
291	 * Stop and remove resources that were removed from the configuration.
292	 */
293	TAILQ_FOREACH_SAFE(cres, &cfg->hc_resources, hr_next, tres) {
294		TAILQ_FOREACH(nres, &newcfg->hc_resources, hr_next) {
295			if (strcmp(cres->hr_name, nres->hr_name) == 0)
296				break;
297		}
298		if (nres == NULL) {
299			control_set_role(cres, HAST_ROLE_INIT);
300			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
301			pjdlog_info("Resource %s removed.", cres->hr_name);
302			free(cres);
303		}
304	}
305	/*
306	 * Move new resources to the current configuration.
307	 */
308	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
309		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
310			if (strcmp(cres->hr_name, nres->hr_name) == 0)
311				break;
312		}
313		if (cres == NULL) {
314			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
315			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
316			pjdlog_info("Resource %s added.", nres->hr_name);
317		}
318	}
319	/*
320	 * Deal with modified resources.
321	 * Depending on what has changed exactly we might want to perform
322	 * different actions.
323	 *
324	 * We do full resource restart in the following situations:
325	 * Resource role is INIT or SECONDARY.
326	 * Resource role is PRIMARY and path to local component or provider
327	 * name has changed.
328	 * In case of PRIMARY, the worker process will be killed and restarted,
329	 * which also means removing /dev/hast/<name> provider and
330	 * recreating it.
331	 *
332	 * We do just reload (send SIGHUP to worker process) if we act as
333	 * PRIMARY, but only remote address, replication mode and timeout
334	 * has changed. For those, there is no need to restart worker process.
335	 * If PRIMARY receives SIGHUP, it will reconnect if remote address or
336	 * replication mode has changed or simply set new timeout if only
337	 * timeout has changed.
338	 */
339	TAILQ_FOREACH_SAFE(nres, &newcfg->hc_resources, hr_next, tres) {
340		TAILQ_FOREACH(cres, &cfg->hc_resources, hr_next) {
341			if (strcmp(cres->hr_name, nres->hr_name) == 0)
342				break;
343		}
344		assert(cres != NULL);
345		if (resource_needs_restart(cres, nres)) {
346			pjdlog_info("Resource %s configuration was modified, restarting it.",
347			    cres->hr_name);
348			role = cres->hr_role;
349			control_set_role(cres, HAST_ROLE_INIT);
350			TAILQ_REMOVE(&cfg->hc_resources, cres, hr_next);
351			free(cres);
352			TAILQ_REMOVE(&newcfg->hc_resources, nres, hr_next);
353			TAILQ_INSERT_TAIL(&cfg->hc_resources, nres, hr_next);
354			control_set_role(nres, role);
355		} else if (resource_needs_reload(cres, nres)) {
356			pjdlog_info("Resource %s configuration was modified, reloading it.",
357			    cres->hr_name);
358			strlcpy(cres->hr_remoteaddr, nres->hr_remoteaddr,
359			    sizeof(cres->hr_remoteaddr));
360			cres->hr_replication = nres->hr_replication;
361			cres->hr_timeout = nres->hr_timeout;
362			if (cres->hr_workerpid != 0) {
363				if (kill(cres->hr_workerpid, SIGHUP) < 0) {
364					pjdlog_errno(LOG_WARNING,
365					    "Unable to send SIGHUP to worker process %u",
366					    (unsigned int)cres->hr_workerpid);
367				}
368			}
369		}
370	}
371
372	yy_config_free(newcfg);
373	pjdlog_info("Configuration reloaded successfully.");
374	return;
375failed:
376	if (newcfg != NULL) {
377		if (newcfg->hc_controlconn != NULL)
378			proto_close(newcfg->hc_controlconn);
379		if (newcfg->hc_listenconn != NULL)
380			proto_close(newcfg->hc_listenconn);
381		yy_config_free(newcfg);
382	}
383	pjdlog_warning("Configuration not reloaded.");
384}
385
386static void
387terminate_workers(void)
388{
389	struct hast_resource *res;
390
391	pjdlog_info("Termination signal received, exiting.");
392	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
393		if (res->hr_workerpid == 0)
394			continue;
395		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
396		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
397		if (kill(res->hr_workerpid, SIGTERM) == 0)
398			continue;
399		pjdlog_errno(LOG_WARNING,
400		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
401		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
402	}
403}
404
405static void
406listen_accept(void)
407{
408	struct hast_resource *res;
409	struct proto_conn *conn;
410	struct nv *nvin, *nvout, *nverr;
411	const char *resname;
412	const unsigned char *token;
413	char laddr[256], raddr[256];
414	size_t size;
415	pid_t pid;
416	int status;
417
418	proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
419	pjdlog_debug(1, "Accepting connection to %s.", laddr);
420
421	if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
422		pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
423		return;
424	}
425
426	proto_local_address(conn, laddr, sizeof(laddr));
427	proto_remote_address(conn, raddr, sizeof(raddr));
428	pjdlog_info("Connection from %s to %s.", raddr, laddr);
429
430	/* Error in setting timeout is not critical, but why should it fail? */
431	if (proto_timeout(conn, HAST_TIMEOUT) < 0)
432		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
433
434	nvin = nvout = nverr = NULL;
435
436	/*
437	 * Before receiving any data see if remote host have access to any
438	 * resource.
439	 */
440	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
441		if (proto_address_match(conn, res->hr_remoteaddr))
442			break;
443	}
444	if (res == NULL) {
445		pjdlog_error("Client %s isn't known.", raddr);
446		goto close;
447	}
448	/* Ok, remote host can access at least one resource. */
449
450	if (hast_proto_recv_hdr(conn, &nvin) < 0) {
451		pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
452		    raddr);
453		goto close;
454	}
455
456	resname = nv_get_string(nvin, "resource");
457	if (resname == NULL) {
458		pjdlog_error("No 'resource' field in the header received from %s.",
459		    raddr);
460		goto close;
461	}
462	pjdlog_debug(2, "%s: resource=%s", raddr, resname);
463	token = nv_get_uint8_array(nvin, &size, "token");
464	/*
465	 * NULL token means that this is first conection.
466	 */
467	if (token != NULL && size != sizeof(res->hr_token)) {
468		pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
469		    raddr, sizeof(res->hr_token), size);
470		goto close;
471	}
472
473	/*
474	 * From now on we want to send errors to the remote node.
475	 */
476	nverr = nv_alloc();
477
478	/* Find resource related to this connection. */
479	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
480		if (strcmp(resname, res->hr_name) == 0)
481			break;
482	}
483	/* Have we found the resource? */
484	if (res == NULL) {
485		pjdlog_error("No resource '%s' as requested by %s.",
486		    resname, raddr);
487		nv_add_stringf(nverr, "errmsg", "Resource not configured.");
488		goto fail;
489	}
490
491	/* Now that we know resource name setup log prefix. */
492	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
493
494	/* Does the remote host have access to this resource? */
495	if (!proto_address_match(conn, res->hr_remoteaddr)) {
496		pjdlog_error("Client %s has no access to the resource.", raddr);
497		nv_add_stringf(nverr, "errmsg", "No access to the resource.");
498		goto fail;
499	}
500	/* Is the resource marked as secondary? */
501	if (res->hr_role != HAST_ROLE_SECONDARY) {
502		pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
503		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
504		    raddr);
505		nv_add_stringf(nverr, "errmsg",
506		    "Remote node acts as %s for the resource and not as %s.",
507		    role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
508		goto fail;
509	}
510	/* Does token (if exists) match? */
511	if (token != NULL && memcmp(token, res->hr_token,
512	    sizeof(res->hr_token)) != 0) {
513		pjdlog_error("Token received from %s doesn't match.", raddr);
514		nv_add_stringf(nverr, "errmsg", "Token doesn't match.");
515		goto fail;
516	}
517	/*
518	 * If there is no token, but we have half-open connection
519	 * (only remotein) or full connection (worker process is running)
520	 * we have to cancel those and accept the new connection.
521	 */
522	if (token == NULL) {
523		assert(res->hr_remoteout == NULL);
524		pjdlog_debug(1, "Initial connection from %s.", raddr);
525		if (res->hr_workerpid != 0) {
526			assert(res->hr_remotein == NULL);
527			pjdlog_debug(1,
528			    "Worker process exists (pid=%u), stopping it.",
529			    (unsigned int)res->hr_workerpid);
530			/* Stop child process. */
531			if (kill(res->hr_workerpid, SIGINT) < 0) {
532				pjdlog_errno(LOG_ERR,
533				    "Unable to stop worker process (pid=%u)",
534				    (unsigned int)res->hr_workerpid);
535				/*
536				 * Other than logging the problem we
537				 * ignore it - nothing smart to do.
538				 */
539			}
540			/* Wait for it to exit. */
541			else if ((pid = waitpid(res->hr_workerpid,
542			    &status, 0)) != res->hr_workerpid) {
543				/* We can only log the problem. */
544				pjdlog_errno(LOG_ERR,
545				    "Waiting for worker process (pid=%u) failed",
546				    (unsigned int)res->hr_workerpid);
547			} else {
548				child_exit_log(res->hr_workerpid, status);
549			}
550			res->hr_workerpid = 0;
551		} else if (res->hr_remotein != NULL) {
552			char oaddr[256];
553
554			proto_remote_address(conn, oaddr, sizeof(oaddr));
555			pjdlog_debug(1,
556			    "Canceling half-open connection from %s on connection from %s.",
557			    oaddr, raddr);
558			proto_close(res->hr_remotein);
559			res->hr_remotein = NULL;
560		}
561	}
562
563	/*
564	 * Checks and cleanups are done.
565	 */
566
567	if (token == NULL) {
568		arc4random_buf(res->hr_token, sizeof(res->hr_token));
569		nvout = nv_alloc();
570		nv_add_uint8_array(nvout, res->hr_token,
571		    sizeof(res->hr_token), "token");
572		if (nv_error(nvout) != 0) {
573			pjdlog_common(LOG_ERR, 0, nv_error(nvout),
574			    "Unable to prepare return header for %s", raddr);
575			nv_add_stringf(nverr, "errmsg",
576			    "Remote node was unable to prepare return header: %s.",
577			    strerror(nv_error(nvout)));
578			goto fail;
579		}
580		if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
581			int error = errno;
582
583			pjdlog_errno(LOG_ERR, "Unable to send response to %s",
584			    raddr);
585			nv_add_stringf(nverr, "errmsg",
586			    "Remote node was unable to send response: %s.",
587			    strerror(error));
588			goto fail;
589		}
590		res->hr_remotein = conn;
591		pjdlog_debug(1, "Incoming connection from %s configured.",
592		    raddr);
593	} else {
594		res->hr_remoteout = conn;
595		pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
596		hastd_secondary(res, nvin);
597	}
598	nv_free(nvin);
599	nv_free(nvout);
600	nv_free(nverr);
601	pjdlog_prefix_set("%s", "");
602	return;
603fail:
604	if (nv_error(nverr) != 0) {
605		pjdlog_common(LOG_ERR, 0, nv_error(nverr),
606		    "Unable to prepare error header for %s", raddr);
607		goto close;
608	}
609	if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
610		pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
611		goto close;
612	}
613close:
614	if (nvin != NULL)
615		nv_free(nvin);
616	if (nvout != NULL)
617		nv_free(nvout);
618	if (nverr != NULL)
619		nv_free(nverr);
620	proto_close(conn);
621	pjdlog_prefix_set("%s", "");
622}
623
624static void
625main_loop(void)
626{
627	fd_set rfds, wfds;
628	int cfd, lfd, maxfd, ret;
629	struct timeval timeout;
630
631	timeout.tv_sec = REPORT_INTERVAL;
632	timeout.tv_usec = 0;
633
634	for (;;) {
635		if (sigexit_received) {
636			sigexit_received = false;
637			terminate_workers();
638			exit(EX_OK);
639		}
640		if (sigchld_received) {
641			sigchld_received = false;
642			child_exit();
643		}
644		if (sighup_received) {
645			sighup_received = false;
646			hastd_reload();
647		}
648
649		cfd = proto_descriptor(cfg->hc_controlconn);
650		lfd = proto_descriptor(cfg->hc_listenconn);
651		maxfd = cfd > lfd ? cfd : lfd;
652
653		/* Setup descriptors for select(2). */
654		FD_ZERO(&rfds);
655		FD_SET(cfd, &rfds);
656		FD_SET(lfd, &rfds);
657		FD_ZERO(&wfds);
658		FD_SET(cfd, &wfds);
659		FD_SET(lfd, &wfds);
660
661		ret = select(maxfd + 1, &rfds, &wfds, NULL, &timeout);
662		if (ret == 0)
663			hook_check(false);
664		else if (ret == -1) {
665			if (errno == EINTR)
666				continue;
667			KEEP_ERRNO((void)pidfile_remove(pfh));
668			pjdlog_exit(EX_OSERR, "select() failed");
669		}
670
671		if (FD_ISSET(cfd, &rfds) || FD_ISSET(cfd, &wfds))
672			control_handle(cfg);
673		if (FD_ISSET(lfd, &rfds) || FD_ISSET(lfd, &wfds))
674			listen_accept();
675	}
676}
677
678int
679main(int argc, char *argv[])
680{
681	const char *pidfile;
682	pid_t otherpid;
683	bool foreground;
684	int debuglevel;
685
686	g_gate_load();
687
688	foreground = false;
689	debuglevel = 0;
690	pidfile = HASTD_PIDFILE;
691
692	for (;;) {
693		int ch;
694
695		ch = getopt(argc, argv, "c:dFhP:");
696		if (ch == -1)
697			break;
698		switch (ch) {
699		case 'c':
700			cfgpath = optarg;
701			break;
702		case 'd':
703			debuglevel++;
704			break;
705		case 'F':
706			foreground = true;
707			break;
708		case 'P':
709			pidfile = optarg;
710			break;
711		case 'h':
712		default:
713			usage();
714		}
715	}
716	argc -= optind;
717	argv += optind;
718
719	pjdlog_debug_set(debuglevel);
720
721	pfh = pidfile_open(pidfile, 0600, &otherpid);
722	if (pfh == NULL) {
723		if (errno == EEXIST) {
724			pjdlog_exitx(EX_TEMPFAIL,
725			    "Another hastd is already running, pid: %jd.",
726			    (intmax_t)otherpid);
727		}
728		/* If we cannot create pidfile from other reasons, only warn. */
729		pjdlog_errno(LOG_WARNING, "Unable to open or create pidfile");
730	}
731
732	cfg = yy_config_parse(cfgpath, true);
733	assert(cfg != NULL);
734
735	signal(SIGINT, sighandler);
736	signal(SIGTERM, sighandler);
737	signal(SIGHUP, sighandler);
738	signal(SIGCHLD, sighandler);
739
740	/* Listen on control address. */
741	if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
742		KEEP_ERRNO((void)pidfile_remove(pfh));
743		pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
744		    cfg->hc_controladdr);
745	}
746	/* Listen for remote connections. */
747	if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
748		KEEP_ERRNO((void)pidfile_remove(pfh));
749		pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
750		    cfg->hc_listenaddr);
751	}
752
753	if (!foreground) {
754		if (daemon(0, 0) < 0) {
755			KEEP_ERRNO((void)pidfile_remove(pfh));
756			pjdlog_exit(EX_OSERR, "Unable to daemonize");
757		}
758
759		/* Start logging to syslog. */
760		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
761
762		/* Write PID to a file. */
763		if (pidfile_write(pfh) < 0) {
764			pjdlog_errno(LOG_WARNING,
765			    "Unable to write PID to a file");
766		}
767	}
768
769	hook_init();
770
771	main_loop();
772
773	exit(0);
774}
775