summary refs log tree commit diff
path: root/calico.1
blob: 4d52a10ebaa8c76acf4be7bdbc289fd1f649b7ce (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
.Dd November 6, 2019
.Dt CALICO 1
.Os
.
.Sh NAME
.Nm calico
.Nd dispatches cat
.
.Sh SYNOPSIS
.Nm
.Op Fl H Ar host
.Op Fl P Ar port
.Op Fl t Ar timeout
.Ar directory
.
.Sh DESCRIPTION
The
.Nm
daemon
dispatches incoming TLS connections
to instances of
.Xr pounce 1
by Server Name Indication (SNI).
Instances of
.Xr pounce 1
should be configured with
.Fl U
to bind to UNIX-domain sockets
named by the host they wish to accept connections for
in the directory passed to
.Nm .
.
.Pp
The arguments are as follows:
.Bl -tag -width Ds
.It Fl H Ar host
Bind to
.Ar host .
The default host is localhost.
.It Fl P Ar port
Bind to
.Ar port .
The default port is 6697.
.It Fl t Ar timeout
Set the timeout in milliseconds
after which a connection will be closed
if it has not sent the ClientHello message.
The default timeout is 1000 milliseconds.
.It Ar directory
The path to the directory containing
.Xr pounce 1
UNIX-domain sockets.
.El
.
.Ss Service Configuration
Add the following to
.Pa /etc/rc.conf
to enable the
.Nm
daemon:
.Bd -literal -offset indent
calico_enable="YES"
.Ed
.
.Pp
The default socket directory is
.Pa /var/run/calico .
It can be changed by setting
.Va calico_path .
The
.Xr pounce 1
service can be configured
to listen in this directory
with the following:
.Bd -literal -offset indent
pounce_flags="-U /var/run/calico"
.Ed
.
.Pp
The
.Nm
and
.Xr pounce 1
services can be started and stopped
completely independently of each other.
.
.Sh EXAMPLES
.Bd -literal -offset indent
pounce -U sockets/foo.example.org foo.conf
pounce -U sockets/bar.example.org bar.conf
calico -H example.org sockets/
.Ed
.
.Sh SEE ALSO
.Xr pounce 1
.
.Sh STANDARDS
The
.Nm
daemon implements the following:
.
.Bl -item
.It
.Rs
.%A E. Rescorla
.%Q Mozilla
.%T The Transport Layer Security (TLS) Protocol Version 1.3
.%I IETF
.%N RFC 8446
.%D August 2018
.%U https://tools.ietf.org/html/rfc8446
.Re
.
.It
.Rs
.%A D. Eastlake 3rd
.%Q Huawei
.%T Transport Layer Security (TLS) Extensions: Extension Definitions
.%I IETF
.%N RFC 6066
.%D January 2011
.%U https://tools.ietf.org/html/rfc6066
.Re
.El
.
.Sh AUTHORS
.An June Bug Aq Mt june@causal.agency
.
.Sh BUGS
Send mail to
.Aq Mt june@causal.agency
or join
.Li #ascii.town
on
.Li chat.freenode.net .
='#n372'>372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
/* Copyright (C) 2020  C. McEnroe <june@causal.agency>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <grp.h>
#include <paths.h>
#include <poll.h>
#include <pwd.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sysexits.h>
#include <syslog.h>
#include <unistd.h>

#include "daemon.h"

#define WS " \t"

struct Set256 stopExits;
struct timespec restartInterval = { .tv_sec = 1 };
struct timespec resetInterval = { .tv_sec = 15 * 60 };

static volatile sig_atomic_t signals[NSIG];
static void signalHandler(int signal) {
	signals[signal] = 1;
}

static int parseConfig(const char *path) {
	int ret = -1;
	size_t cap = 0;
	char *buf = NULL;

	FILE *file = fopen(path, "r");
	if (!file) {
		syslog(LOG_WARNING, "%s: %m", path);
		goto err;
	}

	prependClear();

	int line = 1;
	for (ssize_t len; 0 <= (len = getline(&buf, &cap, file)); ++line) {
		if (buf[len - 1] == '\n') buf[len - 1] = '\0';

		char *ptr = &buf[strspn(buf, WS)];
		if (!ptr[0] || ptr[0] == '#') {
			continue;
		} else if (ptr[0] == '%') {
			int error = prependAdd(&ptr[1]);
			if (error) {
				syslog(LOG_WARNING, "cannot add prepend command: %m");
				goto err;
			}
		} else {
			char *name = strsep(&ptr, WS);
			if (!ptr) {
				syslog(
					LOG_WARNING, "%s:%d: no command line for service %s",
					path, line, name
				);
				goto err;
			}
			int error = serviceAdd(name, ptr);
			if (error) {
				syslog(LOG_WARNING, "cannot add service: %m");
				goto err;
			}
		}
	}
	if (ferror(file)) {
		syslog(LOG_WARNING, "%s: %m", path);
		goto err;
	}
	ret = 0;

err:
	free(buf);
	if (file) fclose(file);
	return ret;
}

typedef void Action(struct Service *service);
static void parseControl(char *command) {
	char *action = strsep(&command, WS);
	if (!command) {
		syslog(LOG_NOTICE, "no service names for %s", action);
		return;
	}

	bool drop = false;
	Action *fn = NULL;
	int signal = 0;
	if (!strcmp(action, "start")) {
		fn = serviceStart;
	} else if (!strcmp(action, "stop")) {
		fn = serviceStop;
	} else if (!strcmp(action, "restart")) {
		fn = serviceRestart;
	} else if (!strcmp(action, "status")) {
		fn = serviceStatus;
	} else if (!strcmp(action, "drop")) {
		drop = true;
	} else {
		for (int i = 1; i < NSIG; ++i) {
			if (strcasecmp(action, sys_signame[i])) continue;
			signal = i;
			break;
		}
	}
	if (!drop && !fn && !signal) {
		syslog(LOG_NOTICE, "unknown action or signal %s", action);
		return;
	}

	while (command) {
		bool found = false;
		char *pattern = strsep(&command, WS);
		for (size_t i = services.len - 1; i < services.len; --i) {
			struct Service *service = &services.ptr[i];
			if (fnmatch(pattern, service->name, 0)) continue;
			if (drop) {
				serviceDrop(i);
			} else if (signal) {
				serviceSignal(service, signal);
			} else {
				fn(service);
			}
			found = true;
		}
		if (!found) syslog(LOG_NOTICE, "no services matching %s", pattern);
	}
}

static void parseExits(char *list) {
	setClear(&stopExits);
	while (*list) {
		byte exit = strtoul(list, &list, 10);
		if (*list) {
			if (*list != ',') errx(EX_USAGE, "invalid exit status %s", list);
			list++;
		}
		setAdd(&stopExits, exit);
	}
}

static void parseInterval(struct timespec *interval, const char *millis) {
	unsigned long ms = strtoul(millis, NULL, 10);
	interval->tv_sec = ms / 1000;
	interval->tv_nsec = 1000000 * (ms % 1000);
}

static void setTitle(void) {
	size_t started = 0;
	for (size_t i = 0; i < services.len; ++i) {
		if (services.ptr[i].state == Start) started++;
	}
	setproctitle("%zu/%zu services", started, services.len);
}

int main(int argc, char *argv[]) {
	int error;
	openlog(getprogname(), LOG_NDELAY | LOG_PID | LOG_PERROR, LOG_DAEMON);

	bool daemonize = true;
	setAdd(&stopExits, EX_USAGE);
	setAdd(&stopExits, EX_DATAERR);
	setAdd(&stopExits, EX_NOINPUT);
	setAdd(&stopExits, EX_OSFILE);
	setAdd(&stopExits, EX_CANTCREAT);

	const char *pidPath = NULL;
	const char *configPath = ETCDIR "/catsit.conf";
	const char *fifoPath = RUNDIR "/catsitd.pipe";

	const char *userName = NULL;
	const char *groupName = NULL;

	for (int opt; 0 < (opt = getopt(argc, argv, "C:c:df:g:p:r:s:t:u:"));) {
		switch (opt) {
			break; case 'C': serviceDir = optarg;
			break; case 'c': fifoPath = optarg;
			break; case 'd': daemonize = false;
			break; case 'f': configPath = optarg;
			break; case 'g': groupName = optarg;
			break; case 'p': pidPath = optarg;
			break; case 'r': parseInterval(&resetInterval, optarg);
			break; case 's': parseExits(optarg);
			break; case 't': parseInterval(&restartInterval, optarg);
			break; case 'u': userName = optarg;
			break; default:  return EX_USAGE;
		}
	}

#ifdef __OpenBSD__
	struct {
		const char *path;
		const char *mode;
	} paths[] = {
		{ fifoPath, "crw" },
		{ configPath, "r" },
		{ "/", "r" },
		{ "/dev/null", "rw" },
		{ serviceDir, "r" },
		{ _PATH_BSHELL, "x" },
		{ pidPath, "cw" },
		{ NULL, NULL },
	};
	for (size_t i = 0; paths[i].path; ++i) {
		error = unveil(paths[i].path, paths[i].mode);
		if (error) err(EX_CANTCREAT, "%s", paths[i].path);
	}
	error = pledge(
		"stdio cpath dpath rpath wpath flock getpw proc exec id", NULL
	);
	if (error) err(EX_OSERR, "pledge");
#endif
	
	error = access(serviceDir, X_OK);
	if (error) err(EX_NOINPUT, "%s", serviceDir);

	errno = 0;
	struct passwd *user = (userName ? getpwnam(userName) : getpwuid(getuid()));
	if (errno) err(EX_OSFILE, "getpwnam");
	if (!user) errx(EX_USAGE, "no such user %s", userName);
	serviceUID = user->pw_uid;

	if (groupName) {
		errno = 0;
		struct group *group = getgrnam(groupName);
		if (errno) err(EX_OSFILE, "getgrnam");
		if (!group) errx(EX_USAGE, "no such group %s", groupName);
		serviceGID = group->gr_gid;
	} else {
		serviceGID = user->pw_gid;
	}

	int len = asprintf(&serviceEnviron[USER], "USER=%s", user->pw_name);
	if (len < 0) err(EX_OSERR, "asprintf");

	len = asprintf(&serviceEnviron[HOME], "HOME=%s", user->pw_dir);
	if (len < 0) err(EX_OSERR, "asprintf");

	int pidFile = -1;
	if (pidPath) {
		pidFile = open(pidPath, O_WRONLY | O_CREAT | O_CLOEXEC, 0600);
		if (pidFile < 0) err(EX_CANTCREAT, "%s", pidPath);

		error = flock(pidFile, LOCK_EX | LOCK_NB);
		if (error && errno != EWOULDBLOCK) err(EX_IOERR, "%s", pidPath);
		if (error) errx(EX_CANTCREAT, "%s: file is locked", pidPath);

		error = ftruncate(pidFile, 0);
		if (error) err(EX_IOERR, "%s", pidPath);
	}

	// We can't lock a named pipe, so just warn if it already exists.
	error = mkfifo(fifoPath, 0600);
	if (error) {
		if (errno != EEXIST) err(EX_CANTCREAT, "%s", fifoPath);
		warn("%s", fifoPath);
	}

	struct Line fifoLine = {0};
	int fifo = open(fifoPath, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
	if (fifo < 0) err(EX_CANTCREAT, "%s", fifoPath);

	// XXX: Keep a writer open so the reader never gets EOF.
	int writer = open(fifoPath, O_WRONLY | O_NONBLOCK | O_CLOEXEC);
	if (writer < 0) err(EX_CANTCREAT, "%s", fifoPath);

	error = parseConfig(configPath);
	if (error) return EX_DATAERR;

	if (daemonize) {
		error = daemon(0, 0);
		if (error) {
			syslog(LOG_WARNING, "daemon: %m");
			return EX_OSERR;
		}
	}
	if (pidPath) {
		int len = dprintf(pidFile, "%ju", (uintmax_t)getpid());
		if (len < 0) syslog(LOG_WARNING, "%s: %m", pidPath);
	}

#ifdef __OpenBSD__
	error = pledge("stdio cpath rpath proc exec id", NULL);
	if (error) err(EX_OSERR, "pledge");
#endif

	signal(SIGHUP, signalHandler);
	signal(SIGINT, signalHandler);
	signal(SIGTERM, signalHandler);
	signal(SIGCHLD, signalHandler);
	signal(SIGINFO, signalHandler);

	for (size_t i = 0; i < services.len; ++i) {
		serviceStart(&services.ptr[i]);
	}
	setTitle();

	sigset_t mask;
	sigemptyset(&mask);
	for (;;) {
		if (signals[SIGCHLD]) {
			int status;
			pid_t pid;
			while (0 < (pid = waitpid(-1, &status, WNOHANG))) {
				serviceReap(pid, status);
			}
			if (pid < 0 && errno != ECHILD) syslog(LOG_WARNING, "waitpid: %m");
			setTitle();
			signals[SIGCHLD] = 0;
		}

		if (signals[SIGINT] || signals[SIGTERM]) {
			break;
		}
		if (signals[SIGHUP]) {
			parseConfig(configPath);
			setTitle();
			signals[SIGHUP] = 0;
		}
		if (signals[SIGINFO]) {
			char command[] = "status *";
			parseControl(command);
			signals[SIGINFO] = 0;
		}

		struct pollfd fds[1 + 2 * services.len];
		fds[0].fd = fifo;
		fds[0].events = POLLIN;

		struct timespec deadline = {0};
		for (size_t i = 0; i < services.len; ++i) {
			struct Service *service = &services.ptr[i];

			fds[1 + 2 * i].fd = service->outPipe[0];
			fds[2 + 2 * i].fd = service->errPipe[0];
			fds[1 + 2 * i].events = POLLIN;
			fds[2 + 2 * i].events = POLLIN;

			if (service->intent != Start) continue;
			if (service->state == Start) continue;
			if (
				!timespecisset(&deadline) ||
				timespeccmp(&service->restartDeadline, &deadline, <)
			) deadline = service->restartDeadline;
		}

		struct timespec now = {0};
		struct timespec timeout = {0};
		if (timespecisset(&deadline)) {
			clock_gettime(CLOCK_MONOTONIC, &now);
			timespecsub(&deadline, &now, &timeout);
		}
		if (timeout.tv_sec < 0 || timeout.tv_nsec < 0) {
			timespecclear(&timeout);
		}

		int nfds = ppoll(
			fds, 1 + 2 * services.len,
			(timespecisset(&deadline) ? &timeout : NULL),
			&mask
		);
		if (nfds < 0 && errno != EINTR) {
			syslog(LOG_WARNING, "ppoll: %m");
			continue;
		}

		if (nfds > 0 && fds[0].revents) {
			const char *line;
			while (NULL != (line = lineRead(&fifoLine, fifo))) {
				char buf[LineCap];
				snprintf(buf, sizeof(buf), "%s", line);
				parseControl(buf);
			}
			if (errno != EAGAIN) syslog(LOG_WARNING, "read: %m");
			setTitle();
		}

		if (nfds > 0) {
			for (size_t i = 0; i < services.len; ++i) {
				if (fds[1 + 2 * i].revents || fds[2 + 2 * i].revents) {
					serviceRead(&services.ptr[i]);
				}
			}
		}

		if (timespecisset(&deadline)) {
			clock_gettime(CLOCK_MONOTONIC, &now);
			for (size_t i = 0; i < services.len; ++i) {
				struct Service *service = &services.ptr[i];
				if (service->intent != Start) continue;
				if (service->state == Start) continue;
				if (timespeccmp(&service->restartDeadline, &now, <=)) {
					serviceStart(service);
				}
			}
			setTitle();
		}
	}

	close(fifo);
	unlink(fifoPath);

	setproctitle("stopping");
	size_t count = 0;
	for (size_t i = 0; i < services.len; ++i) {
		serviceStop(&services.ptr[i]);
		if (services.ptr[i].state == Start) count++;
	}
	while (count--) {
		int status;
		pid_t pid = wait(&status);
		if (pid < 0) {
			syslog(LOG_WARNING, "wait: %m");
			continue;
		}
		serviceReap(pid, status);
	}
	
	if (pidPath) {
		close(pidFile);
		unlink(pidPath);
	}
}