aboutsummaryrefslogtreecommitdiff
path: root/src/stevedore.c
blob: ac9568911e579a7b35130d0a85b4f0b7d5ec6472 (plain)
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/* This file is part of tallyman
Copyright (C) 2018 Sergey Poznyakoff
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
*/
#include "stevedore.h"
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/queue.h>
#include <sys/wait.h>
#include <getopt.h>
#include <netdb.h>
#include <errno.h>
#include <syslog.h>
#include <signal.h>
#include <time.h>
#include <pthread.h>
#define MHD_PLATFORM_H
#include <microhttpd.h>
#include "defs.h"

int debug;
char *progname;

enum {
	OPT_CONFIG_HELP = 256
};
	

struct option longopts[] = {
	{ "help",        no_argument,       0, '?' },
	{ "config-file", required_argument, 0, 'f' },
	{ "config-help", no_argument,       0, OPT_CONFIG_HELP },
	{ "debug",       no_argument,       0, 'd' },
	{ "foreground",  no_argument,       0, 'F' },
	{ "single",      no_argument,       0, 's' },
	{ "version",     no_argument,       0, 'V' },
	{ NULL }
};
static char shortopts[] = "?df:FsV";

void
help(void)
{
	printf("usage: %s [OPTIONS]\n", progname);
	printf("\n");
        printf("OPTIONS are:\n\n");
	printf("   -f, --config-file=FILE   read configuration from FILE\n");
	printf("                            (default %s)\n", DEFAULT_CONFIG_FILE_NAME);
	printf("       --config-help        describe configuration file syntax and variables\n");
	printf("   -F, --foreground         don't fork; remain in foreground\n");
	printf("   -s, --single             don't start sentinel process\n");
	printf("   -d, --debug              increase debug verbosity\n");
	printf("   -V, --version            display version number and license\n");
	printf("   -?, --help               display this help text\n\n");
}

#include "gpl3.h"
void
version(void)
{
	printf("stevedore (%s) %s\n", PACKAGE_TARNAME, PACKAGE_VERSION);
	printf("%s\n", license);
}	

static void
logger_syslog(int prio, int ec, char const *pfx, char const *msg)
{
	if (ec) {
		int save_errno = errno;
		errno = ec;
		if (pfx)
			syslog(prio, "%s: %s: %m", pfx, msg);
		else
			syslog(prio, "%s: %m", msg);
		errno = save_errno;
	} else if (pfx)
		syslog(prio, "%s: %s", pfx, msg);
	else
		syslog(prio, "%s", msg);
}

static void
logger_stderr(int prio, int ec, char const *pfx, char const *msg)
{
	fprintf(stderr, "%s: ", progname);
	if (pfx)
		fprintf(stderr, "%s: ", pfx);
	fprintf (stderr, "%s", msg);
	if (ec)
		fprintf(stderr, ": %s", strerror(ec));
	fputc('\n', stderr);
}

static void (*logger)(int, int, char const *, char const *) = logger_stderr;

static void
diagprt(grecs_locus_t const *locus, int err, int errcode, const char *msg)
{
	int prio = err ? LOG_ERR : LOG_WARNING;
	if (locus) {
		char *locbuf = NULL;
		size_t locsize = 0;
		if (grecs_asprint_locus(&locbuf, &locsize, locus) == 0) {
			logger(prio, errcode, locbuf, msg);
			free(locbuf);
			return;
		}
	}
	logger(prio, errcode, NULL, msg);
}

void
info(char const *fmt, ...)
{
	va_list ap;
	char *buf = NULL;
	size_t size = 0;
	int rc;
	
	va_start(ap, fmt);
	rc = grecs_vasprintf(&buf, &size, fmt, ap);
	va_end(ap);
	if (rc)
		grecs_error(NULL, errno, "grecs_vasprintf");
	else {
		logger(LOG_INFO, 0, NULL, buf);
		free(buf);
	}
}

void
syslog_enable(void)
{
	openlog(syslog_tag, LOG_PID, log_facility);
	logger = logger_syslog;
	grecs_log_to_stderr = 0;
}

int
open_node(char const *node, char const *serv, struct sockaddr **saddr)
{
	struct addrinfo hints;
	struct addrinfo *res;
	int reuse;
	int fd;
	int rc;
	
	memset(&hints, 0, sizeof (hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	rc = getaddrinfo(node, serv, &hints, &res);
	if (rc) {
		grecs_error(NULL, 0, "%s: %s", node, gai_strerror(rc));
		exit(1);
	}

	fd = socket(res->ai_family, res->ai_socktype, 0);
	if (fd == -1) {
		grecs_error(NULL, errno, "socket");
		exit(1);
	}

	reuse = 1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
		   &reuse, sizeof(reuse));
	if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) {
		grecs_error(NULL, errno, "bind");
		exit(1);
	}

	if (listen(fd, 8) == -1) {
		grecs_error(NULL, errno, "listen");
		exit(1);
	}

        if (saddr) {
		*saddr = grecs_malloc(res->ai_addrlen);
		memcpy(*saddr, res->ai_addr, res->ai_addrlen);
	}
	freeaddrinfo(res);

	return fd;
}

int
open_listener(char const *addr, struct sockaddr **saddr)
{
	size_t len;
	int fd;
	
	len = strcspn(addr, ":");
	if (len == 0)
		fd = open_node(DEFAULT_ADDRESS, addr + 1, saddr);
	else if (addr[len] == 0)
		fd = open_node(addr, DEFAULT_PORT, saddr);
	else {
		char *node;
		node = grecs_malloc(len + 1);
		memcpy(node, addr, len);
		node[len] = 0;
		fd = open_node(node, addr + len + 1, saddr);
		free(node);
	}
	return fd;
}

static void
stv_panic(void *cls, const char *file, unsigned int line,
	  const char *reason)
{
        if (reason)
		grecs_error(NULL, 0, "%s:%d: MHD PANIC: %s", file, line, reason);
	else
		grecs_error(NULL, 0, "%s:%d: MHD PANIC", file, line);
	abort();
}

static void
stv_logger(void *arg, const char *fmt, va_list ap)
{
	char *buf = NULL;
	size_t size = 0;
	
	if (grecs_vasprintf(&buf, &size, fmt, ap)) 
		grecs_error(NULL, errno, "grecs_vasprintf");
	else {
		logger(LOG_ERR, 0, NULL, buf);
		free(buf);
	}
}

#if HAVE_LIBWRAP
extern int stv_acl(void *cls, const struct sockaddr *addr,  socklen_t addrlen);
#else
# define stv_acl NULL
#endif

static void
acc_writer(void *closure, char const *text, size_t len)
{
	grecs_txtacc_grow((struct grecs_txtacc *)closure, text, len);
}

static char *
json_to_str(struct json_value *obj)
{
	struct grecs_txtacc *acc = grecs_txtacc_create();
	struct json_format fmt = {
		.indent = 0,
		.precision = 0,
		.write = acc_writer,
		.data = acc
	};
	char *str;
	
	json_format_value(obj, &fmt);
	grecs_txtacc_grow_char(acc, 0);
	str = grecs_txtacc_finish(acc, 1);
	grecs_txtacc_free(acc);
	return str;
}

void 
http_log(struct MHD_Connection *connection,
	 char const *method, char const *url,
	 int status, struct json_value *obj)
{
        char *ipstr;
	char const *host, *referer, *user_agent;
	time_t t;
	struct tm *tm;
	char tbuf[30];
	char *str;
	
	ipstr = get_remote_ip(connection);

	host = MHD_lookup_connection_value(connection,
					   MHD_HEADER_KIND,
					   MHD_HTTP_HEADER_HOST);
	referer = MHD_lookup_connection_value(connection,
					      MHD_HEADER_KIND,
					      MHD_HTTP_HEADER_REFERER);
	user_agent = MHD_lookup_connection_value(connection,
						 MHD_HEADER_KIND,
						 MHD_HTTP_HEADER_USER_AGENT);

	t = time(NULL);
	tm = localtime(&t);
	strftime(tbuf, sizeof(tbuf), "[%d/%b/%Y:%H:%M:%S %z]", tm);

	if (obj)
		str = json_to_str(obj);
	else
		str = NULL;
	
	info("%s %s - - %s \"%s %s\" \"%.1024s\" %3d \"%s\" \"%s\"",
	     host, ipstr, tbuf, method, url, str ? str : "", status, 
	     referer ? referer : "",
	     user_agent ? user_agent : "");
	free(str);
	free(ipstr);
}

int
http_error(struct MHD_Connection *conn,
	   char const *method, char const *url, int status)
{
	int ret;
	struct MHD_Response *resp =
		MHD_create_response_from_buffer (0,
						 NULL,
						 MHD_RESPMEM_PERSISTENT);
	http_log(conn, method, url, status, NULL);
	ret = MHD_queue_response(conn, status, resp);
	MHD_destroy_response(resp);
	return ret;
}

static int
stv_handler(void *cls,
	     struct MHD_Connection *conn,
	     const char *url, const char *method,
	     const char *version,
	     const char *upload_data, size_t *upload_data_size,
	     void **con_cls)
{
	grecs_txtacc_t acc;
	
	if (strcmp(method, MHD_HTTP_METHOD_POST))
		return http_error(conn, method, url,
				  MHD_HTTP_METHOD_NOT_ALLOWED);
	if (strcmp(url, "/"))
		return http_error(conn, method, url, MHD_HTTP_FORBIDDEN);

	if (*con_cls == NULL) {
		acc = grecs_txtacc_create();
		*con_cls = acc;
		return MHD_YES;
	} else {
		acc = *con_cls;
		if (*upload_data_size != 0) {
			grecs_txtacc_grow(acc, upload_data,
					  *upload_data_size);
			*upload_data_size = 0;
		} else {
			char *json;
			struct json_value *obj, *reply;
			struct MHD_Response *resp;
			int ret, rc;

			grecs_txtacc_grow_char(acc, 0);
			json = grecs_txtacc_finish(acc, 0);
			obj = json_parse_string(json, strlen(json));
			grecs_txtacc_free(acc);
			*con_cls = NULL;
			if (!obj) {
				grecs_error(&json_err_locus, 0, "%s", 
                                            json_err_diag);
				return http_error(conn, method, url,
						  //FIXME:
						MHD_HTTP_SERVICE_UNAVAILABLE);
			}

			rc = servdb_update(obj);

			reply = json_new_object();
			json_object_set(reply, "status",
					json_new_bool(rc == 0));
			json = json_to_str(reply);
			json_value_free(reply);
			
			resp = MHD_create_response_from_buffer
				(0, json, MHD_RESPMEM_MUST_COPY);
			free(json);
			MHD_add_response_header(resp,
						MHD_HTTP_HEADER_CONTENT_TYPE,
						"application/json");

			ret = MHD_queue_response(conn, MHD_HTTP_OK, resp);
			MHD_destroy_response(resp);
			http_log(conn, method, url, MHD_HTTP_OK, obj);
			json_value_free(obj);
			return ret;
		}
		return MHD_YES;
	}
	
	return http_error(conn, method, url, MHD_HTTP_INTERNAL_SERVER_ERROR);
}

static void
stv_request_completed (void *cls, struct MHD_Connection *connection,
		       void **con_cls, enum MHD_RequestTerminationCode toe)
{
	grecs_txtacc_t acc = *con_cls;

	if (acc) {
		grecs_txtacc_free(acc);
		*con_cls = NULL;
	}
}	


static int fatal_signals[] = {
	SIGHUP,
	SIGINT,
	SIGQUIT,
	SIGTERM,
	0
};

static void
http_server(int fd, struct sockaddr *server_addr)
{
	struct MHD_Daemon *mhd;
	sigset_t sigs;
	int i;
	pthread_t tid;
		
	/* Block the 'fatal signals' and SIGPIPE in the handling thread */
	sigemptyset(&sigs);
	for (i = 0; fatal_signals[i]; i++)
		sigaddset(&sigs, fatal_signals[i]);
	sigaddset(&sigs, SIGPIPE);
	
	pthread_sigmask(SIG_BLOCK, &sigs, NULL);
	MHD_set_panic_func(stv_panic, NULL);

	mhd = MHD_start_daemon(MHD_USE_INTERNAL_POLLING_THREAD
			       | MHD_USE_ERROR_LOG, 0,
			       stv_acl, server_addr, 
			       stv_handler, NULL,
			       MHD_OPTION_LISTEN_SOCKET, fd,
			       MHD_OPTION_NOTIFY_COMPLETED, stv_request_completed, NULL,
			       MHD_OPTION_EXTERNAL_LOGGER, stv_logger, NULL,
			       MHD_OPTION_END);
	/* Unblock only the fatal signals */
	sigdelset(&sigs, SIGPIPE);
	pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
	/* Start AgentX thread */
	pthread_create(&tid, NULL, agentx_thread, NULL);
	/* Start invalidating thread */
	pthread_create(&tid, NULL, invalidator_thread, NULL);
	/* Wait for signal to arrive */
	sigwait(&sigs, &i);
	MHD_stop_daemon(mhd);
}	

enum state {
	RUNNING,         /* Program is running */
	TERMINATING,     /* Program is terminating */
	CHILD_TERM,      /* SIGTERM has been sent to the child */
	CHILD_KILL
};
volatile enum state state;

static void
sigterm(int sig)
{
	if (state == RUNNING)
		state = TERMINATING;
}

static void
sigalrm(int sig)
{
	if (state == CHILD_TERM)
		state = CHILD_KILL;
}

static void
http_sentinel(int fd, struct sockaddr *server_addr)
{
	pid_t pid = 0;
	int i;
	struct sigaction act;
	pid_t child_pid = 0;
	int status;

	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);

	act.sa_handler = sigalrm;
	sigaction(SIGALRM, &act, NULL);
	
	for (i = 0; fatal_signals[i]; i++)
		sigaddset(&act.sa_mask, fatal_signals[i]);
	act.sa_handler = sigterm;
	for (i = 0; fatal_signals[i]; i++)
		sigaction(fatal_signals[i], &act, NULL);
		      
	while (1) {
		if (pid == 0) {
			if (state != RUNNING)
				break;
			pid = fork();
			if (pid == -1) {
				grecs_error(NULL, errno, "fork");
				break;
			}
			if (pid == 0) {
				runas(runas_user, runas_group);
				http_server(fd, server_addr);
				exit(0);
			}
		}
		
		if (child_pid > 0) {
			child_pid = 0;
			if (WIFEXITED(status)) {
				int code = WEXITSTATUS(status);
				if (code || debug > 1)
					grecs_error(NULL, 0,
                                                   "child exited with status %d",
					           code);
			} else if (WIFSIGNALED(status)) {
				char const *coremsg = "";
#ifdef WCOREDUMP
				if (WCOREDUMP(status))
					coremsg = " (core dumped)";
#endif
				grecs_error(NULL, 0,
                                            "child terminated on signal %d%s",
				            WTERMSIG(status), coremsg);
			} else if (WIFSTOPPED(status)) {
				grecs_error(NULL, 0,
                                            "child stopped on signal %d",
				            WSTOPSIG(status));
				continue;
			} else {
				grecs_error(NULL, 0, 
                                            "child terminated with unrecognized status %d", 
                                            status);
			}
			/* restart the child */
			pid = 0;
			continue;
		}

		switch (state) {
		case RUNNING:
			break;
			
		case TERMINATING:
			kill(pid, SIGTERM);
			alarm(5);
			state = CHILD_TERM;
			break;

		case CHILD_TERM:
			break;

		case CHILD_KILL:
			kill(pid, SIGKILL);
			return;
		}

		child_pid = wait(&status);
		if (child_pid == -1) {
			if (errno != EINTR || debug > 1)
				grecs_error(NULL, errno, "wait");
		}		
	}
}

int
main(int argc, char **argv)
{
	int c;
	char *config_file = DEFAULT_CONFIG_FILE_NAME;
	int single_process = 0;
	int foreground = 0;
	struct sockaddr *server_addr;
	int fd;
	
	progname = strrchr(argv[0], '/');
	if (progname)
		progname++;
	else
		progname = argv[0];
	if (strncmp(progname, "lt-", 3) == 0)
		progname += 3;
	grecs_print_diag_fun = diagprt;
	while ((c = getopt_long(argc, argv, shortopts, longopts, NULL))
	       != EOF) {
		switch (c) {
		case '?':
			help();
			exit(0);
		case 'd':
			debug++;
			break;
		case 'f':
			config_file = optarg;
			break;
		case 'F':
			foreground = 1;
			break;
		case 's':
			single_process = 1;
			break;
		case 'V':
			version();
			exit(0);
		case OPT_CONFIG_HELP:
			config_help();
			exit(0);
		default:
			exit(1);
		}
	}

	if (access(config_file, F_OK)) {
		grecs_error(NULL, 0, "configuration file %s does not exist", 
                            config_file);
		exit(1);
	}

	readconfig(config_file);
	pidfile_check();
	fd = open_listener(listen_address, &server_addr);
	if (single_process)
		runas(runas_user, runas_group);
	if (!foreground) {
		int i;
		if (daemon(0, 1)) {
			grecs_error(NULL, errno, "daemon");
			exit(1);
		}
		for (i = 0; i < fd; i++)
			close(i);
		syslog_enable();
	}
	agentx_init();
	
	pidfile_create();

	if (single_process)
		http_server(fd, server_addr);
	else 
		http_sentinel(fd, server_addr);
	
	pidfile_remove();
	return 0;
}

Return to:

Send suggestions and report system problems to the System administrator.