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