File: gotweb.c

package info (click to toggle)
got 0.119-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,448 kB
  • sloc: ansic: 124,378; sh: 50,814; yacc: 4,353; makefile: 2,241; perl: 357
file content (1596 lines) | stat: -rw-r--r-- 37,301 bytes parent folder | download
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
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
/*
 * Copyright (c) 2016, 2019, 2020-2022 Tracey Emery <tracey@traceyemery.net>
 * Copyright (c) 2015 Mike Larkin <mlarkin@openbsd.org>
 * Copyright (c) 2013 David Gwynne <dlg@openbsd.org>
 * Copyright (c) 2013 Florian Obser <florian@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include "got_compat.h"

#include <net/if.h>
#include <netinet/in.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <dirent.h>
#include <errno.h>
#include <event.h>
#include <fcntl.h>
#include <imsg.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <vis.h>

#include "got_error.h"
#include "got_object.h"
#include "got_reference.h"
#include "got_repository.h"
#include "got_path.h"
#include "got_cancel.h"
#include "got_worktree.h"
#include "got_diff.h"
#include "got_commit_graph.h"
#include "got_blame.h"
#include "got_privsep.h"

#include "gotwebd.h"
#include "log.h"
#include "tmpl.h"

static int gotweb_render_index(struct template *);
static const struct got_error *gotweb_load_got_path(struct repo_dir **,
    const char *, struct request *);
static const struct got_error *gotweb_load_file(char **, const char *,
    const char *, int);
static const struct got_error *gotweb_get_repo_description(char **,
    struct server *, const char *, int);
static const struct got_error *gotweb_get_clone_url(char **, struct server *,
    const char *, int);

static void gotweb_free_repo_dir(struct repo_dir *);

int
gotweb_reply(struct request *c, int status, const char *ctype,
    struct gotweb_url *location)
{
	const char	*csp;

	if (status != 200 && tp_writef(c->tp, "Status: %d\r\n", status) == -1)
		return -1;

	if (location) {
		if (tp_writes(c->tp, "Location: ") == -1 ||
		    gotweb_render_absolute_url(c, location) == -1 ||
		    tp_writes(c->tp, "\r\n") == -1)
			return -1;
	}

	csp = "Content-Security-Policy: default-src 'self'; "
	    "script-src 'none'; object-src 'none';\r\n";
	if (tp_writes(c->tp, csp) == -1)
		return -1;

	if (ctype && tp_writef(c->tp, "Content-Type: %s\r\n", ctype) == -1)
		return -1;

	return tp_writes(c->tp, "\r\n");
}

static int
gotweb_reply_file(struct request *c, const char *ctype, const char *file,
    const char *suffix)
{
	int r;

	r = tp_writef(c->tp, "Content-Disposition: attachment; "
	    "filename=%s%s\r\n", file, suffix ? suffix : "");
	if (r == -1)
		return -1;
	return gotweb_reply(c, 200, ctype, NULL);
}

static struct socket *
gotweb_get_socket(int sock_id)
{
	struct socket *sock;

	TAILQ_FOREACH(sock, &gotwebd_env->sockets, entry) {
		if (sock->conf.id == sock_id)
			return sock;
	}

	return NULL;
}

static void
cleanup_request(struct request *c)
{
	uint32_t request_id = c->request_id;

	fcgi_cleanup_request(c);

	if (imsg_compose_event(gotwebd_env->iev_auth, GOTWEBD_IMSG_REQ_ABORT,
	    GOTWEBD_PROC_GOTWEB, -1, -1, &request_id, sizeof(request_id)) == -1)
		log_warn("imsg_compose_event");
}

static struct request *
recv_request(struct imsg *imsg)
{
	const struct got_error *error;
	struct request *c;
	struct server *srv;
	size_t datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
	int fd = -1;
	uint8_t *outbuf = NULL;

	if (datalen != sizeof(*c)) {
		log_warnx("bad request size received over imsg");
		return NULL;
	}

	fd = imsg_get_fd(imsg);
	if (fd == -1) {
		log_warnx("no client file descriptor");
		return NULL;
	}

	c = calloc(1, sizeof(*c));
	if (c == NULL) {
		log_warn("calloc");
		return NULL;
	}

	outbuf = calloc(1, GOTWEBD_CACHESIZE);
	if (outbuf == NULL) {
		log_warn("calloc");
		free(c);
		return NULL;
	}

	memcpy(c, imsg->data, sizeof(*c));

	/* Non-NULL pointers, if any, are not from our address space. */
	c->sock = NULL;
	c->srv = NULL;
	c->t = NULL;
	c->tp = NULL;
	c->buf = NULL;
	c->outbuf = outbuf;

	memset(&c->ev, 0, sizeof(c->ev));
	memset(&c->tmo, 0, sizeof(c->tmo));

	/* Use our own temporary file descriptors. */
	memcpy(c->priv_fd, gotwebd_env->priv_fd, sizeof(c->priv_fd));

	c->fd = fd;

	c->tp = template(c, fcgi_write, c->outbuf, GOTWEBD_CACHESIZE);
	if (c->tp == NULL) {
		log_warn("gotweb init template");
		cleanup_request(c);
		return NULL;
	}

	c->sock = gotweb_get_socket(c->sock_id);
	if (c->sock == NULL) {
		log_warn("socket id '%d' not found", c->sock_id);
		cleanup_request(c);
		return NULL;
	}

	/* init the transport */
	error = gotweb_init_transport(&c->t);
	if (error) {
		log_warnx("gotweb init transport: %s", error->msg);
		cleanup_request(c);
		return NULL;
	}

	/* get the gotwebd server */
	srv = gotweb_get_server(c->fcgi_params.server_name);
	if (srv == NULL) {
		log_warnx("server '%s' not found", c->fcgi_params.server_name);
		cleanup_request(c);
		return NULL;
	}
	c->srv = srv;

	return c;
}

int
gotweb_process_request(struct request *c)
{
	const struct got_error *error = NULL;
	struct server *srv = c->srv;;
	struct querystring *qs = NULL;
	struct repo_dir *repo_dir = NULL;
	struct repo_commit *commit;
	const char *rss_ctype = "application/rss+xml;charset=utf-8";
	const uint8_t *buf;
	size_t len;
	int r, binary = 0;

	/* querystring */
	qs = &c->fcgi_params.qs;
	c->t->qs = qs;

	/* Log the request. */
	if (gotwebd_env->gotwebd_verbose > 0) {
		struct gotwebd_fcgi_params *p = &c->fcgi_params;
		char *server_name = NULL;
		char *document_uri = NULL;
		const char *action_name = NULL;

		if (p->server_name[0] &&
		    stravis(&server_name, p->server_name, VIS_SAFE) == -1) {
			log_warn("stravis");
			server_name = NULL;
		}

		if (p->document_uri[0] &&
		    stravis(&document_uri, p->document_uri, VIS_SAFE) == -1) {
			log_warn("stravis");
			document_uri = NULL;
		}

		action_name = gotweb_action_name(qs->action);
		log_info("processing request: server='%s' action='%s' "
		    "commit='%s', file='%s', folder='%s', headref='%s' "
		    "index_page=%d path='%s' document_uri='%s'",
		    server_name ? server_name : "",
		    action_name ? action_name : "",
		    qs->commit,
		    qs->file,
		    qs->folder,
		    qs->headref,
		    qs->index_page,
		    qs->path,
		    document_uri ? document_uri : "");
		free(server_name);
		free(document_uri);
	}

	/*
	 * certain actions require a commit id in the querystring. this stops
	 * bad actors from exploiting this by manually manipulating the
	 * querystring.
	 */

	if (qs->action == BLAME || qs->action == BLOB ||
	    qs->action == BLOBRAW || qs->action == DIFF ||
	    qs->action == PATCH) {
		if (qs->commit[0] == '\0') {
			error = got_error(GOT_ERR_BAD_QUERYSTRING);
			goto err;
		}
	}

	if (qs->action != INDEX) {
		if (qs->path[0] == '\0') {
			error = got_error(GOT_ERR_BAD_QUERYSTRING);
			goto err;
		}

		error = gotweb_load_got_path(&repo_dir, qs->path, c);
		c->t->repo_dir = repo_dir;
		if (error)
			goto err;
	}

	if (qs->action == BLOBRAW || qs->action == BLOB) {
		if (qs->folder[0] == '\0' || qs->file[0] == '\0') {
			error = got_error(GOT_ERR_BAD_QUERYSTRING);
			goto err;
		}

		error = got_get_repo_commits(c, 1);
		if (error)
			goto err;

		error = got_open_blob_for_output(&c->t->blob, &c->t->fd,
		    &binary, c, qs->folder, qs->file, qs->commit);
		if (error)
			goto err;
	}

	switch (qs->action) {
	case BLAME:
		if (qs->folder[0] == '\0' || qs->file[0] == '\0') {
			error = got_error(GOT_ERR_BAD_QUERYSTRING);
			goto err;
		}
		error = got_get_repo_commits(c, 1);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_blame);
	case BLOB:
		if (binary) {
			struct gotweb_url url = {
				.index_page = -1,
				.action = BLOBRAW,
				.path = qs->path[0] ? qs->path : NULL,
				.commit = qs->commit[0] ? qs->commit : NULL,
				.folder = qs->folder[0] ? qs->folder : NULL,
				.file = qs->file[0] ? qs->file : NULL,
			};

			return gotweb_reply(c, 302, NULL, &url);
		}

		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_blob);
	case BLOBRAW:
		if (binary)
			r = gotweb_reply_file(c, "application/octet-stream",
			    qs->file, NULL);
		else
			r = gotweb_reply(c, 200, "text/plain", NULL);
		if (r == -1)
			return -1;
		if (template_flush(c->tp) == -1)
			return -1;

		for (;;) {
			error = got_object_blob_read_block(&len, c->t->blob);
			if (error)
				break;
			if (len == 0)
				break;
			buf = got_object_blob_get_read_buf(c->t->blob);
			if (fcgi_write(c, buf, len) == -1)
				return -1;
		}
		return 0;
	case BRIEFS:
		error = got_get_repo_commits(c, srv->max_commits_display);
		if (error)
			goto err;
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_briefs);
	case COMMITS:
		error = got_get_repo_commits(c, srv->max_commits_display);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_commits);
	case DIFF:
		error = got_get_repo_commits(c, 1);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		error = got_open_diff_for_output(&c->t->fp, c);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_diff);
	case INDEX:
		c->t->nrepos = scandir(srv->repos_path, &c->t->repos, NULL,
		    alphasort);
		if (c->t->nrepos == -1) {
			c->t->repos = NULL;
			error = got_error_from_errno2("scandir",
			    srv->repos_path);
			goto err;
		}
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_index);
	case PATCH:
		error = got_get_repo_commits(c, 1);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		error = got_open_diff_for_output(&c->t->fp, c);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		if (gotweb_reply(c, 200, "text/plain", NULL) == -1)
			return -1;
		return gotweb_render_patch(c->tp);
	case RSS:
		error = got_get_repo_tags(c, D_MAXSLCOMMDISP);
		if (error)
			goto err;
		if (gotweb_reply_file(c, rss_ctype, repo_dir->name, ".rss")
		    == -1)
			return -1;
		return gotweb_render_rss(c->tp);
	case SUMMARY:
		error = got_ref_list(&c->t->refs, c->t->repo, "refs/heads",
		    got_ref_cmp_by_name, NULL);
		if (error) {
			log_warnx("%s: got_ref_list: %s", __func__,
			    error->msg);
			goto err;
		}
		error = got_get_repo_commits(c, srv->summary_commits_display);
		if (error)
			goto err;
		qs->action = TAGS;
		error = got_get_repo_tags(c, srv->summary_tags_display);
		if (error) {
			log_warnx("%s: got_get_repo_tags: %s", __func__,
			    error->msg);
			goto err;
		}
		qs->action = SUMMARY;
		commit = TAILQ_FIRST(&c->t->repo_commits);
		if (commit && qs->commit[0] == '\0') {
			if (strlcpy(qs->commit, commit->commit_id,
			    sizeof(qs->commit)) >= sizeof(qs->commit)) {
				error = got_error_msg(GOT_ERR_NO_SPACE,
				    "commit ID too long");
				log_warn("%s: %s", __func__, error->msg);
				goto err;
			}
		}
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_summary);
	case TAG:
		error = got_get_repo_tags(c, 1);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		if (TAILQ_EMPTY(&c->t->repo_tags)) {
			error = got_error_msg(GOT_ERR_BAD_OBJ_ID,
			    "bad commit id");
			goto err;
		}
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_tag);
	case TAGS:
		error = got_get_repo_tags(c, srv->max_commits_display);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_tags);
	case TREE:
		error = got_get_repo_commits(c, 1);
		if (error) {
			log_warnx("%s: %s", __func__, error->msg);
			goto err;
		}
		if (gotweb_reply(c, 200, "text/html", NULL) == -1)
			return -1;
		return gotweb_render_page(c->tp, gotweb_render_tree);
	case ERR:
	default:
		error = got_error(GOT_ERR_BAD_QUERYSTRING);
	}

err:
	c->t->error = error;
	if (gotweb_reply(c, 400, "text/html", NULL) == -1)
		return -1;
	return gotweb_render_page(c->tp, gotweb_render_error);
}

struct server *
gotweb_get_server(const char *server_name)
{
	struct server *srv;

	/* check against the server name first */
	if (*server_name != '\0')
		TAILQ_FOREACH(srv, &gotwebd_env->servers, entry)
			if (strcmp(srv->name, server_name) == 0)
				return srv;

	/* otherwise, use the first server */
	return TAILQ_FIRST(&gotwebd_env->servers);
};

const struct got_error *
gotweb_init_transport(struct transport **t)
{
	const struct got_error *error = NULL;

	*t = calloc(1, sizeof(**t));
	if (*t == NULL)
		return got_error_from_errno2(__func__, "calloc");

	TAILQ_INIT(&(*t)->repo_commits);
	TAILQ_INIT(&(*t)->repo_tags);
	TAILQ_INIT(&(*t)->refs);

	(*t)->fd = -1;

	return error;
}

struct gotwebd_repo *
gotweb_get_repository(struct server *server, const char *name)
{
	struct gotwebd_repo *repo;

	TAILQ_FOREACH(repo, &server->repos, entry) {
		if (strncmp(repo->name, name, strlen(repo->name)) != 0)
			continue;
	
		if (strlen(name) == strlen(repo->name))
			return repo;

		if (strlen(name) != strlen(repo->name) + 4)
			continue;

		if (strcmp(name + strlen(repo->name), ".git") == 0)
			return repo;
	}

	return NULL;
}

void
gotweb_free_repo_tag(struct repo_tag *rt)
{
	if (rt != NULL) {
		free(rt->commit_id);
		free(rt->tag_name);
		free(rt->tag_commit);
		free(rt->commit_msg);
		free(rt->tagger);
	}
	free(rt);
}

void
gotweb_free_repo_commit(struct repo_commit *rc)
{
	if (rc != NULL) {
		free(rc->path);
		free(rc->refs_str);
		free(rc->commit_id);
		free(rc->parent_id);
		free(rc->tree_id);
		free(rc->author);
		free(rc->committer);
		free(rc->commit_msg);
	}
	free(rc);
}

static void
gotweb_free_repo_dir(struct repo_dir *repo_dir)
{
	if (repo_dir != NULL) {
		free(repo_dir->name);
		free(repo_dir->owner);
		free(repo_dir->description);
		free(repo_dir->url);
		free(repo_dir->path);
	}
	free(repo_dir);
}

void
gotweb_free_transport(struct transport *t)
{
	const struct got_error *err;
	struct repo_commit *rc = NULL, *trc = NULL;
	struct repo_tag *rt = NULL, *trt = NULL;
	int i;

	got_ref_list_free(&t->refs);
	TAILQ_FOREACH_SAFE(rc, &t->repo_commits, entry, trc) {
		TAILQ_REMOVE(&t->repo_commits, rc, entry);
		gotweb_free_repo_commit(rc);
	}
	TAILQ_FOREACH_SAFE(rt, &t->repo_tags, entry, trt) {
		TAILQ_REMOVE(&t->repo_tags, rt, entry);
		gotweb_free_repo_tag(rt);
	}
	gotweb_free_repo_dir(t->repo_dir);
	t->qs = NULL;
	free(t->more_id);
	free(t->tags_more_id);
	if (t->blob)
		got_object_blob_close(t->blob);
	if (t->fp) {
		err = got_gotweb_closefile(t->fp);
		if (err)
			log_warnx("%s: got_gotweb_closefile failure: %s",
			    __func__, err->msg);
	}
	if (t->fd != -1 && close(t->fd) == -1)
		log_warn("%s: close", __func__);
	if (t->repos) {
		for (i = 0; i < t->nrepos; ++i)
			free(t->repos[i]);
		free(t->repos);
	}
	if (t->repo)
		got_repo_close(t->repo);
	free(t);
}

void
gotweb_index_navs(struct request *c, struct gotweb_url *prev, int *have_prev,
    struct gotweb_url *next, int *have_next)
{
	struct transport *t = c->t;
	const struct querystring *qs = t->qs;
	struct server *srv = c->srv;

	*have_prev = *have_next = 0;

	if (qs->index_page > 0) {
		*have_prev = 1;
		*prev = (struct gotweb_url){
			.action = -1,
			.index_page = qs->index_page - 1,
		};
	}
	if (t->next_disp == srv->max_repos_display &&
	    t->repos_total != (qs->index_page + 1) *
	    srv->max_repos_display) {
		*have_next = 1;
		*next = (struct gotweb_url){
			.action = -1,
			.index_page = qs->index_page + 1,
		};
	}
}

static int
gotweb_render_index(struct template *tp)
{
	const struct got_error *error = NULL;
	struct request *c = tp->tp_arg;
	struct server *srv = c->srv;
	struct transport *t = c->t;
	const struct querystring *qs = t->qs;
	struct repo_dir *repo_dir = NULL;
	struct dirent **sd_dent = t->repos;
	unsigned int d_i, d_disp = 0;
	unsigned int d_skipped = 0;
	int type, r;

	if (gotweb_render_repo_table_hdr(c->tp) == -1)
		return -1;

	for (d_i = 0; d_i < t->nrepos; d_i++) {
		if (strcmp(sd_dent[d_i]->d_name, ".") == 0 ||
		    strcmp(sd_dent[d_i]->d_name, "..") == 0) {
			d_skipped++;
			continue;
		}

		error = got_path_dirent_type(&type, srv->repos_path,
		    sd_dent[d_i]);
		if (error)
			continue;
		if (type != DT_DIR) {
			d_skipped++;
			continue;
		}

		if (qs->index_page > 0 && (qs->index_page *
		    srv->max_repos_display) > t->prev_disp) {
			t->prev_disp++;
			continue;
		}

		error = gotweb_load_got_path(&repo_dir, sd_dent[d_i]->d_name,
		    c);
		if (error) {
			if (error->code != GOT_ERR_NOT_GIT_REPO)
				log_warnx("%s: %s: %s", __func__,
				    sd_dent[d_i]->d_name, error->msg);
			gotweb_free_repo_dir(repo_dir);
			repo_dir = NULL;
			d_skipped++;
			continue;
		}

		d_disp++;
		t->prev_disp++;

		r = gotweb_render_repo_fragment(c->tp, repo_dir);
		gotweb_free_repo_dir(repo_dir);
		repo_dir = NULL;
		got_repo_close(t->repo);
		t->repo = NULL;
		if (r == -1)
			return -1;

		t->next_disp++;
		if (d_disp == srv->max_repos_display)
			break;
	}
	t->repos_total = t->nrepos - d_skipped;

	if (srv->max_repos_display == 0 ||
	    t->repos_total <= srv->max_repos_display)
		return 0;

	if (gotweb_render_navs(c->tp) == -1)
		return -1;

	return 0;
}

static inline int
should_urlencode(int c)
{
	if (c <= ' ' || c >= 127)
		return 1;

	switch (c) {
		/* gen-delim */
	case ':':
	case '/':
	case '?':
	case '#':
	case '[':
	case ']':
	case '@':
		/* sub-delims */
	case '!':
	case '$':
	case '&':
	case '\'':
	case '(':
	case ')':
	case '*':
	case '+':
	case ',':
	case ';':
	case '=':
		/* needed because the URLs are embedded into the HTML */
	case '\"':
		return 1;
	default:
		return 0;
	}
}

static char *
gotweb_urlencode(const char *str)
{
	const char *s;
	char *escaped;
	size_t i, len;
	int a, b;

	len = 0;
	for (s = str; *s; ++s) {
		len++;
		if (should_urlencode(*s))
			len += 2;
	}

	escaped = calloc(1, len + 1);
	if (escaped == NULL)
		return NULL;

	i = 0;
	for (s = str; *s; ++s) {
		if (should_urlencode(*s)) {
			a = (*s & 0xF0) >> 4;
			b = (*s & 0x0F);

			escaped[i++] = '%';
			escaped[i++] = a <= 9 ? ('0' + a) : ('7' + a);
			escaped[i++] = b <= 9 ? ('0' + b) : ('7' + b);
		} else
			escaped[i++] = *s;
	}

	return escaped;
}

const char *
gotweb_action_name(int action)
{
	switch (action) {
	case NO_ACTION:
		return "no action";
	case BLAME:
		return "blame";
	case BLOB:
		return "blob";
	case BLOBRAW:
		return "blobraw";
	case BRIEFS:
		return "briefs";
	case COMMITS:
		return "commits";
	case DIFF:
		return "diff";
	case ERR:
		return "err";
	case INDEX:
		return "index";
	case PATCH:
		return "patch";
	case SUMMARY:
		return "summary";
	case TAG:
		return "tag";
	case TAGS:
		return "tags";
	case TREE:
		return "tree";
	case RSS:
		return "rss";
	default:
		return NULL;
	}
}

int
gotweb_render_url(struct request *c, struct gotweb_url *url)
{
	const char *sep = "?", *action;
	char *tmp;
	int r;

	action = gotweb_action_name(url->action);
	if (action != NULL) {
		if (tp_writef(c->tp, "?action=%s", action) == -1)
			return -1;
		sep = "&";
	}

	if (url->commit) {
		if (tp_writef(c->tp, "%scommit=%s", sep, url->commit) == -1)
			return -1;
		sep = "&";
	}

	if (url->file) {
		tmp = gotweb_urlencode(url->file);
		if (tmp == NULL)
			return -1;
		r = tp_writef(c->tp, "%sfile=%s", sep, tmp);
		free(tmp);
		if (r == -1)
			return -1;
		sep = "&";
	}

	if (url->folder) {
		if (got_path_is_root_dir(url->folder))
			tmp = NULL;
		else {
			tmp = gotweb_urlencode(url->folder);
			if (tmp == NULL)
				return -1;
		}
		r = tp_writef(c->tp, "%sfolder=%s", sep, tmp ? tmp : "");
		free(tmp);
		if (r == -1)
			return -1;
		sep = "&";
	}

	if (url->headref) {
		tmp = gotweb_urlencode(url->headref);
		if (tmp == NULL)
			return -1;
		r = tp_writef(c->tp, "%sheadref=%s", sep, url->headref);
		free(tmp);
		if (r == -1)
			return -1;
		sep = "&";
	}

	if (url->index_page != -1) {
		if (tp_writef(c->tp, "%sindex_page=%d", sep,
		    url->index_page) == -1)
			return -1;
		sep = "&";
	}

	if (url->path) {
		tmp = gotweb_urlencode(url->path);
		if (tmp == NULL)
			return -1;
		r = tp_writef(c->tp, "%spath=%s", sep, tmp);
		free(tmp);
		if (r == -1)
			return -1;
		sep = "&";
	}

	return 0;
}

int
gotweb_render_absolute_url(struct request *c, struct gotweb_url *url)
{
	struct template	*tp = c->tp;
	struct gotwebd_fcgi_params *p = &c->fcgi_params;
	const char	*proto = p->https ? "https" : "http";

	if (tp_writes(tp, proto) == -1 ||
	    tp_writes(tp, "://") == -1 ||
	    tp_htmlescape(tp, p->server_name) == -1 ||
	    tp_htmlescape(tp, p->document_uri) == -1)
		return -1;

	return gotweb_render_url(c, url);
}

/* 
 * Ensure that a path sent in the request will not escape from the given
 * parent directory. This matters for got-portable where we are not
 * necessarily running in chroot and cannot be protected by unveil(2).
 */
static const struct got_error *
validate_path(const char *path, const char *parent_path,
    const char *orig_path)
{
	const struct got_error *error = NULL;
	char *abspath;

	abspath = realpath(path, NULL);
	if (abspath == NULL) {
		/* Paths which cannot be resolved are safe. */
		if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
			return NULL;
		return got_error_from_errno("realpath");
	}

	if (!got_path_is_child(abspath, parent_path, strlen(parent_path)))
		error = got_error_path(orig_path, GOT_ERR_NOT_GIT_REPO);

	free(abspath);
	return error;
}

static enum gotwebd_access
auth_check(struct request *c, struct gotwebd_access_rule_list *rules)
{
	struct gotwebd *env = gotwebd_env;
	enum gotwebd_access access = GOTWEBD_ACCESS_NO_MATCH;
	struct gotwebd_access_rule *rule;

	/*
	 * The www user ID implies that no user authentication occurred.
	 * But authentication is enabled so we must deny this request.
	 */
	if (c->client_uid == env->www_uid)
		return GOTWEBD_ACCESS_DENIED;

	/*
	 * We cannot access /etc/passwd in this process so we cannot
	 * verify the client's user ID outselves here.
	 * Match rules against the access identifier which has already
	 * passed authentication in the auth process.
	 */
	STAILQ_FOREACH(rule, rules, entry) {
		if (strcmp(rule->identifier, c->access_identifier) == 0)
			access = rule->access;
	}

	return access;
}

static const struct got_error *
gotweb_load_got_path(struct repo_dir **rp, const char *dir,
    struct request *c)
{
	const struct got_error *error = NULL;
	struct gotwebd *env = gotwebd_env;
	struct server *srv = c->srv;
	struct transport *t = c->t;
	struct repo_dir *repo_dir;
	DIR *dt;
	char *dir_test;
	struct gotwebd_repo *repo;
	enum gotwebd_auth_config auth_config = 0;
	enum gotwebd_access access = GOTWEBD_ACCESS_DENIED;

	*rp = calloc(1, sizeof(**rp));
	if (*rp == NULL)
		return got_error_from_errno("calloc");
	repo_dir = *rp;

	if (asprintf(&dir_test, "%s/%s/%s", srv->repos_path, dir,
	    GOTWEB_GIT_DIR) == -1)
		return got_error_from_errno("asprintf");

	error = validate_path(dir_test, srv->repos_path, dir);
	if (error) {
		free(dir_test);
		return error;
	}

	dt = opendir(dir_test);
	if (dt == NULL) {
		free(dir_test);
		if (asprintf(&dir_test, "%s/%s", srv->repos_path, dir) == -1)
			return got_error_from_errno("asprintf");
		dt = opendir(dir_test);
		if (dt == NULL) {
			free(dir_test);
			if (asprintf(&dir_test, "%s/%s%s", srv->repos_path,
			    dir, GOTWEB_GIT_DIR) == -1)
				return got_error_from_errno("asprintf");
			dt = opendir(dir_test);
			if (dt == NULL) {
				free(dir_test);
				return got_error_path(dir,
				    GOT_ERR_NOT_GIT_REPO);
			}
		}
	}

	repo_dir->path = dir_test;
	dir_test = NULL;

	error = got_path_basename(&repo_dir->name, repo_dir->path);
	if (error)
		goto err;

	repo = gotweb_get_repository(srv, repo_dir->name);
	if (repo) {
		auth_config = repo->auth_config;
		switch (auth_config) {
		case GOTWEBD_AUTH_DISABLED:
			access = GOTWEBD_ACCESS_PERMITTED;
			break;
		case GOTWEBD_AUTH_SECURE:
		case GOTWEBD_AUTH_INSECURE:
			access = auth_check(c, &repo->access_rules);
			if (access == GOTWEBD_ACCESS_NO_MATCH)
				access = auth_check(c, &srv->access_rules);
			if (access == GOTWEBD_ACCESS_NO_MATCH)
				access = auth_check(c, &env->access_rules);
			if (access == GOTWEBD_ACCESS_NO_MATCH)
				access = GOTWEBD_ACCESS_DENIED;
			break;
		}
	} else {
		auth_config = srv->auth_config;
		switch (auth_config) {
		case GOTWEBD_AUTH_DISABLED:
			access = GOTWEBD_ACCESS_PERMITTED;
			break;
		case GOTWEBD_AUTH_SECURE:
		case GOTWEBD_AUTH_INSECURE:
			access = auth_check(c, &srv->access_rules);
			if (access == GOTWEBD_ACCESS_NO_MATCH)
				access = auth_check(c, &env->access_rules);
			if (access == GOTWEBD_ACCESS_NO_MATCH)
				access = GOTWEBD_ACCESS_DENIED;
			break;
		}
	}

	if (access != GOTWEBD_ACCESS_PERMITTED &&
	    access != GOTWEBD_ACCESS_DENIED)
		fatalx("invalid access check result %d", access);

	if (access != GOTWEBD_ACCESS_PERMITTED) {
		error = got_error_path(repo_dir->name, GOT_ERR_NOT_GIT_REPO);
		goto err;
	}

	if (srv->respect_exportok &&
	    faccessat(dirfd(dt), "git-daemon-export-ok", F_OK, 0) == -1) {
		error = got_error_path(repo_dir->name, GOT_ERR_NOT_GIT_REPO);
		goto err;
	}

	error = got_repo_open(&t->repo, repo_dir->path, NULL,
	    gotwebd_env->pack_fds);
	if (error)
		goto err;
	error = gotweb_get_repo_description(&repo_dir->description, srv,
	    repo_dir->path, dirfd(dt));
	if (error)
		goto err;
	if (srv->show_repo_owner) {
		error = gotweb_load_file(&repo_dir->owner, repo_dir->path,
		    "owner", dirfd(dt));
		if (error)
			goto err;
		if (repo_dir->owner == NULL) {
			error = got_get_repo_owner(&repo_dir->owner, c);
			if (error)
				goto err;
		}
	}
	if (srv->show_repo_age) {
		error = got_get_repo_age(&repo_dir->age, c, NULL);
		if (error)
			goto err;
	}
	error = gotweb_get_clone_url(&repo_dir->url, srv, repo_dir->path,
	    dirfd(dt));
err:
	free(dir_test);
	if (dt != NULL && closedir(dt) == EOF && error == NULL)
		error = got_error_from_errno("closedir");
	if (error && t->repo) {
		got_repo_close(t->repo);
		t->repo = NULL;
	}
	return error;
}

static const struct got_error *
gotweb_load_file(char **str, const char *dir, const char *file, int dirfd)
{
	const struct got_error *error = NULL;
	struct stat sb;
	off_t len;
	int fd;

	*str = NULL;

	fd = openat(dirfd, file, O_RDONLY);
	if (fd == -1) {
		if (errno == ENOENT || errno == EACCES)
			return NULL;
		return got_error_from_errno_fmt("openat %s/%s", dir, file);
	}

	if (fstat(fd, &sb) == -1) {
		error = got_error_from_errno_fmt("fstat %s/%s", dir, file);
		goto done;
	}

	len = sb.st_size;
	if (len > GOTWEBD_MAXDESCRSZ - 1)
		len = GOTWEBD_MAXDESCRSZ - 1;

	*str = calloc(len + 1, 1);
	if (*str == NULL) {
		error = got_error_from_errno("calloc");
		goto done;
	}

	if (read(fd, *str, len) == -1)
		error = got_error_from_errno("read");
 done:
	if (fd != -1 && close(fd) == -1 && error == NULL)
		error = got_error_from_errno("close");
	return error;
}

static const struct got_error *
gotweb_get_repo_description(char **description, struct server *srv,
    const char *dirpath, int dir)
{
	*description = NULL;
	if (srv->show_repo_description == 0)
		return NULL;

	return gotweb_load_file(description, dirpath, "description", dir);
}

static const struct got_error *
gotweb_get_clone_url(char **url, struct server *srv, const char *dirpath,
    int dir)
{
	*url = NULL;
	if (srv->show_repo_cloneurl == 0)
		return NULL;

	return gotweb_load_file(url, dirpath, "cloneurl", dir);
}

int
gotweb_render_age(struct template *tp, time_t committer_time)
{
	struct request *c = tp->tp_arg;
	long long diff_time;
	const char *years = "years ago", *months = "months ago";
	const char *weeks = "weeks ago", *days = "days ago";
	const char *hours = "hours ago",  *minutes = "minutes ago";
	const char *seconds = "seconds ago", *now = "right now";

	diff_time = time(NULL) - committer_time;
	if (diff_time > 60 * 60 * 24 * 365 * 2) {
		if (tp_writef(c->tp, "%lld %s",
		    (diff_time / 60 / 60 / 24 / 365), years) == -1)
			return -1;
	} else if (diff_time > 60 * 60 * 24 * (365 / 12) * 2) {
		if (tp_writef(c->tp, "%lld %s",
		    (diff_time / 60 / 60 / 24 / (365 / 12)),
		    months) == -1)
			return -1;
	} else if (diff_time > 60 * 60 * 24 * 7 * 2) {
		if (tp_writef(c->tp, "%lld %s",
		    (diff_time / 60 / 60 / 24 / 7), weeks) == -1)
			return -1;
	} else if (diff_time > 60 * 60 * 24 * 2) {
		if (tp_writef(c->tp, "%lld %s",
		    (diff_time / 60 / 60 / 24), days) == -1)
			return -1;
	} else if (diff_time > 60 * 60 * 2) {
		if (tp_writef(c->tp, "%lld %s",
		    (diff_time / 60 / 60), hours) == -1)
			return -1;
	} else if (diff_time > 60 * 2) {
		if (tp_writef(c->tp, "%lld %s", (diff_time / 60),
		    minutes) == -1)
			return -1;
	} else if (diff_time > 2) {
		if (tp_writef(c->tp, "%lld %s", diff_time,
		    seconds) == -1)
			return -1;
	} else {
		if (tp_writes(tp, now) == -1)
			return -1;
	}
	return 0;
}

static void
gotweb_shutdown(void)
{
	imsgbuf_clear(&gotwebd_env->iev_parent->ibuf);
	free(gotwebd_env->iev_parent);

	imsgbuf_clear(&gotwebd_env->iev_auth->ibuf);
	free(gotwebd_env->iev_auth);

	config_free_access_rules(&gotwebd_env->access_rules);

	while (!TAILQ_EMPTY(&gotwebd_env->servers)) {
		struct server *srv;

		srv = TAILQ_FIRST(&gotwebd_env->servers);
		TAILQ_REMOVE(&gotwebd_env->servers, srv, entry);

		config_free_access_rules(&srv->access_rules);
		config_free_repos(&srv->repos);
		free(srv);
	}

	while (!TAILQ_EMPTY(&gotwebd_env->sockets)) {
		struct socket *sock;

		sock = TAILQ_FIRST(&gotwebd_env->sockets);
		TAILQ_REMOVE(&gotwebd_env->sockets, sock, entry);
		free(sock);
	}

	while (!TAILQ_EMPTY(&gotwebd_env->addresses)) {
		struct address *h;

		h = TAILQ_FIRST(&gotwebd_env->addresses);
		TAILQ_REMOVE(&gotwebd_env->addresses, h, entry);
		free(h);
	}

	free(gotwebd_env);

	exit(0);
}

static void
gotweb_sighdlr(int sig, short event, void *arg)
{
	switch (sig) {
	case SIGHUP:
		log_info("%s: ignoring SIGHUP", __func__);
		break;
	case SIGPIPE:
		log_info("%s: ignoring SIGPIPE", __func__);
		break;
	case SIGUSR1:
		log_info("%s: ignoring SIGUSR1", __func__);
		break;
	case SIGCHLD:
		break;
	case SIGINT:
	case SIGTERM:
		gotweb_shutdown();
		break;
	default:
		log_warn("unhandled signal %d", sig);
	}
}

static void
gotweb_launch(struct gotwebd *env)
{
	struct server *srv;
	const struct got_error *error;

	if (env->iev_auth == NULL)
		fatal("auth process not connected");

#ifndef PROFILE
	if (pledge("stdio rpath recvfd sendfd proc exec unveil", NULL) == -1)
		fatal("pledge");
#endif

	TAILQ_FOREACH(srv, &gotwebd_env->servers, entry) {
		if (unveil(srv->repos_path, "r") == -1)
			fatal("unveil %s", srv->repos_path);
	}

	error = got_privsep_unveil_exec_helpers();
	if (error)
		fatalx("%s", error->msg);

	if (unveil(NULL, NULL) == -1)
		fatal("unveil");

	event_add(&env->iev_auth->ev, NULL);
}

static void
gotweb_dispatch_server(int fd, short event, void *arg)
{
	struct imsgev		*iev = arg;
	struct imsgbuf		*ibuf;
	struct imsg		 imsg;
	struct request		*c;
	ssize_t			 n;
	int			 shut = 0;

	ibuf = &iev->ibuf;

	if (event & EV_READ) {
		if ((n = imsgbuf_read(ibuf)) == -1)
			fatal("imsgbuf_read error");
		if (n == 0)	/* Connection closed */
			shut = 1;
	}
	if (event & EV_WRITE) {
		if (imsgbuf_write(ibuf) == -1)
			fatal("imsgbuf_write");
	}

	for (;;) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			fatal("imsg_get");
		if (n == 0)	/* No more messages. */
			break;

		switch (imsg.hdr.type) {
		case GOTWEBD_IMSG_REQ_PROCESS:
			c = recv_request(&imsg);
			if (c) {
				int request_id = c->request_id;
				if (gotweb_process_request(c) == -1) {
					log_warnx("request %u failed",
					    request_id);
				 } else {
					if (template_flush(c->tp) == -1) {
						log_warn("request %u flush",
						    request_id);
					}
				}

				fcgi_create_end_record(c);
				cleanup_request(c);
			}
			break;
		default:
			fatalx("%s: unknown imsg type %d", __func__,
			    imsg.hdr.type);
		}

		imsg_free(&imsg);
	}

	if (!shut)
		imsg_event_add(iev);
	else {
		/* This pipe is dead.  Remove its event handler */
		event_del(&iev->ev);
		event_loopexit(NULL);
	}
}

static void
recv_auth_pipe(struct gotwebd *env, struct imsg *imsg)
{
	struct imsgev *iev;
	int fd;

	if (env->iev_auth != NULL)
		fatalx("auth process already connected");

	fd = imsg_get_fd(imsg);
	if (fd == -1)
		fatalx("invalid auth pipe fd");

	iev = calloc(1, sizeof(*iev));
	if (iev == NULL)
		fatal("calloc");
	if (imsgbuf_init(&iev->ibuf, fd) == -1)
		fatal("imsgbuf_init");
	imsgbuf_allow_fdpass(&iev->ibuf);

	iev->handler = gotweb_dispatch_server;
	iev->data = iev;
	event_set(&iev->ev, fd, EV_READ, gotweb_dispatch_server, iev);
	imsg_event_add(iev);

	env->iev_auth = iev;
}

static void
gotweb_dispatch_main(int fd, short event, void *arg)
{
	struct imsgev		*iev = arg;
	struct imsgbuf		*ibuf;
	struct imsg		 imsg;
	struct gotwebd		*env = gotwebd_env;
	struct server		*srv;
	struct gotwebd_repo	*repo;
	ssize_t			 n;
	int			 shut = 0;

	ibuf = &iev->ibuf;

	if (event & EV_READ) {
		if ((n = imsgbuf_read(ibuf)) == -1)
			fatal("imsgbuf_read error");
		if (n == 0)	/* Connection closed */
			shut = 1;
	}
	if (event & EV_WRITE) {
		if (imsgbuf_write(ibuf) == -1)
			fatal("imsgbuf_write");
	}

	for (;;) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			fatal("imsg_get");
		if (n == 0)	/* No more messages. */
			break;

		switch (imsg.hdr.type) {
		case GOTWEBD_IMSG_CFG_ACCESS_RULE:
			if (TAILQ_EMPTY(&env->servers)) {
				/* global access rule */
				config_get_access_rule(&env->access_rules,
				    &imsg);
			} else {
				srv = TAILQ_LAST(&env->servers, serverlist);
				if (TAILQ_EMPTY(&srv->repos)) {
					/* per-server access rule */
					config_get_access_rule(
					    &srv->access_rules, &imsg);
				} else {
					/* per-repository access rule */
					repo = TAILQ_LAST(&srv->repos,
					    gotwebd_repolist);
					config_get_access_rule(
					    &repo->access_rules, &imsg);
				}
			}
			break;
		case GOTWEBD_IMSG_CFG_SRV:
			config_getserver(env, &imsg);
			break;
		case GOTWEBD_IMSG_CFG_REPO:
			if (TAILQ_EMPTY(&env->servers))
				fatalx("%s: unexpected CFG_REPO msg", __func__);
			srv = TAILQ_LAST(&env->servers, serverlist);
			config_get_repository(&srv->repos, &imsg);
			break;
		case GOTWEBD_IMSG_CFG_FD:
			config_getfd(env, &imsg);
			break;
		case GOTWEBD_IMSG_CFG_SOCK:
			config_getsock(env, &imsg);
			break;
		case GOTWEBD_IMSG_CFG_DONE:
			config_getcfg(env, &imsg);
			break;
		case GOTWEBD_IMSG_CTL_PIPE:
			recv_auth_pipe(env, &imsg);
			break;
		case GOTWEBD_IMSG_AUTH_CONF:
			if (imsg_get_data(&imsg, &env->auth_config,
			    sizeof(env->auth_config)) == -1)
				fatalx("%s: invalid AUTH_CONF msg", __func__);
			break;
		case GOTWEBD_IMSG_WWW_UID:
			if (imsg_get_data(&imsg, &env->www_uid,
			    sizeof(env->www_uid)) == -1)
				fatalx("%s: invalid WWW_UID msg", __func__);
			break;
		case GOTWEBD_IMSG_CTL_START:
			gotweb_launch(env);
			break;
		default:
			fatalx("%s: unknown imsg type %d", __func__,
			    imsg.hdr.type);
		}

		imsg_free(&imsg);
	}

	if (!shut)
		imsg_event_add(iev);
	else {
		/* This pipe is dead.  Remove its event handler */
		event_del(&iev->ev);
		event_loopexit(NULL);
	}
}

void
gotweb(struct gotwebd *env, int fd)
{
	struct event	 sighup, sigint, sigusr1, sigchld, sigterm;
	struct event_base *evb;

	evb = event_init();

	sockets_rlimit(-1);

	env->iev_parent = calloc(1, sizeof(*env->iev_parent));
	if (env->iev_parent == NULL)
		fatal("calloc");
	if (imsgbuf_init(&env->iev_parent->ibuf, fd) == -1)
		fatal("imsgbuf_init");
	imsgbuf_allow_fdpass(&env->iev_parent->ibuf);
	env->iev_parent->handler = gotweb_dispatch_main;
	env->iev_parent->data = env->iev_parent;
	event_set(&env->iev_parent->ev, fd, EV_READ, gotweb_dispatch_main,
	    env->iev_parent);
	event_add(&env->iev_parent->ev, NULL);

	signal(SIGPIPE, SIG_IGN);

	signal_set(&sighup, SIGHUP, gotweb_sighdlr, env);
	signal_add(&sighup, NULL);
	signal_set(&sigint, SIGINT, gotweb_sighdlr, env);
	signal_add(&sigint, NULL);
	signal_set(&sigusr1, SIGUSR1, gotweb_sighdlr, env);
	signal_add(&sigusr1, NULL);
	signal_set(&sigchld, SIGCHLD, gotweb_sighdlr, env);
	signal_add(&sigchld, NULL);
	signal_set(&sigterm, SIGTERM, gotweb_sighdlr, env);
	signal_add(&sigterm, NULL);

#ifndef PROFILE
	if (pledge("stdio rpath recvfd sendfd proc exec unveil", NULL) == -1)
		fatal("pledge");
#endif
	event_dispatch();
	event_base_free(evb);
	gotweb_shutdown();
}