2 * Copyright (c) 2009-2010 The FreeBSD Foundation
5 * This software was developed by Pawel Jakub Dawidek under sponsorship from
6 * the FreeBSD Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
34 #include <sys/linker.h>
35 #include <sys/module.h>
50 #include <activemap.h>
55 #include "hast_proto.h"
59 /* Path to configuration file. */
60 static const char *cfgpath = HAST_CONFIG;
61 /* Hastd configuration. */
62 static struct hastd_config *cfg;
63 /* Was SIGCHLD signal received? */
64 static bool sigchld_received = false;
65 /* Was SIGHUP signal received? */
66 static bool sighup_received = false;
67 /* Was SIGINT or SIGTERM signal received? */
68 bool sigexit_received = false;
69 /* PID file handle. */
76 errx(EX_USAGE, "[-dFh] [-c config] [-P pidfile]");
85 sigchld_received = true;
88 sighup_received = true;
91 assert(!"invalid condition");
99 if (modfind("g_gate") == -1) {
100 /* Not present in kernel, try loading it. */
101 if (kldload("geom_gate") == -1 || modfind("g_gate") == -1) {
102 if (errno != EEXIST) {
103 pjdlog_exit(EX_OSERR,
104 "Unable to load geom_gate module");
113 struct hast_resource *res;
117 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
118 /* Find resource related to the process that just exited. */
119 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
120 if (pid == res->hr_workerpid)
125 * This can happen when new connection arrives and we
126 * cancel child responsible for the old one.
130 pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
131 role2str(res->hr_role));
132 if (WEXITSTATUS(status) == 0) {
134 "Worker process exited gracefully (pid=%u).",
137 pjdlog_error("Worker process failed (pid=%u, status=%d).",
138 (unsigned int)pid, WEXITSTATUS(status));
140 res->hr_workerpid = 0;
141 if (res->hr_role == HAST_ROLE_PRIMARY) {
143 pjdlog_info("Restarting worker process.");
146 pjdlog_prefix_set("%s", "");
155 pjdlog_warning("Configuration reload is not implemented.");
161 struct hast_resource *res;
162 struct proto_conn *conn;
163 struct nv *nvin, *nvout, *nverr;
165 const unsigned char *token;
166 char laddr[256], raddr[256];
171 proto_local_address(cfg->hc_listenconn, laddr, sizeof(laddr));
172 pjdlog_debug(1, "Accepting connection to %s.", laddr);
174 if (proto_accept(cfg->hc_listenconn, &conn) < 0) {
175 pjdlog_errno(LOG_ERR, "Unable to accept connection %s", laddr);
179 proto_local_address(conn, laddr, sizeof(laddr));
180 proto_remote_address(conn, raddr, sizeof(raddr));
181 pjdlog_info("Connection from %s to %s.", laddr, raddr);
183 nvin = nvout = nverr = NULL;
186 * Before receiving any data see if remote host have access to any
189 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
190 if (proto_address_match(conn, res->hr_remoteaddr))
194 pjdlog_error("Client %s isn't known.", raddr);
197 /* Ok, remote host can access at least one resource. */
199 if (hast_proto_recv_hdr(conn, &nvin) < 0) {
200 pjdlog_errno(LOG_ERR, "Unable to receive header from %s",
205 resname = nv_get_string(nvin, "resource");
206 if (resname == NULL) {
207 pjdlog_error("No 'resource' field in the header received from %s.",
211 pjdlog_debug(2, "%s: resource=%s", raddr, resname);
212 token = nv_get_uint8_array(nvin, &size, "token");
214 * NULL token means that this is first conection.
216 if (token != NULL && size != sizeof(res->hr_token)) {
217 pjdlog_error("Received token of invalid size from %s (expected %zu, got %zu).",
218 raddr, sizeof(res->hr_token), size);
223 * From now on we want to send errors to the remote node.
227 /* Find resource related to this connection. */
228 TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
229 if (strcmp(resname, res->hr_name) == 0)
232 /* Have we found the resource? */
234 pjdlog_error("No resource '%s' as requested by %s.",
236 nv_add_stringf(nverr, "errmsg", "Resource not configured.");
240 /* Now that we know resource name setup log prefix. */
241 pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
243 /* Does the remote host have access to this resource? */
244 if (!proto_address_match(conn, res->hr_remoteaddr)) {
245 pjdlog_error("Client %s has no access to the resource.", raddr);
246 nv_add_stringf(nverr, "errmsg", "No access to the resource.");
249 /* Is the resource marked as secondary? */
250 if (res->hr_role != HAST_ROLE_SECONDARY) {
251 pjdlog_error("We act as %s for the resource and not as %s as requested by %s.",
252 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY),
254 nv_add_stringf(nverr, "errmsg",
255 "Remote node acts as %s for the resource and not as %s.",
256 role2str(res->hr_role), role2str(HAST_ROLE_SECONDARY));
259 /* Does token (if exists) match? */
260 if (token != NULL && memcmp(token, res->hr_token,
261 sizeof(res->hr_token)) != 0) {
262 pjdlog_error("Token received from %s doesn't match.", raddr);
263 nv_add_stringf(nverr, "errmsg", "Toke doesn't match.");
267 * If there is no token, but we have half-open connection
268 * (only remotein) or full connection (worker process is running)
269 * we have to cancel those and accept the new connection.
272 assert(res->hr_remoteout == NULL);
273 pjdlog_debug(1, "Initial connection from %s.", raddr);
274 if (res->hr_workerpid != 0) {
275 assert(res->hr_remotein == NULL);
277 "Worker process exists (pid=%u), stopping it.",
278 (unsigned int)res->hr_workerpid);
279 /* Stop child process. */
280 if (kill(res->hr_workerpid, SIGINT) < 0) {
281 pjdlog_errno(LOG_ERR,
282 "Unable to stop worker process (pid=%u)",
283 (unsigned int)res->hr_workerpid);
285 * Other than logging the problem we
286 * ignore it - nothing smart to do.
289 /* Wait for it to exit. */
290 else if ((pid = waitpid(res->hr_workerpid,
291 &status, 0)) != res->hr_workerpid) {
292 pjdlog_errno(LOG_ERR,
293 "Waiting for worker process (pid=%u) failed",
294 (unsigned int)res->hr_workerpid);
296 } else if (status != 0) {
297 pjdlog_error("Worker process (pid=%u) exited ungracefully: status=%d.",
298 (unsigned int)res->hr_workerpid, status);
302 "Worker process (pid=%u) exited gracefully.",
303 (unsigned int)res->hr_workerpid);
305 res->hr_workerpid = 0;
306 } else if (res->hr_remotein != NULL) {
309 proto_remote_address(conn, oaddr, sizeof(oaddr));
311 "Canceling half-open connection from %s on connection from %s.",
313 proto_close(res->hr_remotein);
314 res->hr_remotein = NULL;
319 * Checks and cleanups are done.
323 arc4random_buf(res->hr_token, sizeof(res->hr_token));
325 nv_add_uint8_array(nvout, res->hr_token,
326 sizeof(res->hr_token), "token");
327 if (nv_error(nvout) != 0) {
328 pjdlog_common(LOG_ERR, 0, nv_error(nvout),
329 "Unable to prepare return header for %s", raddr);
330 nv_add_stringf(nverr, "errmsg",
331 "Remote node was unable to prepare return header: %s.",
332 strerror(nv_error(nvout)));
335 if (hast_proto_send(NULL, conn, nvout, NULL, 0) < 0) {
338 pjdlog_errno(LOG_ERR, "Unable to send response to %s",
340 nv_add_stringf(nverr, "errmsg",
341 "Remote node was unable to send response: %s.",
345 res->hr_remotein = conn;
346 pjdlog_debug(1, "Incoming connection from %s configured.",
349 res->hr_remoteout = conn;
350 pjdlog_debug(1, "Outgoing connection to %s configured.", raddr);
351 hastd_secondary(res, nvin);
356 pjdlog_prefix_set("%s", "");
359 if (nv_error(nverr) != 0) {
360 pjdlog_common(LOG_ERR, 0, nv_error(nverr),
361 "Unable to prepare error header for %s", raddr);
364 if (hast_proto_send(NULL, conn, nverr, NULL, 0) < 0) {
365 pjdlog_errno(LOG_ERR, "Unable to send error to %s", raddr);
376 pjdlog_prefix_set("%s", "");
386 if (sigchld_received) {
387 sigchld_received = false;
390 if (sighup_received) {
391 sighup_received = false;
399 /* Setup descriptors for select(2). */
400 #define SETUP_FD(conn) do { \
401 fd = proto_descriptor(conn); \
403 maxfd = fd > maxfd ? fd : maxfd; \
408 SETUP_FD(cfg->hc_controlconn);
409 SETUP_FD(cfg->hc_listenconn);
412 ret = select(maxfd + 1, &rfds, &wfds, NULL, NULL);
416 KEEP_ERRNO((void)pidfile_remove(pfh));
417 pjdlog_exit(EX_OSERR, "select() failed");
420 #define ISSET_FD(conn) \
421 (FD_ISSET((fd = proto_descriptor(conn)), &rfds) || FD_ISSET(fd, &wfds))
422 if (ISSET_FD(cfg->hc_controlconn))
424 if (ISSET_FD(cfg->hc_listenconn))
431 main(int argc, char *argv[])
442 pidfile = HASTD_PIDFILE;
447 ch = getopt(argc, argv, "c:dFhP:");
471 pjdlog_debug_set(debuglevel);
473 pfh = pidfile_open(pidfile, 0600, &otherpid);
475 if (errno == EEXIST) {
476 pjdlog_exitx(EX_TEMPFAIL,
477 "Another hastd is already running, pid: %jd.",
480 /* If we cannot create pidfile from other reasons, only warn. */
481 pjdlog_errno(LOG_WARNING, "Cannot open or create pidfile");
484 cfg = yy_config_parse(cfgpath);
487 signal(SIGHUP, sighandler);
488 signal(SIGCHLD, sighandler);
490 /* Listen on control address. */
491 if (proto_server(cfg->hc_controladdr, &cfg->hc_controlconn) < 0) {
492 KEEP_ERRNO((void)pidfile_remove(pfh));
493 pjdlog_exit(EX_OSERR, "Unable to listen on control address %s",
494 cfg->hc_controladdr);
496 /* Listen for remote connections. */
497 if (proto_server(cfg->hc_listenaddr, &cfg->hc_listenconn) < 0) {
498 KEEP_ERRNO((void)pidfile_remove(pfh));
499 pjdlog_exit(EX_OSERR, "Unable to listen on address %s",
504 if (daemon(0, 0) < 0) {
505 KEEP_ERRNO((void)pidfile_remove(pfh));
506 pjdlog_exit(EX_OSERR, "Unable to daemonize");
509 /* Start logging to syslog. */
510 pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
512 /* Write PID to a file. */
513 if (pidfile_write(pfh) < 0) {
514 pjdlog_errno(LOG_WARNING,
515 "Unable to write PID to a file");