blob: a112fb2090ed197a0b0065637d523b5f39ac7d2e (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
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
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
/*
 * The output every cgit page has in common. A link from one page to another is
 * built here because only this file knows whether a site addresses a request
 * as a path below a virtual root or as a query string, and the two are spelled
 * differently down to the separator between arguments. The headers, the
 * document head, the header block, the footer, the error page and the age
 * column are here so that a page handler is left with only its own body to
 * produce.
 */

#define USE_THE_REPOSITORY_VARIABLE

#include "cache.h"
#include "cgit.h"
#include "html.h"
#include "shared.h"
#include "submodule-config.h"
#include "ui-shared.h"
#include "ui-snapshot.h"

#define DEFAULT_HTTP_PORT 80

#define SHORT_HASH_LEN 10

// A max-msg-len below this leaves too little of a commit subject to be worth
// truncating, and the ellipsis is paid for out of that same budget.
#define MIN_TRUNCATE_LEN 15
#define ELLIPSIS_LEN 3

// Bounds the breadcrumbs, so that one request cannot turn into an unbounded
// row of links.
#define MAX_CRUMB_LEVELS 15

// cgit_fmt exits the request rather than truncate, so a path is only worked
// into a tab title while it still leaves room to spare in that buffer.
#define MAX_TITLE_PATH_LEN 256

static const char *repo_basename(const char *reponame)
{
	// The result lives in a static buffer, so it is only good until the
	// next call.
	static char buf[1024];
	const char *slash;
	size_t len;
	int last;

	len = strlcpy(buf, reponame, sizeof(buf));
	if (len >= sizeof(buf))
		die("Repository name too long: %s", reponame);
	last = len - 1;
	while (last && buf[last] == '/')
		buf[last--] = '\0';
	if (last >= 3 && starts_with(&buf[last - 3], ".git")) {
		last -= 3;
		buf[last--] = '\0';
	}
	while (last && buf[last] == '/')
		buf[last--] = '\0';
	slash = strrchr(buf, '/');
	if (slash)
		return ++slash;
	return buf;
}

static const char *root_url(void)
{
	if (ctx.cfg.virtual_root)
		return ctx.cfg.virtual_root;
	else
		return ctx.cfg.script_name;
}

static void site_url(const char *page, const char *search, const char *sort, int ofs, int always_root)
{
	const char *delim = "?";

	if (always_root || page)
		html_attr(root_url());
	else {
		char *currenturl = cgit_currenturl();
		html_attr(currenturl);
		free(currenturl);
	}

	if (page) {
		htmlf("?p=%s", page);
		delim = "&";
	}
	if (search) {
		html(delim);
		html("q=");
		html_url_arg(search);
		delim = "&";
	}
	if (sort) {
		html(delim);
		html("s=");
		html_url_arg(sort);
		delim = "&";
	}
	if (ofs) {
		html(delim);
		htmlf("ofs=%d", ofs);
	}
}

/*
 * Write the class of a link, and mark the link as the current one for
 * assistive technology when the class says it is the active tab or the
 * current page of a pager.
 */
static void link_class(const char *class)
{
	if (!class)
		return;
	html(" class='");
	html_attr(class);
	html("'");
	if (!strcmp(class, "active") || !strcmp(class, "current"))
		html(" aria-current='page'");
}

static void site_link(const char *page, const char *name, const char *title,
	const char *class, const char *search, const char *sort, int ofs, int always_root)
{
	html("<a");
	if (title) {
		html(" title='");
		html_attr(title);
		html("'");
	}
	link_class(class);
	html(" href='");
	site_url(page, search, sort, ofs, always_root);
	html("'>");
	html_txt(name);
	html("</a>");
}

/*
 * Open an anchor and write the part of its href naming the repository, the
 * page and the path, leaving the href quote open for the caller to add its own
 * arguments and close. The return is the delimiter to put before the first of
 * those, which is still a question mark unless a query string has been opened.
 */
static const char *repolink(const char *title, const char *class, const char *page,
	const char *head, const char *path)
{
	const char *delim = "?";

	html("<a");
	if (title) {
		html(" title='");
		html_attr(title);
		html("'");
	}
	link_class(class);
	html(" href='");
	if (ctx.cfg.virtual_root) {
		html_url_path(ctx.cfg.virtual_root);
		html_url_path(ctx.repo->url);
		if (ctx.repo->url[strlen(ctx.repo->url) - 1] != '/')
			html("/");
		if (page) {
			html_url_path(page);
			html("/");
			if (path)
				html_url_path(path);
		}
	} else {
		html_url_path(ctx.cfg.script_name);
		html("?url=");
		html_url_arg(ctx.repo->url);
		if (ctx.repo->url[strlen(ctx.repo->url) - 1] != '/')
			html("/");
		if (page) {
			html_url_arg(page);
			html("/");
			if (path)
				html_url_arg(path);
		}
		delim = "&amp;";
	}
	if (head && ctx.repo->defbranch && strcmp(head, ctx.repo->defbranch)) {
		html(delim);
		html("h=");
		html_url_arg(head);
		delim = "&amp;";
	}
	return cgit_fmt("%s", delim);
}

static const char *emit_rev_arg(const char *delim, const char *rev)
{
	if (rev && ctx.qry.head && strcmp(rev, ctx.qry.head)) {
		html(delim);
		html("id=");
		html_url_arg(rev);
		return "&amp;";
	}
	return delim;
}

static void reporevlink(const char *page, const char *name, const char *title,
	const char *class, const char *head, const char *rev, const char *path)
{
	const char *delim;

	delim = repolink(title, class, page, head, path);
	emit_rev_arg(delim, rev);
	html("'>");
	html_txt(name);
	html("</a>");
}

static void emit_diff_args(const char *delim)
{
	if (ctx.qry.difftype) {
		html(delim);
		htmlf("dt=%d", (int)ctx.qry.difftype);
		delim = "&amp;";
	}
	if (ctx.qry.context > 0 && ctx.qry.context != DEFAULT_DIFF_CONTEXT) {
		html(delim);
		html("context=");
		htmlf("%d", ctx.qry.context);
		delim = "&amp;";
	}
	if (ctx.qry.ignorews) {
		html(delim);
		html("ignorews=1");
		delim = "&amp;";
	}
	if (ctx.qry.follow) {
		html(delim);
		html("follow=1");
	}
}

static struct string_list_item *lookup_path(struct string_list *list, const char *path)
{
	struct string_list_item *item;

	while (path && path[0]) {
		if ((item = string_list_lookup(list, path)))
			return item;
		if (!(path = strchr(path, '/')))
			break;
		path++;
	}
	return NULL;
}

/*
 * A repository can supply the module-link template through a repo-local
 * cgitrc, so the %s placeholders are expanded here instead of the template
 * being handed to printf, where a surplus conversion would read past the
 * argument list.
 */
static void emit_module_link(const char *tmpl, const char **args, int nargs)
{
	struct strbuf sb = STRBUF_INIT;
	int used = 0;

	while (*tmpl) {
		if (*tmpl != '%') {
			strbuf_addch(&sb, *tmpl++);
			continue;
		}
		tmpl++;
		if (*tmpl == '%') {
			strbuf_addch(&sb, '%');
			tmpl++;
		} else if (*tmpl == 's' && used < nargs) {
			strbuf_addstr(&sb, args[used++]);
			tmpl++;
		} else {
			strbuf_addch(&sb, '%');
		}
	}
	html_attr(sb.buf);
	strbuf_release(&sb);
}

static struct date_mode configured_date_mode(void)
{
	struct date_mode mode = ctx.cfg.date_mode;

	if (ctx.cfg.local_time)
		mode.local = 1;
	return mode;
}

/*
 * Dates render as time elements, whose datetime attribute wants the strict
 * ISO 8601 form with the T separator rather than the space git prints by
 * default.
 */
static void print_abs_date(time_t t, int tz)
{
	html("<time datetime='");
	html_attr(show_date(t, tz, cgit_date_mode(DATE_ISO8601_STRICT)));
	html("' title='");
	html_attr(show_date(t, tz, cgit_date_mode(DATE_ISO8601)));
	html("'>");
	html_txt(show_date(t, tz, configured_date_mode()));
	html("</time>");
}

static void print_rel_date(time_t t, int tz, double count, const char *class, const char *suffix)
{
	htmlf("<time class='%s' datetime='", class);
	html_attr(show_date(t, tz, cgit_date_mode(DATE_ISO8601_STRICT)));
	htmlf("' data-ut='%" PRIu64 "' title='", (uint64_t)t);
	html_attr(show_date(t, tz, cgit_date_mode(DATE_ISO8601)));
	htmlf("'>%.0f %s</time>", count, suffix);
}

/*
 * Whether a clone url opens with a URI scheme. The scp form git@host:path
 * has none, and a link element's href must hold a URI, so that form stays
 * out of the document head.
 */
static int has_uri_scheme(const char *url)
{
	const char *p = url;

	if (!isalpha((unsigned char)*p))
		return 0;
	while (isalnum((unsigned char)*p) || *p == '+' || *p == '-' || *p == '.')
		p++;
	return *p == ':';
}

static void print_rel_vcs_link(const char *url)
{
	if (!has_uri_scheme(url))
		return;
	html("<link rel='vcs-git' href='");
	html_attr(url);
	html("' title='");
	html_attr(ctx.repo->name);
	html(" Git repository'>\n");
}

static int emit_css_link(struct string_list_item *item, void *fallback)
{
	// An empty css entry is how a site turns the stylesheet off.
	if (item && *item->string == '\0')
		return 0;

	html("<link rel='stylesheet' href='");
	if (item)
		html_attr(item->string);
	else
		html_attr((const char *)fallback);
	html("'>\n");

	return 0;
}

static int emit_js_link(struct string_list_item *item, void *fallback)
{
	// An empty js entry is how a site turns the script off.
	if (item && *item->string == '\0')
		return 0;

	html("<script src='");
	if (item)
		html_attr(item->string);
	else
		html_attr((const char *)fallback);
	html("'></script>\n");

	return 0;
}

static void add_clone_urls(void (*fn)(const char *), char *urls, char *suffix)
{
	struct strbuf **url_list = strbuf_split_str(urls, ' ', 0);
	int i;

	for (i = 0; url_list[i]; i++) {
		strbuf_rtrim(url_list[i]);
		if (url_list[i]->len == 0)
			continue;
		if (suffix && *suffix)
			strbuf_addf(url_list[i], "/%s", suffix);
		fn(url_list[i]->buf);
	}

	strbuf_list_free(url_list);
}

/*
 * The id parameter pins a page to one commit while the rest of the chrome
 * keeps naming the branch. Answer that commit, or null when the request
 * follows the branch or the pin lands on its tip anyway.
 */
static const struct object_id *pinned_oid(void)
{
	static struct object_id oid;
	static int resolved, pinned;
	struct object_id head_oid;
	struct commit *commit;

	// The chrome asks several times per page and the answer cannot change
	// within a request.
	if (resolved)
		return pinned ? &oid : NULL;
	resolved = 1;

	if (!ctx.repo || !ctx.qry.has_oid || !ctx.qry.oid || !ctx.qry.head)
		return NULL;
	if (repo_get_oid(the_repository, ctx.qry.oid, &oid) ||
		repo_get_oid(the_repository, ctx.qry.head, &head_oid))
		return NULL;
	// A full hex id resolves without being looked up, so only peeling to a
	// commit proves the pin names history, and a tag pinned to the tip
	// compares equal only by its peeled commit.
	commit = lookup_commit_reference_gently(the_repository, &oid, 1);
	if (!commit)
		return NULL;
	oidcpy(&oid, &commit->object.oid);
	if (oideq(&oid, &head_oid))
		return NULL;
	pinned = 1;
	return &oid;
}

struct branch_option_data {
	int count;
	const char *selected;
};

/*
 * Whether the head the request follows is one of the branches the switcher
 * lists, remote ones included when those are shown. A head that is not, a
 * raw commit id or a tag, would otherwise leave the select resting on the
 * first branch, and submitting the form would quietly move the visitor there.
 */
static int head_is_listed_branch(void)
{
	struct ref_store *refs = get_main_ref_store(the_repository);
	struct strbuf ref = STRBUF_INIT;
	int found;

	strbuf_addf(&ref, "refs/heads/%s", ctx.qry.head);
	found = refs_ref_exists(refs, ref.buf);
	if (!found && ctx.repo->enable_remote_branches) {
		strbuf_reset(&ref);
		strbuf_addf(&ref, "refs/remotes/%s", ctx.qry.head);
		found = refs_ref_exists(refs, ref.buf);
	}
	strbuf_release(&ref);
	return found;
}

static void print_detached_head_option(void)
{
	const char *head = ctx.qry.head;
	struct object_id oid;
	struct strbuf label = STRBUF_INIT;

	// A head that is a full id reads better cut to the length the pinned
	// entry uses.
	if (strlen(head) == the_hash_algo->hexsz && !get_oid_hex(head, &oid))
		strbuf_addf(&label, "%.*s (detached)", SHORT_HASH_LEN, head);
	else
		strbuf_addf(&label, "%s (detached)", head);
	html_option(head, label.buf, head);
	strbuf_release(&label);
}

static int print_branch_option(const struct reference *ref, void *data)
{
	struct branch_option_data *opt = data;
	const char *name = ref->name;

	// The switcher runs on every page, so it is bounded like the refs list.
	if (ctx.cfg.max_ref_count && opt->count >= ctx.cfg.max_ref_count)
		return -1;
	// A name spelled like an option is refused as a head, so offering it
	// would only lead to an error page.
	if (name[0] == '-')
		return 0;
	opt->count++;
	html_option(name, name, opt->selected);
	return 0;
}

static void print_header(void)
{
	const char *logo = NULL, *logo_link = NULL;

	if (ctx.repo && ctx.repo->logo && *ctx.repo->logo)
		logo = ctx.repo->logo;
	else
		logo = ctx.cfg.logo;
	if (ctx.repo && ctx.repo->logo_link && *ctx.repo->logo_link)
		logo_link = ctx.repo->logo_link;
	else
		logo_link = ctx.cfg.logo_link;

	html("<header id='header'>\n");
	if (logo && *logo) {
		html("<a class='logo' href='");
		if (logo_link && *logo_link)
			html_attr(logo_link);
		else
			html_attr(root_url());
		html("'><img src='");
		html_attr(logo);
		html("' alt='cgit logo'></a>\n");
	}

	html("<h1 class='main'>");
	if (ctx.repo) {
		cgit_index_link("index", NULL, NULL, NULL, NULL, 0, 1);
		html(" : ");
		cgit_summary_link(ctx.repo->name, NULL, NULL, NULL);
	} else {
		html_txt(ctx.cfg.root_title);
	}
	html("</h1>\n");

	// A repository with no commits has no branches to list, so the
	// switcher would be an empty select next to a switch button, and an
	// error raised before the head was resolved has nothing to select.
	if (ctx.repo && ctx.env.authenticated && !ctx.empty_repo && ctx.qry.head) {
		const struct object_id *pinned = pinned_oid();
		// Only one option may carry selected, and a pinned commit
		// outranks the branch it was reached from.
		struct branch_option_data opt = {
			.selected = pinned ? NULL : ctx.qry.head,
		};
		char *oid = ctx.qry.oid, *oid2 = ctx.qry.oid2;

		html("<form class='branch-switch' method='get'>\n");
		// Switching branch means leaving the pinned commit behind, so
		// the id fields stay out of the form.
		ctx.qry.oid = ctx.qry.oid2 = NULL;
		cgit_add_hidden_formfields(0, 1, ctx.qry.page);
		ctx.qry.oid = oid;
		ctx.qry.oid2 = oid2;
		html("<select name='h' aria-label='Branch'>\n");
		if (pinned) {
			const char *hex = oid_to_hex(pinned);

			html_option(hex, cgit_fmt("%.*s (detached)", SHORT_HASH_LEN, hex), hex);
		} else if (!head_is_listed_branch()) {
			print_detached_head_option();
		}
		refs_for_each_branch_ref(get_main_ref_store(the_repository), print_branch_option, &opt);
		if (ctx.repo->enable_remote_branches)
			refs_for_each_remote_ref(get_main_ref_store(the_repository), print_branch_option, &opt);
		html("</select> ");
		html("<input type='submit' value='switch'>");
		html("</form>\n");
	}

	if (ctx.repo) {
		html("<p class='sub desc'>");
		html_txt(ctx.repo->desc);
		html("</p>\n");
		html("<p class='sub owner'>");
		html_txt(ctx.repo->owner);
		html("</p>\n");
	} else if (ctx.cfg.root_desc) {
		html("<p class='sub desc'>");
		html_txt(ctx.cfg.root_desc);
		html("</p>\n");
	}

	html("</header>\n");
}

static const char *tab_class(const char *page)
{
	if (!ctx.qry.page)
		return NULL;

	return strcmp(ctx.qry.page, page) ? NULL : "active";
}

static const char *tab_title(const char *format, const char *fallback, const char *path)
{
	if (!path || !*path || strlen(path) > MAX_TITLE_PATH_LEN)
		return fallback;
	return cgit_fmt(format, path);
}

static void print_repo_tabs(void)
{
	const char *vpath = ctx.qry.vpath;

	html("<ul>\n");
	if (ctx.repo->readme.nr) {
		html("<li>");
		reporevlink("about", "about", "About this repository", tab_class("about"), ctx.qry.head,
			NULL, NULL);
		html("</li>\n");
	}
	html("<li>");
	cgit_summary_link("summary", "Repository summary", tab_class("summary"), ctx.qry.head);
	html("</li>\n<li>");
	cgit_refs_link("refs", "Branches and tags", tab_class("refs"), ctx.qry.head, ctx.qry.oid, NULL);
	html("</li>\n<li>");
	cgit_log_link(
		"log", tab_title("Commit history of %s", "Commit history", vpath),
		tab_class("log"), ctx.qry.head, NULL, ctx.qry.vpath, 0, NULL, NULL,
		ctx.qry.showmsg, ctx.qry.follow
	);
	html("</li>\n<li>");
	if (ctx.qry.page && !strcmp(ctx.qry.page, "blame"))
		cgit_blame_link(
			"blame", tab_title("Line-by-line blame of %s", "Blame", vpath),
			tab_class("blame"), ctx.qry.head, ctx.qry.oid, ctx.qry.vpath
		);
	else
		cgit_tree_link(
			"tree", tab_title("Browse the tree at %s", "Browse the file tree", vpath),
			tab_class("tree"), ctx.qry.head, ctx.qry.oid, ctx.qry.vpath
		);
	html("</li>\n<li>");
	cgit_commit_link(
		"commit", "The current commit", tab_class("commit"),
		ctx.qry.head, ctx.qry.oid, ctx.qry.vpath
	);
	html("</li>\n<li>");
	cgit_diff_link(
		"diff", tab_title("Changes to %s", "Changes in the current commit", vpath),
		tab_class("diff"), ctx.qry.head, ctx.qry.oid, ctx.qry.oid2, ctx.qry.vpath
	);
	html("</li>\n");
	if (ctx.repo->max_stats) {
		html("<li>");
		cgit_stats_link("stats", "Commit activity", tab_class("stats"), ctx.qry.head, ctx.qry.vpath);
		html("</li>\n");
	}
	html("</ul>\n");
}

static void print_repo_search(void)
{
	html("<form class='search' role='search' method='get' action='");
	if (ctx.cfg.virtual_root) {
		char *fileurl = cgit_fileurl(ctx.qry.repo, "log", ctx.qry.vpath, NULL);
		html_url_path(fileurl);
		free(fileurl);
	}
	html("'>\n");
	cgit_add_hidden_formfields(1, 0, "log");
	html("<select name='qt' aria-label='Search type'>\n");
	html_option("grep", "log msg", ctx.qry.grep);
	html_option("author", "author", ctx.qry.grep);
	html_option("committer", "committer", ctx.qry.grep);
	html_option("range", "range", ctx.qry.grep);
	html("</select>\n");
	html("<input class='txt' type='search' name='q' aria-label='Search' value='");
	html_attr(ctx.qry.search);
	html("'>\n");
	html("<input type='submit' value='search'>\n");
	html("</form>\n");
}

static void print_site_tabs(void)
{
	html("<ul>\n<li>");
	site_link(NULL, "index", "Repository index", tab_class("repolist"), NULL, NULL, 0, 1);
	html("</li>\n");
	if (ctx.cfg.root_readme) {
		html("<li>");
		site_link("about", "about", "About this site", tab_class("about"), NULL, NULL, 0, 1);
		html("</li>\n");
	}
	html("</ul>\n");
}

static void print_site_search(void)
{
	char *currenturl = cgit_currenturl();

	html("<form class='search' role='search' method='get' action='");
	html_attr(currenturl);
	html("'>\n");
	html("<input class='txt' type='search' name='q' aria-label='Search' value='");
	html_attr(ctx.qry.search);
	html("'>\n");
	html("<input type='submit' value='search'>\n");
	html("</form>\n");
	free(currenturl);
}

static void snapshot_link(const char *name, const char *title, const char *class,
	const char *head, const char *rev, const char *archivename)
{
	reporevlink("snapshot", name, title, class, head, rev, archivename);
}

/*
 * The link is built out of the request in ctx.qry, so a caller that alters a
 * field of ctx.qry first gets a link differing in exactly that.
 */
static void self_link(const char *name, const char *title, const char *class)
{
	const char *rev = ctx.qry.has_oid ? ctx.qry.oid : NULL;

	if (!strcmp(ctx.qry.page, "repolist"))
		cgit_index_link(name, title, class, ctx.qry.search, ctx.qry.sort, ctx.qry.ofs, 1);
	else if (!strcmp(ctx.qry.page, "summary"))
		cgit_summary_link(name, title, class, ctx.qry.head);
	else if (!strcmp(ctx.qry.page, "tag"))
		cgit_tag_link(name, title, class, ctx.qry.has_oid ? ctx.qry.oid : ctx.qry.head);
	else if (!strcmp(ctx.qry.page, "tree"))
		cgit_tree_link(name, title, class, ctx.qry.head, rev, ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "plain"))
		cgit_plain_link(name, title, class, ctx.qry.head, rev, ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "blame"))
		cgit_blame_link(name, title, class, ctx.qry.head, rev, ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "log"))
		cgit_log_link(
			name, title, class, ctx.qry.head, rev, ctx.qry.path, ctx.qry.ofs, ctx.qry.grep,
			ctx.qry.search, ctx.qry.showmsg, ctx.qry.follow
		);
	else if (!strcmp(ctx.qry.page, "commit"))
		cgit_commit_link(name, title, class, ctx.qry.head, rev, ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "patch"))
		cgit_patch_link(name, title, class, ctx.qry.head, rev, ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "refs"))
		cgit_refs_link(name, title, class, ctx.qry.head, rev, ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "snapshot"))
		snapshot_link(name, title, class, ctx.qry.head, rev, ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "diff"))
		cgit_diff_link(name, title, class, ctx.qry.head, ctx.qry.oid, ctx.qry.oid2, ctx.qry.path);
	else if (!strcmp(ctx.qry.page, "stats"))
		cgit_stats_link(name, title, class, ctx.qry.head, ctx.qry.path);
	else {
		// A page name this switch does not know still gets a plain
		// repolink.
		repolink(title, class, ctx.qry.page, ctx.qry.head, ctx.qry.path);
		html("'>");
		html_txt(name);
		html("</a>");
	}
}

static void print_path_crumbs(char *path)
{
	char *old_path = ctx.qry.path;
	char *start = path, *slash, *end = path + strlen(path);
	int levels = 0;

	ctx.qry.path = NULL;
	self_link("root", NULL, NULL);
	// self_link reads the path out of ctx.qry, so terminating the buffer at
	// each slash is what makes a crumb link to the prefix it stands for.
	ctx.qry.path = start = path;
	while (start < end) {
		if (!(slash = strchr(start, '/')) || levels > MAX_CRUMB_LEVELS)
			slash = end;
		*slash = '\0';
		html_txt("/");
		self_link(start, NULL, NULL);
		if (slash < end)
			*slash = '/';
		start = slash + 1;
		++levels;
	}
	ctx.qry.path = old_path;
}

/*
 * A reverse memchr, which glibc has as memrchr but macOS and the BSDs do not.
 */
static const char *find_last_char(const char *start, const char *end, int c)
{
	while (end > start) {
		if (*--end == c)
			return end;
	}
	return NULL;
}

static void vprint_error(const char *fmt, va_list ap)
{
	va_list cp;

	html("<div class='error'>");
	va_copy(cp, ap);
	html_vtxtf(fmt, cp);
	va_end(cp);
	html("</div>\n");
}

void cgit_print_error(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vprint_error(fmt, ap);
	va_end(ap);
}

const char *cgit_httpscheme(void)
{
	if (ctx.env.https && !strcmp(ctx.env.https, "on"))
		return "https://";
	else
		return "http://";
}

char *cgit_hosturl(void)
{
	if (ctx.env.http_host)
		return xstrdup(ctx.env.http_host);
	if (!ctx.env.server_name)
		return NULL;
	if (!ctx.env.server_port || atoi(ctx.env.server_port) == DEFAULT_HTTP_PORT)
		return xstrdup(ctx.env.server_name);
	return cgit_fmtalloc("%s:%s", ctx.env.server_name, ctx.env.server_port);
}

char *cgit_currenturl(void)
{
	const char *root = root_url();

	if (!ctx.qry.url)
		return xstrdup(root);
	if (root[0] && root[strlen(root) - 1] == '/')
		return cgit_fmtalloc("%s%s", root, ctx.qry.url);
	return cgit_fmtalloc("%s/%s", root, ctx.qry.url);
}

char *cgit_currentquery(void)
{
	const char *orig_query = ctx.env.query_string ? ctx.env.query_string : "";
	size_t len = strlen(orig_query);
	char *query = xmalloc(len + 2);
	char *match;

	// The url argument carried the path into this request and every caller
	// spells the path out again, so it is dropped here. The copy keeps a
	// leading question mark so that every match has a character before it,
	// which is what tells the argument itself from the tail of another one.
	memcpy(query + 1, orig_query, len + 1);
	query[0] = '?';
	match = query;
	while ((match = strstr(match, "url="))) {
		if (match[-1] == '?' || match[-1] == '&') {
			const char *next = strchr(match, '&');
			if (next)
				memmove(match, next + 1, strlen(next));
			else
				match[0] = '\0';
		} else {
			match++;
		}
	}
	if (!query[1])
		query[0] = '\0';
	return query;
}

char *cgit_currentfullurl(void)
{
	const char *root = root_url();
	char *query = cgit_currentquery();
	char *ret;

	if (!ctx.qry.url)
		ret = cgit_fmtalloc("%s%s", root, query);
	else if (root[0] && root[strlen(root) - 1] == '/')
		ret = cgit_fmtalloc("%s%s%s", root, ctx.qry.url, query);
	else
		ret = cgit_fmtalloc("%s/%s%s", root, ctx.qry.url, query);
	free(query);
	return ret;
}

const char *cgit_loginurl(void)
{
	static const char *login_url;

	if (!login_url)
		login_url = cgit_fmtalloc("%s?p=login", root_url());
	return login_url;
}

char *cgit_repourl(const char *reponame)
{
	if (ctx.cfg.virtual_root)
		return cgit_fmtalloc("%s%s/", ctx.cfg.virtual_root, reponame);
	else
		return cgit_fmtalloc("?r=%s", reponame);
}

char *cgit_fileurl(const char *reponame, const char *pagename, const char *filename,
	const char *query)
{
	struct strbuf sb = STRBUF_INIT;
	const char *delim;

	// The result is a raw URL, so the query joiner is a bare ampersand
	// and each sink escapes the whole string for wherever it lands.
	if (ctx.cfg.virtual_root) {
		strbuf_addf(&sb, "%s%s/%s/%s", ctx.cfg.virtual_root, reponame, pagename,
			filename ? filename : "");
		delim = "?";
	} else {
		strbuf_addf(&sb, "?url=%s/%s/%s", reponame, pagename, (filename ? filename : ""));
		delim = "&";
	}
	if (query)
		strbuf_addf(&sb, "%s%s", delim, query);
	return strbuf_detach(&sb, NULL);
}

char *cgit_pageurl(const char *reponame, const char *pagename, const char *query)
{
	return cgit_fileurl(reponame, pagename, NULL, query);
}

const char *cgit_snapshot_prefix(const struct cgit_repo *repo)
{
	if (repo->snapshot_prefix)
		return repo->snapshot_prefix;

	return repo_basename(repo->url);
}

void cgit_index_link(const char *name, const char *title, const char *class,
	const char *pattern, const char *sort, int ofs, int always_root)
{
	site_link(NULL, name, title, class, pattern, sort, ofs, always_root);
}

void cgit_summary_link(const char *name, const char *title, const char *class, const char *head)
{
	reporevlink(NULL, name, title, class, head, NULL, NULL);
}

void cgit_tag_link(const char *name, const char *title, const char *class, const char *tag)
{
	reporevlink("tag", name, title, class, tag, NULL, NULL);
}

void cgit_tree_link(const char *name, const char *title, const char *class,
	const char *head, const char *rev, const char *path)
{
	reporevlink("tree", name, title, class, head, rev, path);
}

void cgit_plain_link(const char *name, const char *title, const char *class,
	const char *head, const char *rev, const char *path)
{
	reporevlink("plain", name, title, class, head, rev, path);
}

void cgit_blame_link(const char *name, const char *title, const char *class,
	const char *head, const char *rev, const char *path)
{
	reporevlink("blame", name, title, class, head, rev, path);
}

void cgit_log_link(const char *name, const char *title, const char *class,
	const char *head, const char *rev, const char *path, int ofs, const char *grep,
	const char *pattern, int showmsg, int follow)
{
	const char *delim;

	delim = repolink(title, class, "log", head, path);
	delim = emit_rev_arg(delim, rev);
	if (grep && pattern) {
		html(delim);
		html("qt=");
		html_url_arg(grep);
		delim = "&amp;";
		html(delim);
		html("q=");
		html_url_arg(pattern);
	}
	if (ofs > 0) {
		html(delim);
		html("ofs=");
		htmlf("%d", ofs);
		delim = "&amp;";
	}
	if (showmsg) {
		html(delim);
		html("showmsg=1");
		delim = "&amp;";
	}
	if (follow) {
		html(delim);
		html("follow=1");
	}
	html("'>");
	html_txt(name);
	html("</a>");
}

void cgit_commit_link(const char *name, const char *title, const char *class,
	const char *head, const char *rev, const char *path)
{
	const char *delim;

	delim = repolink(title, class, "commit", head, path);
	delim = emit_rev_arg(delim, rev);
	emit_diff_args(delim);
	html("'>");
	if (name && name[0] != '\0') {
		if (ctx.cfg.max_msg_len >= MIN_TRUNCATE_LEN && strlen(name) > (size_t)ctx.cfg.max_msg_len) {
			size_t len = ctx.cfg.max_msg_len - ELLIPSIS_LEN;

			// A cut inside a multibyte character would leave an
			// invalid sequence on the page.
			while (len > 0 && (name[len] & 0xC0) == 0x80)
				len--;
			html_ntxt(name, len);
			html("...");
		} else {
			html_txt(name);
		}
	} else {
		html_txt("(no commit message)");
	}
	html("</a>");
}

void cgit_refs_link(const char *name, const char *title, const char *class,
	const char *head, const char *rev, const char *path)
{
	reporevlink("refs", name, title, class, head, rev, path);
}

void cgit_diff_link(const char *name, const char *title, const char *class,
	const char *head, const char *new_rev, const char *old_rev, const char *path)
{
	const char *delim;

	delim = repolink(title, class, "diff", head, path);
	delim = emit_rev_arg(delim, new_rev);
	if (old_rev) {
		html(delim);
		html("id2=");
		html_url_arg(old_rev);
		delim = "&amp;";
	}
	emit_diff_args(delim);
	html("'>");
	html_txt(name);
	html("</a>");
}

void cgit_patch_link(const char *name, const char *title, const char *class,
	const char *head, const char *rev, const char *path)
{
	reporevlink("patch", name, title, class, head, rev, path);
}

void cgit_stats_link(const char *name, const char *title, const char *class,
	const char *head, const char *path)
{
	reporevlink("stats", name, title, class, head, NULL, path);
}

void cgit_object_link(struct object *obj, int full)
{
	const char *page;
	char *shortrev, *fullrev, *name;

	fullrev = oid_to_hex(&obj->oid);
	if (full) {
		name = cgit_fmt("%s %s", type_name(obj->type), fullrev);
	} else {
		shortrev = xstrdup(fullrev);
		shortrev[SHORT_HASH_LEN] = '\0';
		name = cgit_fmt("%s %s...", type_name(obj->type), shortrev);
	}
	if (obj->type == OBJ_COMMIT) {
		cgit_commit_link(name, NULL, NULL, ctx.qry.head, fullrev, NULL);
		return;
	} else if (obj->type == OBJ_TREE)
		page = "tree";
	else if (obj->type == OBJ_TAG)
		page = "tag";
	else
		page = "blob";
	reporevlink(page, name, NULL, NULL, ctx.qry.head, fullrev, NULL);
}

/*
 * The tree being listed decides which .gitmodules applies, so the revision
 * the query names is resolved once and reused for every row.
 */
static const struct object_id *page_treeish(void)
{
	static struct object_id oid;
	static int state;

	if (!state) {
		const char *rev = ctx.qry.oid ? ctx.qry.oid : ctx.qry.head;

		state = rev && !repo_get_oid(the_repository, rev, &oid) ? 1 : -1;
	}
	return state > 0 ? &oid : NULL;
}

static void strip_git_suffix(struct strbuf *sb)
{
	while (sb->len && sb->buf[sb->len - 1] == '/')
		strbuf_setlen(sb, sb->len - 1);
	strbuf_strip_suffix(sb, ".git");
}

/*
 * Reduces a submodule url to the path it names on its host, so the tail can
 * be compared against the urls this instance serves. A relative url points
 * at a sibling of the repository's own clone, which maps onto a sibling of
 * its cgit url.
 */
static char *submodule_url_path(const char *url)
{
	struct strbuf sb = STRBUF_INIT;
	const char *rest, *colon;

	if (starts_with(url, "./") || starts_with(url, "../")) {
		strbuf_addf(&sb, "%s/%s", ctx.repo->url, url);
		if (strbuf_normalize_path(&sb)) {
			strbuf_release(&sb);
			return NULL;
		}
	} else if (
		skip_prefix(url, "http://", &rest)  ||
		skip_prefix(url, "https://", &rest) ||
		skip_prefix(url, "git://", &rest)   ||
		skip_prefix(url, "ssh://", &rest)
	) {
		rest = strchr(rest, '/');
		if (!rest)
			return NULL;
		strbuf_addstr(&sb, rest);
	} else if (skip_prefix(url, "file://", &rest)) {
		strbuf_addstr(&sb, rest);
	} else if ((colon = strchr(url, ':')) && !memchr(url, '/', colon - url)) {
		// scp syntax, user@host:path
		strbuf_addstr(&sb, colon + 1);
	} else {
		strbuf_addstr(&sb, url);
	}

	strip_git_suffix(&sb);
	while (sb.len && sb.buf[0] == '/')
		strbuf_remove(&sb, 0, 1);
	if (!sb.len) {
		strbuf_release(&sb);
		return NULL;
	}
	return strbuf_detach(&sb, NULL);
}

/*
 * Finds the served repository whose url matches the most trailing components
 * of the submodule url, whatever scheme carried it.
 */
static struct cgit_repo *repo_serving_url(const char *url)
{
	struct cgit_repo *repo, *best = NULL;
	char *path = submodule_url_path(url);
	size_t plen, rlen, blen = 0;
	int i;

	if (!path)
		return NULL;
	plen = strlen(path);
	for (i = 0; i < cgit_repolist.count; i++) {
		repo = &cgit_repolist.repos[i];
		if (repo->ignore)
			continue;
		rlen = strlen(repo->url);
		if (!rlen || rlen > plen)
			continue;
		if (strcmp(path + plen - rlen, repo->url))
			continue;
		// Only whole trailing components count, so x/foo cannot
		// claim a repository named oo.
		if (rlen < plen && path[plen - rlen - 1] != '/')
			continue;
		if (rlen > blen) {
			best = repo;
			blen = rlen;
		}
	}
	free(path);
	return best;
}

// Hosts whose repository and commit pages follow a known form, so an ssh url
// can still be offered as a browser link. kernel.org runs cgit, which keeps
// the .git suffix in its own page urls.
static const struct forge {
	const char *host;
	const char *commit_seg;
	int keep_dot_git;
} forges[] = {
	{ "github.com", "/commit/", 0 },
	{ "gitlab.com", "/-/commit/", 0 },
	{ "bitbucket.org", "/commits/", 0 },
	{ "codeberg.org", "/commit/", 0 },
	{ "gitea.com", "/commit/", 0 },
	{ "git.sr.ht", "/commit/", 0 },
	{ "git.kernel.org", "/commit/?id=", 1 },
};

static const struct forge *forge_for_host(const char *host, size_t len)
{
	size_t i;

	for (i = 0; i < ARRAY_SIZE(forges); i++)
		if (strlen(forges[i].host) == len && !strncasecmp(forges[i].host, host, len))
			return &forges[i];
	return NULL;
}

/*
 * Derives a submodule row's links from its .gitmodules entry. The url is
 * matched against this instance's own repositories first, so ssh, file and
 * relative urls still land on an internal page when their target is served
 * here, and a scheme cgit cannot vouch for is left unlinked as a tooltip.
 */
static void gitmodules_link(const char *path, const char *rev, char **module,
	char **commit, const char **tooltip)
{
	const struct object_id *treeish = page_treeish();
	const struct submodule *sub;
	const struct forge *forge;
	struct cgit_repo *target;
	struct strbuf sb = STRBUF_INIT;
	const char *url, *rest, *colon;

	if (!treeish)
		return;
	sub = submodule_from_path(the_repository, treeish, path);
	if (!sub || !sub->url)
		return;
	url = sub->url;

	target = repo_serving_url(url);
	if (target) {
		char *query = cgit_fmtalloc("id=%s", rev);

		*module = cgit_pageurl(target->url, "tree", query);
		*commit = cgit_pageurl(target->url, "commit", query);
		free(query);
		return;
	}

	if (skip_prefix(url, "http://", &rest) || skip_prefix(url, "https://", &rest)) {
		*module = xstrdup(url);
		forge = forge_for_host(rest, strcspn(rest, "/"));
		if (forge) {
			strbuf_addstr(&sb, url);
			while (sb.len && sb.buf[sb.len - 1] == '/')
				strbuf_setlen(&sb, sb.len - 1);
			if (!forge->keep_dot_git)
				strbuf_strip_suffix(&sb, ".git");
			strbuf_addstr(&sb, forge->commit_seg);
			strbuf_addstr(&sb, rev);
			*commit = strbuf_detach(&sb, NULL);
		}
		return;
	}

	if ((colon = strchr(url, ':')) && !memchr(url, '/', colon - url)) {
		const char *host = url;
		const char *at = memchr(url, '@', colon - url);

		if (at)
			host = at + 1;
		forge = forge_for_host(host, colon - host);
		if (forge) {
			rest = colon + 1;
			while (*rest == '/')
				rest++;
			strbuf_addf(&sb, "https://%.*s/%s", (int)(colon - host), host, rest);
			while (sb.len && sb.buf[sb.len - 1] == '/')
				strbuf_setlen(&sb, sb.len - 1);
			if (!forge->keep_dot_git)
				strbuf_strip_suffix(&sb, ".git");
			*module = xstrdup(sb.buf);
			strbuf_addstr(&sb, forge->commit_seg);
			strbuf_addstr(&sb, rev);
			*commit = strbuf_detach(&sb, NULL);
			return;
		}
	}

	*tooltip = url;
}

void cgit_submodule_link(const char *class, char *path, const char *rev)
{
	struct string_list *list;
	struct string_list_item *item;
	char tail, *module = NULL, *commit = NULL;
	const char *name, *tooltip = NULL;
	size_t len;

	len = 0;
	tail = 0;
	list = &ctx.repo->submodules;
	item = lookup_path(list, path);
	if (!item) {
		len = strlen(path);
		tail = path[len - 1];
		if (tail == '/') {
			path[len - 1] = 0;
			item = lookup_path(list, path);
		}
	}

	if (!item && !ctx.repo->module_link && ctx.repo->enable_gitmodules_links)
		gitmodules_link(path, rev, &module, &commit, &tooltip);

	// The row shows the entry's own name, like every other row, while
	// the lookups above want the full path.
	name = strrchr(path, '/');
	name = name ? name + 1 : path;

	if (item || ctx.repo->module_link || module) {
		html("<a ");
		if (class)
			htmlf("class='%s' ", class);
		html("href='");
		if (item) {
			const char *args[] = { rev };
			emit_module_link(item->util, args, 1);
		} else if (ctx.repo->module_link) {
			const char *args[] = { name, rev };
			emit_module_link(ctx.repo->module_link, args, 2);
		} else {
			html_attr(module);
		}
		html("'>");
		html_txt(name);
		html("</a>");
	} else {
		html("<span");
		if (class)
			htmlf(" class='%s'", class);
		if (tooltip) {
			html(" title='");
			html_attr(tooltip);
			html("'");
		}
		html(">");
		html_txt(name);
		html("</span>");
	}
	html(" @ ");
	if (commit) {
		html("<a class='ls-mod-hash' href='");
		html_attr(commit);
		html("' title='");
	} else {
		html("<span class='ls-mod-hash' title='");
	}
	html_attr(rev);
	html("'>");
	html_txtf("%.7s", rev);
	html(commit ? "</a>" : "</span>");
	free(module);
	free(commit);
	if (tail == '/')
		path[len - 1] = tail;
}

struct date_mode cgit_date_mode(enum date_mode_type type)
{
	static struct date_mode mode;

	mode.type = type;
	mode.local = ctx.cfg.local_time;
	return mode;
}

void cgit_print_age(time_t t, int tz, time_t max_relative)
{
	time_t now, secs;

	if (!t)
		return;
	time(&now);
	secs = now - t;
	if (secs < 0)
		secs = 0;

	if (!ctx.cfg.enable_relative_dates || (secs > max_relative && max_relative >= 0)) {
		print_abs_date(t, tz);
		return;
	}

	if (secs < SECONDS_PER_HOUR * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_MINUTE, "age-mins", "min.");
		return;
	}
	if (secs < SECONDS_PER_DAY * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_HOUR, "age-hours", "hours");
		return;
	}
	if (secs < SECONDS_PER_WEEK * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_DAY, "age-days", "days");
		return;
	}
	if (secs < SECONDS_PER_MONTH * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_WEEK, "age-weeks", "weeks");
		return;
	}
	if (secs < SECONDS_PER_YEAR * 2) {
		print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_MONTH, "age-months", "months");
		return;
	}
	print_rel_date(t, tz, secs * 1.0 / SECONDS_PER_YEAR, "age-years", "years");
}

/*
 * Whether a content type carries text a charset applies to, which is every
 * text type and the XML ones, the atom feed among them.
 */
static int type_has_charset(const char *mimetype)
{
	return starts_with(mimetype, "text/") || strstr(mimetype, "xml");
}

void cgit_print_http_headers(void)
{
	ctx.page.headers_sent = 1;
	if (ctx.env.no_http && !strcmp(ctx.env.no_http, "1"))
		return;

	// CGI treats a missing Status as 200, but writing it keeps every
	// response's header block the same shape.
	if (ctx.page.status)
		htmlf("Status: %d %s\n", ctx.page.status, ctx.page.statusmsg);
	else
		html("Status: 200 OK\n");
	// A charset only means something for text, so an archive or a pack
	// is sent without one.
	if (ctx.page.mimetype && ctx.page.charset && type_has_charset(ctx.page.mimetype))
		htmlf("Content-Type: %s; charset=%s\n", ctx.page.mimetype, ctx.page.charset);
	else if (ctx.page.mimetype)
		htmlf("Content-Type: %s\n", ctx.page.mimetype);
	if (ctx.page.size)
		htmlf("Content-Length: %zu\n", ctx.page.size);
	if (ctx.page.filename) {
		html("Content-Disposition: inline; filename=\"");
		html_header_arg_in_quotes(ctx.page.filename);
		html("\"\n");
	}
	// An untrusted page serves repository bytes verbatim, so the browser is
	// told not to guess a type of its own from them and not to load
	// anything they reference.
	if (ctx.page.untrusted) {
		html("X-Content-Type-Options: nosniff\n");
		html("Content-Security-Policy: default-src 'none'\n");
	}
	if (!ctx.env.authenticated)
		html("Cache-Control: no-cache, no-store\n");
	html("\n");
	// Some pages follow the headers with output written by git itself, not
	// through html_raw, so the buffer is emptied to keep the headers first.
	html_flush();
	if (ctx.env.request_method && !strcmp(ctx.env.request_method, "HEAD"))
		exit(0);
}

void cgit_redirect(const char *url, const char *query, bool permanent)
{
	htmlf("Status: %d %s\n", permanent ? 301 : 302, permanent ? "Moved Permanently" : "Found");
	html("Location: ");
	html_url_path(url);
	if (query)
		html_header_query(query);
	html("\n\n");
}

void cgit_print_docstart(void)
{
	const struct object_id *pinned;
	char *host = cgit_hosturl();

	if (ctx.cfg.embedded) {
		if (ctx.cfg.header)
			html_include(ctx.cfg.header);
		return;
	}

	html("<!DOCTYPE html>\n");
	html("<html lang='en' class='cgit-standalone'>\n");
	html("<head>\n");
	html("<meta charset='UTF-8'>\n");
	html("<meta name='viewport' content='width=device-width, initial-scale=1'>\n");
	html("<meta name='color-scheme' content='light dark'>\n");
	html("<meta name='theme-color' media='(prefers-color-scheme: light)' content='#ffffff'>\n");
	html("<meta name='theme-color' media='(prefers-color-scheme: dark)' content='#1b1b1b'>\n");
	html("<title>");
	// An error page reached before a title was chosen still has to name
	// itself, since an empty title element is not valid.
	html_txt(ctx.page.title ? ctx.page.title : ctx.cfg.root_title);
	// The auth page goes out before the repository is opened, when
	// pinned_oid cannot resolve anything yet.
	if (ctx.env.authenticated && (pinned = pinned_oid()))
		html_txtf(" @ %.*s", SHORT_HASH_LEN, oid_to_hex(pinned));
	html("</title>\n");
	// The placeholder a scanned repository carries instead of a description
	// is left out, since it describes nothing.
	if (ctx.repo && ctx.repo->desc && *ctx.repo->desc && ctx.repo->desc != cgit_default_repo_desc) {
		html("<meta name='description' content='");
		html_attr(ctx.repo->desc);
		html("'>\n");
	} else if (!ctx.repo && ctx.cfg.root_desc && *ctx.cfg.root_desc) {
		html("<meta name='description' content='");
		html_attr(ctx.cfg.root_desc);
		html("'>\n");
	}
	htmlf("<meta name='generator' content='cgit %s'>\n", cgit_version);
	if (ctx.cfg.robots && *ctx.cfg.robots) {
		html("<meta name='robots' content='");
		html_attr(ctx.cfg.robots);
		html("'>\n");
	}

	if (ctx.cfg.css.items)
		for_each_string_list(&ctx.cfg.css, emit_css_link, NULL);
	else
		emit_css_link(NULL, "/cgit.css");

	if (ctx.cfg.js.items)
		for_each_string_list(&ctx.cfg.js, emit_js_link, NULL);
	else
		emit_js_link(NULL, "/cgit.js");

	if (ctx.cfg.favicon && *ctx.cfg.favicon) {
		html("<link rel='icon' href='");
		html_attr(ctx.cfg.favicon);
		html("'>\n");
	}
	if (host && ctx.repo && ctx.qry.head) {
		char *fileurl;
		struct strbuf sb = STRBUF_INIT;
		strbuf_addf(&sb, "h=%s", ctx.qry.head);

		html("<link rel='alternate' title='Atom feed' href='");
		html(cgit_httpscheme());
		html_attr(host);
		fileurl = cgit_fileurl(ctx.repo->url, "atom", ctx.qry.vpath, sb.buf);
		html_attr(fileurl);
		html("' type='application/atom+xml'>\n");
		strbuf_release(&sb);
		free(fileurl);
	}
	if (ctx.repo)
		cgit_add_clone_urls(print_rel_vcs_link);
	if (ctx.cfg.head_include)
		html_include(ctx.cfg.head_include);
	if (ctx.repo && ctx.repo->head_content)
		html(ctx.repo->head_content);
	html("</head>\n");
	html("<body>\n");
	if (ctx.cfg.header)
		html_include(ctx.cfg.header);
	free(host);
}

void cgit_print_docend(void)
{
	html("</main>\n");
	if (ctx.cfg.embedded) {
		html("</div>\n");
		if (ctx.cfg.footer)
			html_include(ctx.cfg.footer);
		return;
	}
	if (ctx.cfg.footer)
		html_include(ctx.cfg.footer);
	else {
		htmlf("<footer class='footer'>generated by "
			"<a href='https://github.com/brycekwon/cgit'>cgit %s</a> "
			"(<a href='https://git-scm.com/'>git %s</a>)</footer>\n",
			cgit_version, git_version_string);
	}
	html("</div>\n");
	html("</body>\n</html>\n");
}

void cgit_print_error_page(int code, const char *msg, const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	cgit_vprint_error_page(code, msg, fmt, ap);
	va_end(ap);
}

void cgit_vprint_error_page(int code, const char *msg, const char *fmt, va_list ap)
{
	// An error page describes a condition that may not outlast the slot
	// holding it. A request naming a commit not yet pushed would cache its
	// 404 under the never-expiring static ttl and keep serving it after
	// the push, so the error is rendered straight to the visitor instead.
	html_flush();
	cache_abandon_fill();
	// Once the status line is out the error can only join the body under
	// way, and the page that hit it carries on to its own end.
	if (ctx.page.headers_sent) {
		vprint_error(fmt, ap);
		return;
	}
	ctx.page.status = code;
	ctx.page.statusmsg = msg;
	// A page that had already chosen another type, such as an image
	// served through the about page, still answers its error as html.
	ctx.page.mimetype = "text/html";
	ctx.page.charset = PAGE_ENCODING;
	ctx.page.filename = NULL;
	cgit_print_layout_start();
	vprint_error(fmt, ap);
	cgit_print_layout_end();
}

void cgit_print_layout_start(void)
{
	cgit_print_http_headers();
	cgit_print_docstart();
	cgit_print_pageheader();
}

void cgit_print_layout_end(void)
{
	cgit_print_docend();
}

void cgit_add_clone_urls(void (*fn)(const char *))
{
	if (ctx.repo->clone_url)
		add_clone_urls(fn, cgit_expand_macros(ctx.repo->clone_url), NULL);
	else if (ctx.cfg.clone_prefix)
		add_clone_urls(fn, ctx.cfg.clone_prefix, ctx.repo->url);
}

static char *http_clone_url;
static int http_clone_url_scanned;

/*
 * Scheme names compare case-insensitively.
 */
static int is_http_url(const char *url)
{
	return istarts_with(url, "http://") || istarts_with(url, "https://");
}

static void capture_http_clone_url(const char *url)
{
	if (!http_clone_url && is_http_url(url))
		http_clone_url = xstrdup(url);
}

/*
 * One row of the clone table. Every row is a link, but a browser cannot
 * follow the ssh, scp or git forms, so those rows point at the first http
 * url in the clone list, or at the repository's own page when the list has
 * none. A colspan of zero leaves the attribute out.
 */
void cgit_print_clone_row(const char *url, int colspan)
{
	const char *href = url;
	char *fallback = NULL;

	if (!is_http_url(url)) {
		if (!http_clone_url_scanned) {
			http_clone_url_scanned = 1;
			cgit_add_clone_urls(capture_http_clone_url);
		}
		href = http_clone_url;
		if (!href)
			href = fallback = cgit_repourl(ctx.repo->url);
	}

	if (colspan)
		htmlf("<tr><td colspan='%d' class='clone-url'>", colspan);
	else
		html("<tr><td class='clone-url'>");
	html("<a rel='vcs-git' title='");
	html_attr(ctx.repo->name);
	html(" Git repository' href='");
	html_attr(href);
	html("'>");
	html_txt(url);
	html("</a></td></tr>\n");
	free(fallback);
}

void cgit_add_hidden_formfields(int incl_head, int incl_search, const char *page)
{
	if (!ctx.cfg.virtual_root) {
		struct strbuf url = STRBUF_INIT;

		strbuf_addf(&url, "%s/%s", ctx.qry.repo, page);
		if (ctx.qry.vpath)
			strbuf_addf(&url, "/%s", ctx.qry.vpath);
		html_hidden("url", url.buf);
		strbuf_release(&url);
	}

	if (incl_head && ctx.qry.head && ctx.repo->defbranch && strcmp(ctx.qry.head, ctx.repo->defbranch))
		html_hidden("h", ctx.qry.head);

	if (ctx.qry.oid)
		html_hidden("id", ctx.qry.oid);
	if (ctx.qry.oid2)
		html_hidden("id2", ctx.qry.oid2);
	if (ctx.qry.showmsg)
		html_hidden("showmsg", "1");

	if (incl_search) {
		if (ctx.qry.grep)
			html_hidden("qt", ctx.qry.grep);
		if (ctx.qry.search)
			html_hidden("q", ctx.qry.search);
	}
}

void cgit_print_pageheader(void)
{
	const struct object_id *pinned;

	// The root names the page and the repository so a stylesheet or script
	// can tell them apart without reading the tabs.
	html("<div id='cgit'");
	if (ctx.cfg.embedded)
		html(" class='cgit-embedded'");
	if (ctx.qry.page) {
		html(" data-page='");
		html_attr(ctx.qry.page);
		html("'");
	}
	if (ctx.repo) {
		html(" data-repo='");
		html_attr(ctx.repo->url);
		html("'");
	}
	html(">\n");
	if (!ctx.env.authenticated || ctx.cfg.enable_header)
		print_header();

	if (ctx.env.authenticated)
		html("<nav class='tabs' aria-label='Pages'>\n");
	if (ctx.env.authenticated && ctx.repo && ctx.empty_repo) {
		// Every other tab needs a commit to render and the search form
		// has nothing to search, so an empty repo gets summary alone.
		html("<ul>\n<li>");
		cgit_summary_link("summary", "Repository summary", tab_class("summary"), ctx.qry.head);
		html("</li>\n</ul>\n");
	} else if (ctx.env.authenticated && ctx.repo) {
		print_repo_tabs();
		print_repo_search();
	} else if (ctx.env.authenticated) {
		print_site_tabs();
		print_site_search();
	}
	if (ctx.env.authenticated)
		html("</nav>\n");
	pinned = ctx.env.authenticated && ctx.repo ? pinned_oid() : NULL;
	// The commit and diff pages name the commit they show as their own
	// content, so the rev crumb would only repeat them.
	if (pinned && ctx.qry.page && (!strcmp(ctx.qry.page, "commit") || !strcmp(ctx.qry.page, "diff")))
		pinned = NULL;
	if ((ctx.env.authenticated && ctx.repo && ctx.qry.vpath) || pinned) {
		html("<nav class='path' aria-label='");
		html(ctx.qry.vpath ? "breadcrumb" : "revision");
		html("'>");
		if (ctx.qry.vpath) {
			// The nav lays out as a flex row, which would make
			// every crumb its own item and swallow the spaces
			// between them, so the run stays inline in a span.
			html("<span>path: ");
			print_path_crumbs(ctx.qry.vpath);
			if (ctx.repo->enable_follow_links && !strcmp(ctx.qry.page, "log")) {
				html(" (");
				ctx.qry.follow = !ctx.qry.follow;
				self_link(ctx.qry.follow ? "follow" : "unfollow", NULL, NULL);
				ctx.qry.follow = !ctx.qry.follow;
				html(")");
			}
			html("</span>");
		}
		if (pinned) {
			const char *hex = oid_to_hex(pinned);
			char *oid = ctx.qry.oid;

			html("<span class='rev'>rev: ");
			cgit_commit_link(cgit_fmt("%.*s", SHORT_HASH_LEN, hex),
				NULL, NULL, ctx.qry.head, hex, ctx.qry.vpath);
			html(" (");
			// self_link reads the pin out of ctx.qry, so lifting
			// it is what makes the link land back on the tip of
			// the branch.
			ctx.qry.oid = NULL;
			ctx.qry.has_oid = 0;
			self_link("latest", NULL, NULL);
			ctx.qry.oid = oid;
			ctx.qry.has_oid = 1;
			html(")</span>");
		}
		html("</nav>\n");
	}
	html("<main class='content'>\n");
}

void cgit_print_filemode(unsigned short mode)
{
	if (S_ISDIR(mode))
		html("d");
	else if (S_ISLNK(mode))
		html("l");
	else if (S_ISGITLINK(mode))
		html("m");
	else
		html("-");
	html_fileperm(mode >> 6);
	html_fileperm(mode >> 3);
	html_fileperm(mode);
}

// The tag names and their stems, a stem being the name with any leading v or V
// removed, gathered once per request. Claims on a stem are counted over the
// tag list itself rather than by looking refs up by name, because a loose ref
// lookup on a case-insensitive filesystem finds v1.2 when asked for V1.2 and
// would call every tag still stored loose ambiguous.
static struct string_list tag_names = STRING_LIST_INIT_DUP;
static struct string_list tag_stems = STRING_LIST_INIT_DUP;
static int tags_collected;

static int collect_tag(const struct reference *ref, void *data)
{
	const char *name = ref->name;

	string_list_append(&tag_names, name);
	if (name[0] == 'v' || name[0] == 'V')
		name++;
	string_list_append(&tag_stems, name);
	return 0;
}

/*
 * Whether ref is a tag whose stem no other tag shares.
 */
static int stem_is_unique(const char *ref)
{
	struct string_list_item *stem;
	size_t i;

	if (!tags_collected) {
		tags_collected = 1;
		refs_for_each_tag_ref(get_main_ref_store(the_repository), collect_tag, NULL);
		string_list_sort(&tag_names);
		string_list_sort(&tag_stems);
	}
	if (!string_list_has_string(&tag_names, ref))
		return 0;
	stem = string_list_lookup(&tag_stems, ref + 1);
	if (!stem)
		return 0;
	// The lookup lands on any one of equal entries, so both neighbours
	// are checked.
	i = stem - tag_stems.items;
	return (i == 0 || strcmp(tag_stems.items[i - 1].string, stem->string)) &&
		(i + 1 == tag_stems.nr || strcmp(tag_stems.items[i + 1].string, stem->string));
}

static void compose_snapshot_prefix(struct strbuf *filename, const char *base, const char *ref)
{
	// A tag named v1.2 or V1.2 gives its snapshot the prettier name 1.2,
	// but only where dropping the letter cannot land two different tags on
	// one name, so that a snapshot can still be traced back to the tag it
	// was made from.
	if ((ref[0] == 'v' || ref[0] == 'V') && isdigit((unsigned char)ref[1]) && stem_is_unique(ref))
		ref++;

	strbuf_addf(filename, "%s-%s", base, ref);
}

void cgit_print_snapshot_links(const struct cgit_repo *repo, const char *ref, const char *separator)
{
	const struct cgit_snapshot_format *f;
	struct strbuf filename = STRBUF_INIT;
	const char *basename;
	size_t prefixlen;

	basename = cgit_snapshot_prefix(repo);
	if (starts_with(ref, basename))
		strbuf_addstr(&filename, ref);
	else
		compose_snapshot_prefix(&filename, basename, ref);

	prefixlen = filename.len;
	for (f = cgit_snapshot_formats; f->suffix; f++) {
		if (!(repo->snapshots & cgit_snapshot_format_bit(f)))
			continue;
		strbuf_setlen(&filename, prefixlen);
		strbuf_addstr(&filename, f->suffix);
		snapshot_link(filename.buf, NULL, NULL, NULL, NULL, filename.buf);
		if (cgit_snapshot_get_sig(ref, f)) {
			strbuf_addstr(&filename, ".asc");
			html(" (");
			snapshot_link("sig", NULL, NULL, NULL, NULL, filename.buf);
			html(")");
		} else if (
			starts_with(f->suffix, ".tar") &&
			cgit_snapshot_get_sig(ref, &cgit_snapshot_formats[0])
		) {
			// A compressed tarball offers the signature made for
			// the plain tar it expands to, which is the first
			// format in the table.
			strbuf_setlen(&filename, filename.len - strlen(f->suffix));
			strbuf_addstr(&filename, ".tar.asc");
			html(" (");
			snapshot_link("sig", NULL, NULL, NULL, NULL, filename.buf);
			html(")");
		}
		html(separator);
	}
	strbuf_release(&filename);
}

void cgit_set_title_from_path(const char *path)
{
	struct strbuf sb = STRBUF_INIT;
	const char *slash, *last_slash;

	if (!path)
		return;

	// The path is read from the end so that the title names the file first
	// and the directories it sits in after it.
	last_slash = path + strlen(path);
	while ((slash = find_last_char(path, last_slash, '/'))) {
		strbuf_add(&sb, slash + 1, last_slash - slash - 1);
		strbuf_addstr(&sb, " < ");
		last_slash = slash;
	}
	strbuf_add(&sb, path, last_slash - path);
	strbuf_addf(&sb, " - %s", ctx.page.title);
	ctx.page.title = strbuf_detach(&sb, NULL);
}