aboutsummaryrefslogtreecommitdiff
path: root/src/ping903.c
blob: b4ea906db68ad3301552105f54f802e94a3882a4 (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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
/* This file is part of Ping903
   Copyright (C) 2020 Sergey Poznyakoff
  
   Ping903 is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.
  
   Ping903 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 General Public License for more details.
  
   You should have received a copy of the GNU General Public License
   along with Ping903.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <syslog.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <microhttpd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <fnmatch.h>
#include "ping903.h"
#include "json.h"
#include "defs.h"
#include "basicauth.h"

char *httpd_addr;
int httpd_access_log = 0;
int httpd_log_verbose = 0;
unsigned int httpd_backlog_size = SOMAXCONN;


struct strentry {
	struct strentry *next;
	char str[1];
};

struct strlist {
	struct strentry *head, *tail;
};

static int
strlist_add(struct strlist *slist, const char *str, size_t len)
{
	struct strentry *sent = malloc(sizeof(*sent) + len);
	if (!sent)
		return -1;

	memcpy(sent->str, str, len);
	sent->str[len] = 0;
	sent->next = NULL;
	
	if (slist->tail)
		slist->tail->next = sent;
	else
		slist->head = sent;
	slist->tail = sent;
	return 0;
}

static void
strlist_free(struct strlist *slist)
{
	struct strentry *sent = slist->head;
	while (sent) {
		struct strentry *next = sent->next;
		free(sent);
		sent = next;
	}
	slist->head = slist->tail = NULL;
}

static int
strlist_from_csv(struct strlist *slist, const char *s)
{
	while (*s) {
		size_t n = strcspn(s, ",");
		if (n > 0) {
			if (strlist_add(slist, s, n)) {
				strlist_free(slist);
				return -1;
			}
		}
		s += n;
		if (*s)
			s++;
	}
	return 0;
}

static 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) {
		error("%s: %s", node, gai_strerror(rc));
		exit(1);
	}

	fd = socket(res->ai_family, res->ai_socktype, 0);
	if (fd == -1) {
		error("socket: %s", strerror(errno));
		exit(1);
	}
	reuse = 1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
		   &reuse, sizeof(reuse));
	if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) {
		error("bind: %s", strerror(errno));
		exit(1);
	}

	if (listen(fd, 8) == -1) {
		error("listen: %s", strerror(errno));
		exit(1);
	}

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

	return fd;
}

static int
open_listener(char const *addr, struct sockaddr **saddr)
{
	size_t len;
	int fd;

	if (!addr)
		return open_node(DEFAULT_ADDRESS, DEFAULT_SERVICE, saddr);
	
	len = strcspn(addr, ":");
	if (len == 0)
		fd = open_node(DEFAULT_ADDRESS, addr + 1, saddr);
	else if (addr[len] == 0)
		fd = open_node(addr, DEFAULT_SERVICE, saddr);
	else {
		char *node;
		node = emalloc(len + 1);
		memcpy(node, addr, len);
		node[len] = 0;
		fd = open_node(node, addr + len + 1, saddr);
		free(node);
	}
	return fd;
}

static void
p903_httpd_logger(void *arg, const char *fmt, va_list ap)
{
	vlogger(LOG_ERR, fmt, ap);
}

static void
p903_httpd_panic(void *cls, const char *file, unsigned int line,
		 const char *reason)
{
	if (reason)
		fatal("%s:%d: MHD PANIC: %s", file, line, reason);
	else
		fatal("%s:%d: MHD PANIC", file, line);
	abort();
}

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

static int
reassemble_get_args(void *cls, enum MHD_ValueKind kind,
		    const char *key, const char *value)
{
	struct strlist *slist = cls;
	strlist_add(slist, "&", 1);
	strlist_add(slist, key, strlen(key));
	if (value) {
		strlist_add(slist, "=", 1);
		strlist_add(slist, value, strlen(value));
	}
	return MHD_YES;
}

static void
http_log(struct MHD_Connection *connection,
	 char const *method, char const *url,
	 int status, char const *str)
{
	char *ipstr;
	char const *host, *referer, *user_agent;
	time_t t;
	struct tm *tm;
	char tbuf[30];
	struct strlist slist = { NULL, NULL };
	char *reqs = NULL;
	
	if (!httpd_access_log)
		return;
	if (!httpd_log_verbose)
		str = NULL;
	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);

	MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND,
				  &reassemble_get_args, &slist);
	if (slist.head) {
		size_t len = 0;
		struct strentry *sent;
		char *p;
		
		for (sent = slist.head; sent; sent = sent->next)
			len += strlen(sent->str);
		p = malloc(len + 1);
		if (p) {
			reqs = p;
			*p++ = '?';
			for (sent = slist.head->next; sent; sent = sent->next)
				p += strlen(strcpy(p, sent->str));
			*p = 0;
		}
		strlist_free(&slist);
	}
	
	info("%s %s - - %s \"%s %s%s\" \"%.1024s\" %3d \"%s\" \"%s\"",
	     host, ipstr, tbuf, method, url, reqs ? reqs : "",
	     str ? str : "", status,
	     referer ? referer : "",
	     user_agent ? user_agent : "");
	free(reqs);
	free(ipstr);
}

static int
http_response(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 httpd_json_response(struct MHD_Connection *conn,
			       char const *url, char const *method,
			       int status,
			       struct json_value *val);

static int
http_response_detail(struct MHD_Connection *conn,
		     char const *method, char const *url, int status,
		     char const *message, int index)
{
	struct json_value *jv, *errobj = json_new_object();
	int rc;
		
	if (!errobj)
		goto err;
	if ((jv = json_new_string(message)) == NULL)
		goto err;
	if (json_object_set(errobj, "message", jv))
		goto err;
	if (index) {
		if ((jv = json_new_number(index)) == NULL)
			goto err;
		if (json_object_set(errobj, "index", jv))
			goto err;
	}
	rc = httpd_json_response(conn, url, method, status, errobj);
	json_value_free(errobj);
	return rc;
err:
	json_value_free(errobj);
	return http_response(conn, method, url,
			     MHD_HTTP_INTERNAL_SERVER_ERROR);
}

struct strbuf {
	char *base;
	size_t off;
	size_t size;
	int err;
};

static void
strbuf_writer(void *closure, char const *text, size_t len)
{
	struct strbuf *sb = closure;
	if (sb->err)
		return;
	while (sb->off + len >= sb->size) {
		char *p = json_2nrealloc(sb->base, &sb->size, 1);
		if (!p) {
			error("not enough memory trying to format reply");
			sb->err = 1;
			return;
		}
		sb->base = p;
	}
	memcpy(sb->base + sb->off, text, len);
	sb->off += len;
}
	
static char *
json_to_str(struct json_value *obj)
{
	struct strbuf sb;
	struct json_format fmt = {
		.indent = 0,
		.precision = 5,
		.write = strbuf_writer,
		.data = &sb
	};

	memset(&sb, 0, sizeof(sb));
	json_value_format(obj, &fmt, 0);
	strbuf_writer(&sb, "", 1);

	if (sb.err) {
		free(sb.base);
		return NULL;
	}
	return sb.base;
}

static int
httpd_json_response(struct MHD_Connection *conn,
		    char const *url, char const *method,
		    int status,
		    struct json_value *val)
{
	char *reply;
	struct MHD_Response *resp;
	int ret;
	
	reply = json_to_str(val);
	json_value_free(val);
	if (!reply)
		return http_response(conn, method, url,
				  MHD_HTTP_INTERNAL_SERVER_ERROR);
	
	resp = MHD_create_response_from_buffer(strlen(reply),
					       reply, MHD_RESPMEM_MUST_COPY);
	http_log(conn, method, url, status, reply);
	free(reply);
	MHD_add_response_header(resp,
				MHD_HTTP_HEADER_CONTENT_TYPE,
				"application/json");
	ret = MHD_queue_response(conn, status, resp);
	MHD_destroy_response(resp);
	return ret;
}

static int try_auth(struct MHD_Connection *conn, const char *url,
		    const char *method, int *ret_val);

struct auth_flt_data
{
	struct MHD_Connection *conn;
	const char *url;
	const char *method;
	int err;
};
	
static int
auth_flt(char const *kw, struct json_value *val, void *data)
{
	int rc;
	struct auth_flt_data *adata = data;
	char *url = malloc(strlen(adata->url) + strlen(kw) + 2);
	if (!url) {
		adata->err = 1;
		return 0;
	}
	strcpy(url, adata->url);
	strcat(url, "/");
	strcat(url, kw);
	rc = try_auth(adata->conn, url, adata->method, NULL);
	free(url);
	return rc;
}

static int
attr_flt(char const *kw, struct json_value *val, void *data)
{
	return strcmp(kw, (char*)data);
}

static int
http_json_flt_response(struct MHD_Connection *conn,
		       const char *url, const char *method,
		       struct json_value *val, const char *suffix)
{
	int ret;
	
	if (!val)
		return http_response(conn, method, url,
				  MHD_HTTP_INTERNAL_SERVER_ERROR);
	while (*suffix == '/')
		suffix++;
	if (*suffix) {
		if (json_object_filter(val, attr_flt, (void*)suffix)) {
			ret = http_response(conn, method, url,
					    MHD_HTTP_INTERNAL_SERVER_ERROR);
			json_value_free(val);
			return ret;
		}
		if (!val->v.o->head) {
			ret = http_response(conn, method, url,
						MHD_HTTP_NOT_FOUND);
			json_value_free(val);
			return ret;
		}
	} else {
		struct auth_flt_data adata = {
			.conn = conn,
			.url = url,
			.method = method,
			.err = 0
		};
		if (json_object_filter(val, auth_flt, &adata) || adata.err) {
			ret = http_response(conn, method, url,
					    MHD_HTTP_INTERNAL_SERVER_ERROR);
			json_value_free(val);
			return ret;
		}
	}	
		
	return httpd_json_response(conn, url, method, MHD_HTTP_OK, val);
}

static struct json_value *
ident_to_json(void)
{
	struct json_value *obj, *jv;

	obj = json_new_object();
	if (!obj)
		return NULL;
	if (!(jv = json_new_string(PACKAGE))
	    || json_object_set(obj, "package", jv))
		goto err;
	if (!(jv = json_new_string(PACKAGE_VERSION))
	    || json_object_set(obj, "version", jv))
		goto err;
	if (!(jv = json_new_number(getpid()))
	    || json_object_set(obj, "pid", jv))
		goto err;
	return obj;
err:
	json_value_free(jv);
	json_value_free(obj);
	return NULL;
}

static int
ept_ident(struct MHD_Connection *conn,
	  const char *url, const char *method, const char *suffix,
	  struct json_value *unused)
{
	return http_json_flt_response(conn, url, method,
				      ident_to_json(), suffix);
}

static int
ept_config(struct MHD_Connection *conn,
	   const char *url, const char *method, const char *suffix,
	   struct json_value *unused)
{
	return http_json_flt_response(conn, url, method,
				      config_to_json(), suffix);
}

static int
ept_ip_delete(struct MHD_Connection *conn,
	      const char *url, const char *method, const char *suffix,
	      struct json_value *unused)
{
	int ret;

	while (*suffix == '/')
		suffix++;
	if (!*suffix)
		return http_response(conn, method, url, MHD_HTTP_FORBIDDEN);
	switch (pinger_host_delete_by_name(suffix)) {
	case UPD_OK:
		ret = http_response(conn, method, url, MHD_HTTP_OK);
		break;

	case UPD_EXISTS:
		ret = http_response_detail(conn, method, url,
					   MHD_HTTP_NOT_FOUND,
					   "No such host", 0);
		break;
		
	default:
		ret = http_response(conn, method, url,
				    MHD_HTTP_INTERNAL_SERVER_ERROR);
	}
	return ret;
}

static int
ept_ip_put(struct MHD_Connection *conn,
	   const char *url, const char *method, const char *suffix,
	   struct json_value *unused)
{
	while (*suffix == '/')
		suffix++;
	if (!*suffix)
		return http_response(conn, method, url, MHD_HTTP_FORBIDDEN);
	switch (pinger_host_add_name(suffix)) {
	case UPD_OK:
		break;
		
	case UPD_NORESOLV:
		return http_response_detail(conn, method, url,
					    MHD_HTTP_FORBIDDEN,
					    "Hostname does not resolve",
					    0);

	case UPD_NOMEM:
		return http_response(conn, method, url,
				     MHD_HTTP_INTERNAL_SERVER_ERROR);
		
	case UPD_EXISTS:
		return http_response_detail(conn, method, url,
					    MHD_HTTP_FORBIDDEN,
					    "Hostname already exists",
					    0);
	}

	return http_response(conn, method, url, MHD_HTTP_CREATED);
}

static int
ept_ip_post(struct MHD_Connection *conn,
	    const char *url, const char *method, const char *suffix,
	    struct json_value *obj)
{
	char const *err_text;
	int err_pos;
	int status;

	status = pinger_hostlist_set(obj, &err_text, &err_pos);
	if (!err_text && !err_pos)
		return http_response(conn, method, url, status);
	else
		return http_response_detail(conn, method, url, status,
					    err_text, err_pos);
}

struct host_stat_args_closure {
	struct strlist hostlist;
	struct strlist attrlist;
	int err;
};

static int
collect_host_stat_args(void *cls, enum MHD_ValueKind kind,
		       const char *key, const char *value)
{
	struct host_stat_args_closure *clos = cls;
	
	if (strcmp(key, "select") == 0 && value) {
		if (strlist_from_csv(&clos->hostlist, value)) {
			clos->err = 1;
			return MHD_NO;
		}
	} else if (strcmp(key, "attr") == 0 && value) {
		if (strlist_from_csv(&clos->attrlist, value)) {
			clos->err = 1;
			return MHD_NO;
		}
	} else {
		clos->err = 1;
		return MHD_NO;
	}
	return MHD_YES;
}

static void
host_stat_args_free(struct host_stat_args_closure *clos)
{
	strlist_free(&clos->hostlist);
	strlist_free(&clos->attrlist);
}

static int
get_selected_host_stat(struct strlist const *slist,
		       struct json_value **ret_arr)
{
	struct json_value *arr, *jv;
	struct strentry *sent;
	
	if (!(arr = json_new_array()))
		return GET_NOMEM;
	for (sent = slist->head; sent; sent = sent->next) {
		switch (get_hostname_stat(sent->str, &jv)) {
		case GET_OK:
			break;
			
		case GET_NOENT:
			jv = json_new_null();
			break;

		case GET_NOMEM:
			jv = NULL;
			break;
		}
		if (jv) {
			if (json_array_append(arr, jv) == 0)
				continue;
			json_value_free(jv);
		}
		/* Error: */
		json_value_free(arr);
		return -1;
	}
	*ret_arr = arr;
	return 0;
}

static int
attrlist_flt(char const *kw, struct json_value *val, void *data)
{
	struct strlist *slist = data;
	struct strentry *sent;

	for (sent = slist->head; sent; sent = sent->next) {
		if (strcmp(kw, sent->str) == 0)
			return 0;
	}
	return 1;
}

static int
attrlist_extract(struct json_value *val, struct strlist *slist)
{
	if (val && slist->head) {
		switch (val->type) {
		case json_array: {
			size_t i;

			for (i = 0; i < val->v.a->oc; i++) {
				if (attrlist_extract(val->v.a->ov[i], slist))
					return -1;
			}
			break;
		}
		case json_object:
			return json_object_filter(val, attrlist_flt, slist);
			break;
			
		default:
			/* Leave scalar values unchanged */
			break;
		}
	}
	return 0;
}

static int
ept_host_stat(struct MHD_Connection *conn,
	      const char *url, const char *method, const char *suffix,
	      struct json_value *unused)
{
	struct json_value *val;
	int rc, ret;
	struct host_stat_args_closure clos;
	
	while (*suffix == '/')
		suffix++;

	memset(&clos, 0, sizeof(clos));
	if (*suffix && strlist_add(&clos.hostlist, suffix, strlen(suffix)))
		return http_response(conn, method, url,
				     MHD_HTTP_INTERNAL_SERVER_ERROR);
	MHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND,
				  &collect_host_stat_args, &clos);
	if (clos.err) {
		host_stat_args_free(&clos);
		return http_response(conn, method, url, MHD_HTTP_BAD_REQUEST);
	}

	if (clos.hostlist.head) {
		rc = get_selected_host_stat(&clos.hostlist, &val);
	} else {
		rc = get_all_host_stat(&val);
	}

	if (attrlist_extract(val, &clos.attrlist)) {
		json_value_free(val);
		rc = GET_NOMEM;
	}		

	host_stat_args_free(&clos);
	
	switch (rc) {
	case GET_OK:
	case GET_NOENT:
		ret = httpd_json_response(conn, url, method, MHD_HTTP_OK, val);
		break;

	default:
		ret = http_response(conn, method, url,
				    MHD_HTTP_INTERNAL_SERVER_ERROR);
		
	}
	return ret;
}

static int
ept_ip_match(struct MHD_Connection *conn,
	     const char *url, const char *method, const char *suffix,
	     struct json_value *unused)
{
	struct json_value *ar;
	struct host_stat_args_closure clos;
	struct strentry *ent;

	while (*suffix == '/')
		suffix++;
	
	memset(&clos, 0, sizeof(clos));
	if (*suffix && strlist_add(&clos.hostlist, suffix, strlen(suffix)))
		return http_response(conn, method, url,
				     MHD_HTTP_INTERNAL_SERVER_ERROR);
	MHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND,
				  &collect_host_stat_args, &clos);
	if (clos.err || clos.attrlist.head) {
		host_stat_args_free(&clos);
		return http_response(conn, method, url, MHD_HTTP_BAD_REQUEST);
	}
	if (!clos.hostlist.head)
		return http_response(conn, method, url, MHD_HTTP_FORBIDDEN);

	if (!(ar = json_new_array()))
		goto err;
	for (ent = clos.hostlist.head; ent; ent = ent->next) {
		struct json_value *obj, *jv;
		
		if (!(obj = json_new_object()))
			goto err;
		if (json_array_append(ar, obj)) {
			json_value_free(obj);
			goto err;
		}
		if (!(jv = json_new_string(ent->str))
		    || json_object_set(obj, "name", jv)) {
			json_value_free(jv);
			goto err;
		}
		if (!(jv = json_new_array())
		    || json_object_set(obj, "hosts", jv)) {
			json_value_free(jv);
			goto err;
		}
	}	

	host_stat_args_free(&clos);

	if (get_host_matches(ar) == 0)
		return httpd_json_response(conn, url, method, MHD_HTTP_OK, ar);

err:
	host_stat_args_free(&clos);
	json_value_free(ar);
	return http_response(conn, method, url,
			     MHD_HTTP_INTERNAL_SERVER_ERROR);
}

enum auth_type {
	AUTH_NONE,
	AUTH_BASIC
};
	
struct auth_location {
	int type;
	char *url;
	size_t ulen;
	int wildcard;
	char *method;
	char *passwd_file;
	char *realm;
	struct auth_location *next;
};

static struct auth_location *auth_head, *auth_tail;

static int
cf_auth_parse(union cf_callback_arg *arg, void *data)
{
	int ac;
	char **av;
	char *endp;
	struct auth_location *loc;
	int type;
	char *passwd_file = NULL;
	char *realm = NULL;
		
	// auth TYPE METHOD URL [FILE [REALM]]
	enum { i_type, i_method, i_url, i_file, i_realm };

	switch (strsplit(arg->input.val, 5, &ac, &av, &endp)) {
	case STRSPLIT_OK:
		if (!*endp)
			break;
		/* fall through */
	case STRSPLIT_ERR:
		error("%s:%d: syntax error near %s",
		      arg->input.file, arg->input.line, endp);
		argcv_free(ac, av);
		return CF_RET_FAIL;
		
	case STRSPLIT_NOMEM:
		emalloc_die();
	}
	
        if (ac < 3) {
		error("%s:%d: syntax error",
		      arg->input.file, arg->input.line);
		argcv_free(ac, av);
		return CF_RET_FAIL;
	}

	if (strcmp(av[i_type], "basic") == 0) {
		type = AUTH_BASIC;
		if (ac < 5 && (!auth_tail || auth_tail->type != type)) {
			error("%s:%d: realm or password file name missing",
			      arg->input.file, arg->input.line);
			argcv_free(ac, av);
			return CF_RET_FAIL;
		}
		passwd_file = ac > i_file ? av[i_file] : auth_tail->passwd_file;
		realm = ac > i_realm ? av[i_realm] : auth_tail->realm;
	} else if (strcmp(av[i_type], "none") == 0) {
		type = AUTH_NONE;
		if (ac > 3) {
			error("%s:%d: too many arguments for this authorization type",
			      arg->input.file, arg->input.line);
			argcv_free(ac, av);
			return CF_RET_FAIL;
		}
			
	} else {
		error("%s:%d: unsupported authentication method",
		      arg->input.file, arg->input.line);
		argcv_free(ac, av);
		return CF_RET_FAIL;
	}

	loc = emalloc(sizeof(*loc));
	loc->type = type;
	loc->url = av[i_url];
	loc->ulen = strlen(loc->url);
	loc->wildcard = loc->url[strcspn(loc->url, "[]*?")] != 0;
	loc->method = av[i_method];
	loc->passwd_file = passwd_file;
	loc->realm = realm;
	loc->next = NULL;

	if (auth_tail)
		auth_tail->next = loc;
	else
		auth_head = loc;
	auth_tail = loc;

	/* All elements except 1st were transferred to loc, hence 1 as the
	   value of the first parameter. */
	argcv_free(1, av); 
	
	return CF_RET_OK;
}

static int
cf_auth_serialize(union cf_callback_arg *arg, void *data)
{
	struct json_value *ar, *obj = NULL, *jv = NULL;
	struct auth_location *auth;
	static char const *auth_type_str[] = {
		[AUTH_NONE] = "none",
		[AUTH_BASIC] = "basic"
	};

	if (!auth_head)
		return CF_RET_IGNORE;
	
	if (!(ar = json_new_array()))
		return CF_RET_FAIL;
	
	for (auth = auth_head; auth; auth = auth->next) {
		if (!(obj = json_new_object()))
			goto err;
		if (!(jv = json_new_string(auth_type_str[auth->type]))
		    || json_object_set(obj, "type", jv))
			goto err;
		if (!(jv = json_new_string(auth->url))
		    || json_object_set(obj, "url", jv))
			goto err;
		if (!(jv = json_new_string(auth->method))
		    || json_object_set(obj, "method", jv))
			goto err;
		if (auth->type == AUTH_BASIC) {
			if (auth->passwd_file
			    && (!(jv = json_new_string(auth->passwd_file))
				|| json_object_set(obj, "passwd-file", jv)))
				goto err;
			if (auth->realm
			    && (!(jv = json_new_string(auth->realm))
				|| json_object_set(obj, "realm", jv)))
				goto err;
		}
		if (json_array_append(ar, obj))
			goto err;
	}
	arg->output = ar;
	return CF_RET_OK;
err:
	json_value_free(jv);
	json_value_free(obj);
	json_value_free(ar);
	return CF_RET_FAIL;
}

int
cf_auth(int mode, union cf_callback_arg *arg, void *data)
{
	switch (mode) {
	case CF_PARSE:
		return cf_auth_parse(arg, data);
	case CF_SERIALIZE:
		return cf_auth_serialize(arg, data);
	}
	abort();
}

#define WWW_AUTH_PFX "Basic realm=\""
#define WWW_AUTH_SFX "\""

static char *
www_auth_hdr_format(char const *realm)
{
	size_t len = strlen(realm);
	char const *p;
	char *buf, *q;
	
	for (p = realm; *p; p++)
		if (*p == '\\' || *p == '"')
			len++;

	len += sizeof(WWW_AUTH_PFX) + sizeof(WWW_AUTH_SFX) - 1;

	buf = malloc(len);
	if (buf) {
		strcpy(buf, WWW_AUTH_PFX);
		q = buf + sizeof(WWW_AUTH_PFX) - 1;
		for (p = realm; *p; p++) {
			if (*p == '\\' || *p == '"')
				*q++ = '\\';
			*q++ = *p;
		}
		strcpy(q, WWW_AUTH_SFX);
	}
	return buf;
}

static int
http_unauthorized(struct MHD_Connection *conn,
		  char const *method, char const *url,
		  char const *str)
{
	int status = MHD_HTTP_UNAUTHORIZED;
	int ret;
	char *buf;
	struct MHD_Response *resp =
		MHD_create_response_from_buffer(0,
						NULL,
						MHD_RESPMEM_PERSISTENT);
	buf = www_auth_hdr_format(str);
	if (buf) {
		MHD_add_response_header(resp,
					MHD_HTTP_HEADER_WWW_AUTHENTICATE,
					buf);
		free(buf);
	} else {
		status = MHD_HTTP_INTERNAL_SERVER_ERROR;
	}
	http_log(conn, method, url, status, NULL);
	ret = MHD_queue_response(conn, status, resp);
	MHD_destroy_response(resp);
	return ret;
}

static int
try_auth(struct MHD_Connection *conn, const char *url, const char *method,
	 int *ret_val)
{
	struct auth_location *loc;
	size_t url_len;
	char *url_buf;
	char *p;
	char const *q;
	
	url_len = strlen(url);
	while (url_len > 1 && url[url_len-1] == '/')
		--url_len;
	url_buf = malloc(url_len + 1);
	if (!url_buf) {
		if (ret_val)
			*ret_val = http_response(conn, method, url,
						 MHD_HTTP_INTERNAL_SERVER_ERROR);
		return 1;
	}

	/* Copy url to url_buf squashing repeated '/' into a single slash */
	p = url_buf;
	q = url;
	while (*q) {
		if (!(*q == '/' && (q[1] == 0 || (q > url && q[-1] == '/'))))
			*p++ = *q;
		q++;
	}
	*p = 0;
	
	for (loc = auth_head; loc; loc = loc->next) {
		if (fnmatch(loc->method, method, 0))
			continue;
		if (loc->wildcard
		    ? fnmatch(loc->url, url_buf, 0) == 0
		    : (url_len >= loc->ulen
		       && strncmp(url_buf, loc->url, loc->ulen) == 0
		       && (url_buf[loc->ulen] == '/'
			   || url_buf[loc->ulen] == 0))) {
			char const *auth;

			free(url_buf);

			if (loc->type == AUTH_NONE)
				return 0;
			
			auth = MHD_lookup_connection_value(conn,
					       MHD_HEADER_KIND,
					       MHD_HTTP_HEADER_AUTHORIZATION);
			if (!auth) {
				if (ret_val)
					*ret_val = http_unauthorized(conn,
								     method,
								     url,
								     loc->realm);
				return 1;
			}
			switch (basicauth(loc->passwd_file, auth)) {
			case BASICAUTH_DENY:
			case BASICAUTH_BAD_INPUT:
				if (ret_val)
					*ret_val = http_unauthorized(conn,
								     method,
								     url,
								     loc->realm);
				return 1;				
			case BASICAUTH_ALLOW:
				return 0;
			case BASICAUTH_CANT_OPEN:
				error("can't open password file %s: %s",
				      loc->passwd_file, strerror(errno));
				/* fall through */
			default:
				if (ret_val)
					*ret_val = http_response(conn,
								 method,
								 url,
					      MHD_HTTP_INTERNAL_SERVER_ERROR);
				return 1;
			}
		}
	}
	free(url_buf);
	return 0;
}

typedef int (*ENDPOINT_HANDLER)(struct MHD_Connection *,
				const char *, const char *, const char *,
				struct json_value *);

enum {
	EPT_EXACT  = 0x01,
	EPT_PREFIX = 0x02
};

struct endpoint {
	char *url;
	int flags;
	char *method;
	ENDPOINT_HANDLER handler;
};

static struct endpoint endpoint[] = {
	{ "/id", EPT_PREFIX, MHD_HTTP_METHOD_GET, ept_ident },
	{ "/config/ip-list", EPT_PREFIX, MHD_HTTP_METHOD_PUT, ept_ip_put },
	{ "/config/ip-list", EPT_PREFIX, MHD_HTTP_METHOD_POST, ept_ip_post },
	{ "/config/ip-list", EPT_PREFIX, MHD_HTTP_METHOD_DELETE, ept_ip_delete },
	{ "/config", EPT_PREFIX, MHD_HTTP_METHOD_GET, ept_config },
	{ "/host",   EPT_PREFIX, MHD_HTTP_METHOD_GET, ept_host_stat },
	{ "/match",  EPT_PREFIX, MHD_HTTP_METHOD_GET, ept_ip_match },
	{ NULL }
};

static int
find_endpoint_handler(char const *url, char const *method,
		      ENDPOINT_HANDLER *ret_handler, char const **ret_suffix)
{
	struct endpoint *ept;
	int urlmatch = 0;
	for (ept = endpoint; ept->url; ept++) {
		if (ept->flags & EPT_EXACT) {
			if (strcmp(ept->url, url) == 0) {
				if (strcmp(ept->method, method)) {
					urlmatch++;
					continue;
				}
				*ret_handler = ept->handler;
				*ret_suffix = url + strlen(url);
				return MHD_HTTP_OK;
			}
		} else {
			size_t len = strlen(ept->url);
			if (strncmp(url, ept->url, len) == 0
			    && (url[len] == '/' || url[len] == 0)) {
				if (strcmp(ept->method, method)) {
					urlmatch++;
					continue;
				}
				*ret_handler = ept->handler;
				*ret_suffix = url + len;
				return MHD_HTTP_OK;
			}
		}
	}
	return urlmatch ? MHD_HTTP_METHOD_NOT_ALLOWED : MHD_HTTP_NOT_FOUND;
}

struct postbuf {
	char *base;
	size_t size;
	size_t len;
	ENDPOINT_HANDLER handler;
	char suffix[1];
};

static void
postbuf_free(struct postbuf *pb)
{
	free(pb->base);
	free(pb);
}

static int
postbuf_add(struct postbuf *pb, const char *str, size_t len)
{	
	while (pb->len + len >= pb->size) {
		char *np = json_2nrealloc(pb->base, &pb->size, 1);
		if (!np)
			return -1;
		pb->base = np;
	}
	memcpy(pb->base + pb->len, str, len);
	pb->len += len;
	return 0;
}

static int
p903_httpd_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)
{
	ENDPOINT_HANDLER handler;
	char const *suffix;
	int status;

	if (*con_cls == NULL && try_auth(conn, url, method, &status))
		return status;
	if (strcmp(method, MHD_HTTP_METHOD_POST) == 0) {
		struct postbuf *pb;
		
		if (*con_cls == NULL) {
			char const *ctype;
			
			status = find_endpoint_handler(url, method, &handler,
						       &suffix);
			if (status != MHD_HTTP_OK)
				return http_response(conn, method, url, status);

			ctype = MHD_lookup_connection_value(conn,
							    MHD_HEADER_KIND,
							    MHD_HTTP_HEADER_CONTENT_TYPE);
			if (!ctype || strcmp(ctype, "application/json"))
				return http_response(conn, method, url,
						  MHD_HTTP_NOT_ACCEPTABLE);

			pb = malloc(sizeof(*pb) + strlen(suffix));
			if (!pb)
				return http_response(conn, method, url,
						  MHD_HTTP_INTERNAL_SERVER_ERROR);
			pb->base = NULL;
			pb->size = 0;
			pb->len  = 0;
			pb->handler = handler;
			strcpy(pb->suffix, suffix);
			*con_cls = pb;
		} else {
			pb = *con_cls;
			if (*upload_data_size != 0) {
				if (postbuf_add(pb, upload_data,
						*upload_data_size)) {
					postbuf_free(pb);
					return http_response(conn, method, url,
					        MHD_HTTP_INTERNAL_SERVER_ERROR);
				}
				*upload_data_size = 0;
			} else {
				char *endp;
				int rc;
				struct json_value *jv;
				
				if (postbuf_add(pb, "", 1)) {
					postbuf_free(pb);
					return http_response(conn, method, url,
					        MHD_HTTP_INTERNAL_SERVER_ERROR);
				}
				rc = json_parse_string(pb->base, &jv, &endp);
				if (rc != JSON_E_NOERR) {
					error("%s: %s near #%ld", url,
					      json_strerror(rc),
					      endp - pb->base);
					return http_response(conn, method, url,
							  MHD_HTTP_BAD_REQUEST);
				}
				rc = pb->handler(conn, url, method, pb->suffix,
						 jv);
				postbuf_free(pb);
				json_value_free(jv);
				return rc;
			}
		}
		return MHD_YES;
	}

	/* For all other methods */
	status = find_endpoint_handler(url, method, &handler, &suffix);
	if (status != MHD_HTTP_OK)
		return http_response(conn, method, url, status); 
	return handler(conn, url, method, suffix, NULL);
}

static void
sigign(int sig)
{
}

void
ping903(void)
{
	struct MHD_Daemon *mhd;
	sigset_t sigs;
	int i;
	pthread_t tid;
        int fd = -1;
	struct sockaddr *server_addr;
	void *p;
	struct sigaction act;

	p903_init();
	
	fd = open_listener(httpd_addr, &server_addr);
	
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	act.sa_handler = sigign;

	/* Block the 'fatal signals' and SIGPIPE in the handling thread */
	sigemptyset(&sigs);
	for (i = 0; fatal_signals[i]; i++) {
		sigaddset(&sigs, fatal_signals[i]);
		sigaction(fatal_signals[i], &act, NULL);
	}
	
	sigaddset(&sigs, SIGPIPE);

	pthread_sigmask(SIG_BLOCK, &sigs, NULL);
	MHD_set_panic_func(p903_httpd_panic, NULL);
	mhd = MHD_start_daemon(MHD_USE_INTERNAL_POLLING_THREAD
			       | MHD_USE_ERROR_LOG, 0,
			       p903_httpd_acl, server_addr,
			       p903_httpd_handler, NULL,
			       MHD_OPTION_LISTEN_SOCKET, fd,
			       MHD_OPTION_EXTERNAL_LOGGER, p903_httpd_logger, NULL,
			       MHD_OPTION_LISTEN_BACKLOG_SIZE, httpd_backlog_size,
			       MHD_OPTION_END);
	
	/* Unblock only the fatal signals */
	sigdelset(&sigs, SIGPIPE);
	pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);

	/* Start the Receiver thread */
	pthread_create(&tid, NULL, p903_receiver, NULL);
	/* Start the Sender thread */
	pthread_create(&tid, NULL, p903_sender, NULL);
	/* Start the Scheduler thread */
	pthread_create(&tid, NULL, p903_scheduler, NULL);

	/* Wait for signal to arrive */
	sigwait(&sigs, &i);
	info("shutting down on signal %s", strsignal(i));
	MHD_stop_daemon(mhd);
	pthread_create(&tid, NULL, p903_saver, NULL);
	pthread_join(tid, &p);
}

Return to:

Send suggestions and report system problems to the System administrator.