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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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);
}
}
|