Source

linux-scalability-benchmarks / gatling / http.c

The default branch has multiple heads

Full commit
   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
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
#ifndef __FreeBSD__
#define _XOPEN_SOURCE 500
#endif

#include "gatling.h"

#include "buffer.h"
#include "fmt.h"
#include "ip6.h"
#include "mmap.h"
#include "str.h"
#include "textcode.h"
#include "scan.h"
#include "socket.h"
#include "case.h"
#include "ip4.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#ifdef __dietlibc__
#include <md5.h>
#else
#include <openssl/md5.h>
#define MD5Init MD5_Init
#define MD5Update MD5_Update
#define MD5Final MD5_Final
#endif
#include <errno.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <ctype.h>
#include <sys/socket.h>
#include <limits.h>

#include "havealloca.h"

MD5_CTX md5_ctx;

char* http_header_blob(char* b,long l,char* h) {
  long i;
  long sl=str_len(h);
  for (i=0; i+sl+2<l; ++i)
    if (b[i]=='\n' && b[i+sl+1]==':' && case_equalb(b+i+1,sl,h)) {
      b+=i+sl+2;
      while (*b==' ' || *b=='\t') ++b;
      return b;
    }
  return 0;
}

char* http_header(struct http_data* r,char* h) {
  return http_header_blob(array_start(&r->r),array_bytes(&r->r),h);
}

static inline int issafe(unsigned char c) {
  return (c!='"' && c!='%' && c>=' ' && c!='+' && c!=':' && c!='#');
}

size_t fmt_urlencoded(char* dest,const char* src,size_t len) {
  register const unsigned char* s=(const unsigned char*) src;
  size_t written=0,i;
  for (i=0; i<len; ++i) {
    if (!issafe(s[i])) {
      if (dest) {
	dest[written]='%';
	dest[written+1]=fmt_tohex(s[i]>>4);
	dest[written+2]=fmt_tohex(s[i]&15);
      }
      written+=3;
    } else {
      if (dest) dest[written]=s[i]; ++written;
    }
  }
  return written;
}

void catencoded(array* a,char* s) {
  unsigned int len=str_len(s);
  char* buf=alloca(fmt_urlencoded(0,s,len));
  array_catb(a,buf,fmt_urlencoded(buf,s,len));
}

void cathtml(array* a,char* s) {
  unsigned int len=str_len(s);
  char* buf=alloca(fmt_html(0,s,len));
  array_catb(a,buf,fmt_html(buf,s,len));
}

int http_dirlisting(struct http_data* h,DIR* D,const char* path,const char* arg) {
  long i,o,n;
  struct dirent* d;
  int (*sortfun)(de*,de*);
  array a,b,c;
  de* ab;
  byte_zero(&a,sizeof(a));
  byte_zero(&b,sizeof(b));
  byte_zero(&c,sizeof(c));
  o=n=0;
  while ((d=readdir(D))) {
    de* x=array_allocate(&a,sizeof(de),n);
    if (!x) break;
    x->name=o;
#ifdef __MINGW32__
    if (stat(d->d_name,&x->ss)==-1) continue;
#else
    if (lstat(d->d_name,&x->ss)==-1) continue;
    if (S_ISLNK(x->ss.st_mode)) {
      struct stat tmp;
      if (stat(d->d_name,&tmp)==0)
	if (S_ISDIR(tmp.st_mode))
	  x->todir=1;
    }
#endif
    array_cats0(&b,d->d_name);
    o+=str_len(d->d_name)+1;
    ++n;
  }
  closedir(D);
  if (array_failed(&a) || array_failed(&b)) {
    array_reset(&a);
    array_reset(&b);
    return 0;
  }
  base=array_start(&b);
  sortfun=sort_name_a;
  if (arg) {
    if (str_equal(arg,"N=D")) sortfun=sort_name_d;
    else if (str_equal(arg,"N=A")) sortfun=sort_name_a;
    else if (str_equal(arg,"M=A")) sortfun=sort_mtime_a;
    else if (str_equal(arg,"M=D")) sortfun=sort_mtime_d;
    else if (str_equal(arg,"S=A")) sortfun=sort_size_a;
    else if (str_equal(arg,"S=D")) sortfun=sort_size_d;
  }
  qsort(array_start(&a),n,sizeof(de),(int(*)(const void*,const void*))sortfun);
  array_cats(&c,"<title>Index of ");
  array_cats(&c,path);
  array_cats(&c,"</title>\n<h1>Index of ");
  array_cats(&c,path);
  {
    char* tmp=http_header(h,"User-Agent");
    if (tmp && byte_equal(tmp,5,"Wget/"))
      array_cats(&c,"</h1>\n<table><tr><th>Name<th>Last Modified<th>Size\n");
    else {
      array_cats(&c,"</h1>\n<table><tr><th><a href=\"?N=");
      array_cats(&c,sortfun==sort_name_a?"D":"A");
      array_cats(&c,"\">Name</a><th><a href=\"?M=");
      array_cats(&c,sortfun==sort_mtime_a?"D":"A");
      array_cats(&c,"\">Last Modified</a><th><a href=\"?S=");
      array_cats(&c,sortfun==sort_size_a?"D":"A");
      array_cats(&c,"\">Size</a>\n");
    }
  }
  ab=array_start(&a);
  for (i=0; i<n; ++i) {
    char* name=base+ab[i].name;
    char buf[31];
    int j;
    struct tm* x=localtime(&ab[i].ss.st_mtime);
    if (name[0]=='.') {
      if (name[1]==0) continue; /* skip "." */
      if (name[1]!='.' || name[2]!=0)	/* skip dot-files */
	continue;
    }
    if (name[0]==':') name[0]='.';
    array_cats(&c,"<tr><td><a href=\"");
    catencoded(&c,base+ab[i].name);
    if (S_ISDIR(ab[i].ss.st_mode) || ab[i].todir) array_cats(&c,"/");
    array_cats(&c,"\">");
    cathtml(&c,base+ab[i].name);
#ifndef __MINGW32__
    if (S_ISLNK(ab[i].ss.st_mode)) array_cats(&c,"@"); else
#endif
    if (S_ISDIR(ab[i].ss.st_mode)) array_cats(&c,"/");
    array_cats(&c,"</a><td>");

    j=fmt_2digits(buf,x->tm_mday);
    j+=fmt_str(buf+j,"-");
    byte_copy(buf+j,3,months+3*x->tm_mon); j+=3;
    j+=fmt_str(buf+j,"-");
    j+=fmt_2digits(buf+j,(x->tm_year+1900)/100);
    j+=fmt_2digits(buf+j,(x->tm_year+1900)%100);
    j+=fmt_str(buf+j," ");
    j+=fmt_2digits(buf+j,x->tm_hour);
    j+=fmt_str(buf+j,":");
    j+=fmt_2digits(buf+j,x->tm_min);

    array_catb(&c,buf,j);
    array_cats(&c,"<td align=right>");
    array_catb(&c,buf,fmt_humank(buf,ab[i].ss.st_size));
  }
  array_cats(&c,"</table>");
  array_reset(&a);
  array_reset(&b);
  if (array_failed(&c)) return 0;
  h->bodybuf=array_start(&c);
  h->blen=array_bytes(&c);
  return 1;
}

int buffer_putlogstr(buffer* b,const char* s) {
  unsigned long l;
  char* x;
  for (l=0; s[l] && s[l]!='\r' && s[l]!='\n'; ++l) ;
  if (!l) return 0;
  x=alloca(l);
  return buffer_put(b,x,fmt_foldwhitespace(x,s,l));
}

#ifdef SUPPORT_PROXY
int add_proxy(const char* c) {
  struct cgi_proxy* x=malloc(sizeof(struct cgi_proxy));
  int i;
  if (!x) return -1;
  byte_zero(x,sizeof(struct cgi_proxy));
  if (c[1]=='/') {
    if (c[0]=='F')
      x->proxyproto=FASTCGI;
    else if (c[0]=='S')
      x->proxyproto=SCGI;
    else
      goto nixgut;
    c+=2;
  }
  i=scan_ip6if(c,x->ip,&x->scope_id);
  if (c[i]!='/') { nixgut: free(x); return -1; }
  c+=i+1;
  i=scan_ushort(c,&x->port);
  if (c[i]!='/') goto nixgut;
  c+=i+1;
  if (regcomp(&x->r,c,REG_EXTENDED)) goto nixgut;
  if (!last)
    cgis=last=x;
  else
    last->next=x; last=x;
  return 0;
}

static size_t fmt_strblob(char* dst,const char* str,const char* blob,size_t n) {
  size_t x;
  if (!dst) return strlen(str)+n+1;
  x=fmt_str(dst,str);
  memcpy(dst+x,blob,n);
  x+=n;
  dst[x]='\n';
  return x+1;
}

static size_t fmt_cgivars(char* dst,struct http_data* h,const char* uri,size_t urilen,const char* vhostdir,size_t* headers) {
  /* input:
   *   dst: destination buffer, may be NULL
   *   h: http context, used to get to HTTP request
   *   uri: pointer to decoded URI, truncated at '?', after leading '/'
   *   urilen: last char in regex match
   *     uri="script.php/path_info"
   *                    ^ uri+urilen
   *   vhostdir: virtual hosting dir, e.g. "www.fefe.de:80" or "default"
   *   needs global: char serverroot[]
   * output:
   *   returns number of bytes written to dst
   *   if dst is NULL, returns number of buffer size needed
   *   writes environment entries to dst, separated by \n
   *   writes count of headers written to *headers if non-NULL
   */
  char remoteaddr[IP6_FMT];
  char myaddr[IP6_FMT];
  char tmp[FMT_ULONG];
  size_t n,s;
  s=0;

  while (urilen && uri[0]=='/') { ++uri; --urilen; }

  remoteaddr[fmt_ip6c(remoteaddr,h->peerip)]=0;
  myaddr[fmt_ip6c(myaddr,h->myip)]=0;

  {
    char* x=http_header(h,"Content-Length");
    if (x) {
      size_t j=str_chr(x,'\n'); if (j && x[j-1]=='\r') { --j; }
      n=fmt_strblob(dst,"CONTENT_LENGTH=",x,j);
    } else {
      n=fmt_str(dst,"CONTENT_LENGTH=0\n");
    }
    s+=n; if (dst) dst+=n;
  }

  n=fmt_strm(dst,"SERVER_SOFTWARE=",RELEASE,"\n"); s+=n; if (dst) dst+=n;
  {
    char* x=http_header(h,"Host");
    if (x) {
      size_t j=str_chr(x,'\n'); if (j && x[j-1]=='\r') { --j; }
      n=fmt_strblob(dst,"SERVER_NAME=",x,j);
    } else
      n=fmt_strm(dst,"SERVER_NAME=",remoteaddr,"\n");
    s+=n; if (dst) dst+=n;
  }
  n=fmt_strm(dst,"SERVER_ADDR=",myaddr,"\n"); s+=n; if (dst) dst+=n;
  tmp[fmt_ulong(tmp,h->myport)]=0;
  n=fmt_strm(dst,"SERVER_PORT=",tmp,"\n"); s+=n; if (dst) dst+=n;
  n=fmt_strm(dst,"REMOTE_ADDR=",remoteaddr,"\n"); s+=n; if (dst) dst+=n;
  tmp[fmt_ulong(tmp,h->peerport)]=0;
  n=fmt_strm(dst,"REMOTE_PORT=",tmp,"\n"); s+=n; if (dst) dst+=n;
  n=fmt_strm(dst,"GATEWAY_INTERFACE=CGI/1.1\nSERVER_PROTOCOL=HTTP/1.1\n"); s+=n; if (dst) dst+=n;
  {
    char* x=array_start(&h->r);
    size_t z,y=str_chr(x,' ');
    n=fmt_strblob(dst,"REQUEST_METHOD=",x,y); s+=n; if (dst) dst+=n;
    x+=y+1;
    y=str_chr(x,' ');
    /* REQUEST_URI is not actually part of the CGI 1.1 spec (RFC3875) */
    n=fmt_strblob(dst,"REQUEST_URI=",x,y); s+=n; if (dst) dst+=n;
    z=byte_chr(x,y,'?')+1;
    if (z<y) {
      n=fmt_strblob(dst,"QUERY_STRING=",x+z,y-z); s+=n; if (dst) dst+=n;
    }

    n=fmt_strblob(dst,"SCRIPT_NAME=/",uri,urilen); s+=n; if (dst) dst+=n;
    n=fmt_strm(dst,"SCRIPT_FILENAME=",serverroot,"/",vhostdir); s+=n; if (dst) dst+=n;
    n=fmt_strblob(dst,"/",uri,urilen); s+=n; if (dst) dst+=n;

    if (uri[urilen]=='/') {	/* we have a PATH_INFO */
      /* the situation is like this:
	 uri="script.cgi/pathinfo"
	                ^urilen
      */

      n=fmt_strm(dst,"PATH_INFO=",uri+urilen,"\n"); s+=n; if (dst) dst+=n;

      /* PATH_TRANSLATED is "$PWD$PATH_INFO" */
      while (uri[urilen]=='/') ++urilen;
      n=fmt_strm(dst,"PATH_TRANSLATED=",serverroot,"/",vhostdir,"/",uri+urilen,"\n"); s+=n; if (dst) dst+=n;
    }

  }

  /* now translate all header lines into HTTP_* */
  /* for example Accept: -> HTTP_ACCEPT= */
  {
    size_t hc=16;
    char* x=array_start(&h->r);
    x=strchr(x,'\n');
    while (x) {
      char* olddst=dst;
      ++x;
      if (*x<=' ') break;
      if (!case_starts(x,"Content-Length:") && !case_starts(x,"Content-Type:")) {
	n=fmt_strm(dst,"HTTP_"); s+=n; if (dst) dst+=n;
      }
      while (*x!=':') {
	char c=*x;
	if (c>='a' && c<='z') c-='a'-'A';
	if (c=='-') c='_'; else
	if (c<'A' || c>'Z') {
	  dst=olddst;
	  goto skipheader;
	}
	if (dst) { *dst=c; ++dst; } ++s;
	++x;
      }
      if (dst) { *dst='='; ++dst; } ++s;
      ++x; while (*x==' ') ++x;
      {
	char* start=x;
	while (*x && *x!='\r' && *x!='\n') ++x;
	n=x-start;
	if (dst) { byte_copy(dst,n,start); dst+=n+1; dst[-1]='\n'; } s+=n+1;
      }
      ++hc;
skipheader:
      x=strchr(x,'\n');
    }
    if (headers) *headers=hc;
  }
  return s;
}

static int proxy_connection(int sockfd,char* c,const char* dir,struct http_data* ctx_for_sockfd,int isexec,const char* args) {
  /* c is the filename
   * dir is the virtual hosting dir ("www.fefe.de:80")
   * the current working directory is inside the virtual hosting dir */
  struct cgi_proxy* x=cgis;
  struct stat ss;
  regmatch_t matches;

  /* if isexec is set, we already found that .proxy is there */
  if (!isexec && stat(".proxy",&ss)==-1) return -3;
  while (x) {
    if (x->file_executable && (!isexec || x->port)) {
      x=x->next;
      continue;
    }

    matches.rm_so=matches.rm_eo=0;
    if (x->file_executable || regexec(&x->r,c,1,&matches,0)==0) {
      /* if the port is zero, then use local execution proxy mode instead */
      int fd_to_gateway;
      struct http_data* ctx_for_gatewayfd;
      char* d=c;
      while (*d=='/') ++d;

      ctx_for_sockfd->proxyproto=x->proxyproto;

      if (!(ctx_for_gatewayfd=(struct http_data*)malloc(sizeof(struct http_data)))) return -1;
      byte_zero(ctx_for_gatewayfd,sizeof(struct http_data));

      if (!x->file_executable) {

#if 0
	printf("%u %u\n",matches.rm_so,matches.rm_eo);
	printf("got data \"%s\"\n",c+matches.rm_eo);
#endif

	if (x->proxyproto == SCGI || x->proxyproto == FASTCGI) {
	  struct stat ss;
	  /* does the file actually exist? */
	  if (stat(d,&ss)) {
	    if (errno==ENOTDIR) {	/* we have PATH_INFO */
	      char save=c[matches.rm_eo];
	      int r;
	      c[matches.rm_eo]=0;
	      r=stat(d,&ss);
	      c[matches.rm_eo]=save;
	      if (r) goto freeandfail;
	    } else {
freeandfail:
	      free(ctx_for_gatewayfd);
	      return -1;
	    }
	  }
	}
	ctx_for_gatewayfd->proxyproto=x->proxyproto;
	if (x->proxyproto == SCGI) {
	  size_t l=fmt_cgivars(0,ctx_for_sockfd,c,matches.rm_eo,dir,0)+sizeof("SCGI=1");
	  char* x,* y;
	  if (!array_allocate(&ctx_for_gatewayfd->r,1,l+fmt_ulong(0,l)+3))
	    goto freeandfail;
	  x=array_start(&ctx_for_gatewayfd->r);
	  x+=fmt_ulong(x,l);
	  *x++=':';
	  y=x;
	  x+=fmt_cgivars(x,ctx_for_sockfd,c,matches.rm_eo,dir,0);
	  x+=fmt_str(x,"SCGI=1\n");

	  /* fmt_cgivars uses "FOO=bar\n" but we want "FOO\000bar\000" */
	  while (y<x) {
	    if (*y=='=') {
	      *y=0;
	      while (y<x) {
		if (*y=='\n') { *y=0; break; }
		++y;
	      }
	    }
	    ++y;
	  }

	  *x=',';
	} else if (x->proxyproto == FASTCGI) {
	  size_t hc;
	  size_t l=fmt_cgivars(0,ctx_for_sockfd,c,matches.rm_eo,dir,&hc);
	  char* x,* y;
	  /* fmt_cgivars writes "FOO=barbaz\n" but we need
	   * "\003\006FOObarbaz"; if a key or value is longer than 127,
	   * the length takes up four bytes instead of one.  A
	   * conservative upper bound on additional space used is 
	   * thus the number of headers (hc) times 6. */

	  /* space calculation with fastcgi boilerplate overhead:
	   * 16 for {FCGI_BEGIN_REQUEST,   1, {FCGI_RESPONDER, 0}}
	   * 8 for {FCGI_PARAMS,          1,
	   * l for the actual params
	   * 8 for {FCGI_PARAMS,          1, ""}
	   * 8 for {FCGI_STDIN,           1, ""}
	   */
	  if (!array_allocate(&ctx_for_gatewayfd->r,1,l+hc*6+16+8+8+8+2))
	    goto freeandfail;
	  x=array_start(&ctx_for_gatewayfd->r);
	  byte_copy(x,24,"\x01\x01\x00\x01\x00\x08\x00\x00" /* FCGI_Record: FCGI_BEGIN_REQUEST (1) */
			 "\x00\x01\x00\x00\x00\x00\x00\x00" /* FCGI_BeginRequestBody */
			 "\x01\x04\x00\x01\x00\x00\x00\x00" /* FCGI_Record: FCGI_PARAMS (4) */
			);
	  /* We need to convert the key-value pairs, but unfortunately
	   * that expansion may require more space than the unexpanded
	   * version.  So we allocate for the worst case and write the
	   * original towards the end of the allocated space, so we can
	   * expand inside the same buffer. */
	  y=x+hc*6+16+8+8+8+2;
	  fmt_cgivars(y,ctx_for_sockfd,c,matches.rm_eo,dir,&hc);
	  x+=24;
	  {
	    size_t a=0;
	    size_t b;
	    size_t kl,vl,prev;
	    for (b=kl=vl=prev=0; b<l; ++b) {
	      if (y[b]=='=') {
		kl=b-prev;
		prev=b+1;
	      } else if (y[b]=='\n') {
		vl=b-prev;
		prev=b+1;
		if (kl<127) {
		  x[a]=kl;
		  ++a;
		} else {
		  uint32_pack_big(x+a,kl|0x80000000u);
		  a+=4;
		}
		if (vl<127) {
		  x[a]=vl;
		  ++a;
		} else {
		  uint32_pack_big(x+a,vl|0x80000000u);
		  a+=4;
		}
		byte_copy(x+a,kl,y+b-vl-kl-1); a+=kl;
		byte_copy(x+a,vl,y+b-vl); a+=vl;
	      }
	    }
	    x[a]=x[a+1]=0; a+=2;
	    x[-4]=a>>8;	/* adjust length field in FCGI_Record */
	    x[-3]=a&0xff;
	    array_truncate(&ctx_for_gatewayfd->r,1,a+24+8+8);
	    x+=a;
	    byte_copy(x,8,"\x01\x04\x00\x01\x00\x00\x00\x00"); /* FCGI_Record: FCGI_PARAMS (4) */
	    x+=8;

	    {
	      char* cl=http_header(ctx_for_sockfd,"Content-Length");
	      unsigned long long content_length=0;
	      if (cl) {
		char c;
		if ((c=cl[scan_ulonglong(cl,&content_length)])!='\r' && c!='\n') content_length=0;
	      }
	      if (content_length)
		array_truncate(&ctx_for_gatewayfd->r,1,a+24+8); /* shave off 8 bytes */
	      else {
		byte_copy(x,8,"\x01\x05\x00\x01\x00\x00\x00\x00"); /* FCGI_Record: FCGI_STDIN (5) */
		x+=8;
	      }
	    }
	  }
	}
      }

      if (logging) {
	char buf[IP6_FMT+10];
	char* tmp;
	const char* method="???";
	{
	  int x;
	  x=fmt_ip6c(buf,ctx_for_gatewayfd->myip);
	  x+=fmt_str(buf+x,"/");
	  x+=fmt_ulong(buf+x,ctx_for_gatewayfd->myport);
	  buf[x]=0;
	}
	tmp=array_start(&ctx_for_sockfd->r);
#ifdef SUPPORT_HTTPS
	switch (*tmp) {
	case 'H': method=(ctx_for_sockfd->t==HTTPREQUEST)?"HEAD":"HEAD/SSL"; break;
	case 'G': method=(ctx_for_sockfd->t==HTTPREQUEST)?"GET":"GET/SSL"; break;
	case 'P':
		  if (tmp[1]=='O')
		    method=(ctx_for_sockfd->t==HTTPREQUEST)?"POST":"POST/SSL";
		  else
		    method=(ctx_for_sockfd->t==HTTPREQUEST)?"PUT":"PUT/SSL";
		  break;
	}
#else
	switch (*tmp) {
	case 'H': method="HEAD"; break;
	case 'G': method="GET"; break;
	case 'P': method=(tmp[1]=='O')?"POST":"PUT"; break;
	}
#endif
	buffer_putm(buffer_1,method,x->port?"/PROXY ":"/CGI ");
	buffer_putulong(buffer_1,sockfd);
	buffer_puts(buffer_1," ");
	buffer_putlogstr(buffer_1,c);
	if (args) {
	  buffer_puts(buffer_1,"?");
	  buffer_putlogstr(buffer_1,args);
	}
	buffer_puts(buffer_1," 0 ");
	buffer_putlogstr(buffer_1,(tmp=http_header(ctx_for_sockfd,"User-Agent"))?tmp:"[no_user_agent]");
	buffer_puts(buffer_1," ");
	buffer_putlogstr(buffer_1,(tmp=http_header(ctx_for_sockfd,"Referer"))?tmp:"[no_referrer]");
	buffer_puts(buffer_1," ");
	buffer_putlogstr(buffer_1,(tmp=http_header(ctx_for_sockfd,"Host"))?tmp:buf);
	buffer_putsflush(buffer_1,"\n");
      }
      ++rps1;

      if (x->port) {
	/* proxy mode */
	changestate(ctx_for_gatewayfd,PROXYSLAVE);
	fd_to_gateway=socket_tcp6();
#ifdef STATE_DEBUG
	ctx_for_gatewayfd->myfd=fd_to_gateway;
#endif
	if (fd_to_gateway==-1) goto punt2;
	if (!io_fd(fd_to_gateway)) {
punt:
	  io_close(fd_to_gateway);
punt2:
	  free(ctx_for_gatewayfd);
	  return -1;
	}
	io_block(fd_to_gateway);
	io_eagain(fd_to_gateway);
	if (socket_connect6(fd_to_gateway,x->ip,x->port,x->scope_id)==-1)
	  if (errno!=EINPROGRESS)
	    goto punt;
	if (logging) {
	  char tmp[100];
	  char bufsockfd[FMT_ULONG];
	  char bufs[FMT_ULONG];
	  char bufport[FMT_ULONG];

	  bufsockfd[fmt_ulong(bufsockfd,sockfd)]=0;
	  bufs[fmt_ulong(bufs,fd_to_gateway)]=0;
	  bufport[fmt_ulong(bufport,x->port)]=0;
	  tmp[fmt_ip6ifc(tmp,x->ip,x->scope_id)]=0;

	  buffer_putm(buffer_1,"proxy_connect ",bufsockfd," ",bufs," ",tmp," ",bufport," ");
	  buffer_putlogstr(buffer_1,c);
	  buffer_putnlflush(buffer_1);
	}
	io_wantwrite(fd_to_gateway);
#ifdef SUPPORT_CGI
      } else {
	/* local CGI mode */
	uint32 a,len; uint16 b;
	pid_t pid;
	size_t reqlen;
	char* req=array_start(&ctx_for_sockfd->r); /* "GET /t.cgi/foo/bar?fnord HTTP/1.0\r\nHost: localhost:80\r\n\r\n"; */
	char ra[IP6_FMT];
	req[strlen(req)]=' ';

	{
	  char* tmp;
	  reqlen=0;
	  for (tmp=req; tmp; tmp=strchr(tmp,'\n')) {
	    if (tmp[1]=='\r' && tmp[2]=='\n') {
	      reqlen=tmp+2-req;
	      break;
	    } else if (tmp[1]=='\n') {
	      reqlen=tmp+1-req;
	      break;
	    }
	    ++tmp;
	  }
	}

	ctx_for_sockfd->keepalive=0;
	ra[fmt_ip6c(ra,ctx_for_sockfd->peerip)]=0;
	a=reqlen; write(forksock[0],&a,4);
	a=strlen(dir); write(forksock[0],&a,4);
	a=strlen(ra); write(forksock[0],&a,4);
	write(forksock[0],req,reqlen);
	write(forksock[0],dir,strlen(dir));
	write(forksock[0],ra,strlen(ra));
	b=ctx_for_sockfd->peerport; write(forksock[0],&b,2);
	b=ctx_for_sockfd->myport; write(forksock[0],&b,2);

	read(forksock[0],&a,4);		/* code; 0 means OK */
	read(forksock[0],&len,4);	/* length of error message */
	read(forksock[0],&pid,sizeof(pid));
	if (len) {
	  char* c=alloca(len+1);
	  read(forksock[0],c,len);
	  c[len]=0;
	  httperror(ctx_for_sockfd,"502 Gateway Broken",c,*ctx_for_sockfd->r.p=='H'?1:0);
	  free(ctx_for_gatewayfd);
	  return -1;
	} else {
	  fd_to_gateway=io_receivefd(forksock[0]);
#ifdef STATE_DEBUG
	  ctx_for_gatewayfd->myfd=fd_to_gateway;
#endif
	  changestate(ctx_for_gatewayfd,PROXYPOST);
	  if (fd_to_gateway==-1) {
	    buffer_putsflush(buffer_2,"received no file descriptor for CGI\n");
	    free(ctx_for_gatewayfd);
	    return -1;
	  }
	  if (!io_fd(fd_to_gateway)) {
	    httperror(ctx_for_sockfd,"502 Gateway Broken",c,*ctx_for_sockfd->r.p=='H'?1:0);
	    io_close(fd_to_gateway);
	    free(ctx_for_gatewayfd);
	    return -1;
	  }
	}
#ifdef SUPPORT_HTTPS
	if (ctx_for_sockfd->t==HTTPSREQUEST)
	  changestate(ctx_for_sockfd,HTTPSPOST);
	else
#endif
	changestate(ctx_for_sockfd,HTTPPOST);
	if (logging) {
	  char bufsfd[FMT_ULONG];
	  char bufs[FMT_ULONG];
	  char bufpid[FMT_ULONG];

	  bufsfd[fmt_ulong(bufsfd,sockfd)]=0;
	  bufs[fmt_ulong(bufs,fd_to_gateway)]=0;
	  bufpid[fmt_ulong(bufpid,pid)]=0;

	  buffer_putmflush(buffer_1,"cgi_fork ",bufsfd," ",bufs," ",bufpid,"\n");
	}
#endif
      }
      ctx_for_gatewayfd->buddy=sockfd;
      ctx_for_sockfd->buddy=fd_to_gateway;
      io_setcookie(fd_to_gateway,ctx_for_gatewayfd);

     /* Have:
      *   - the header and possibly some data left in ctx_for_sockfd->r.
      * Want:
      *   - leave the data (not the header) in ctx_for_sockfd->r.
      *   - set ctl_for_gatewayfd->still_to_copy to Content-Length.
      *   - set ctl_for_sockfd->still_to_copy to Content-Length -
      *     the size of the copied data.  If that is non-zero, set t to
      *     HTTPPOST.
      */

      {
	char* cl=http_header(ctx_for_sockfd,"Content-Length");
	unsigned long long content_length=0;
	if (cl) {
	  char c;
	  if ((c=cl[scan_ulonglong(cl,&content_length)])!='\r' && c!='\n') content_length=0;
	}

	ctx_for_gatewayfd->still_to_copy=content_length;

	/* If the client sent "Expect: 100-continue", do so */
	{
	  char* e=http_header(ctx_for_sockfd,"Expect");
	  if (e && byte_equal(e,4,"100-")) {
	    const char contmsg[]="HTTP/1.1 100 Continue\r\n\r\n";
	    /* if this fails, tough luck.  I'm not bloating my state
	      * engine for this crap. */
	    io_trywrite(sockfd,contmsg,sizeof(contmsg)-1);
	  }
	}

	/* figure out how much data we have */
	{
	  size_t size_of_header=header_complete(ctx_for_sockfd);
	  size_t size_of_data_in_packet=array_bytes(&ctx_for_sockfd->r) - size_of_header - 1;
	    /* the -1 is for the \0 we appended */

	  changestate(ctx_for_sockfd,HTTPPOST);
	  if (size_of_data_in_packet) {
	    byte_copy(array_start(&ctx_for_sockfd->r),
		      size_of_data_in_packet,
		      array_start(&ctx_for_sockfd->r)+size_of_header);
	    array_truncate(&ctx_for_sockfd->r,1,size_of_data_in_packet);
/*
	    if (content_length>size_of_data_in_packet)
	      ctx_for_sockfd->still_to_copy-=size_of_data_in_packet;
	    else
	      ctx_for_sockfd->still_to_copy=0;
*/
	  } else {
	    array_trunc(&ctx_for_sockfd->r);
	    ctx_for_sockfd->still_to_copy=content_length;
	  }

	  if (ctx_for_gatewayfd->still_to_copy && array_bytes(&ctx_for_sockfd->r))
	    io_wantwrite(fd_to_gateway);
	  else
	    io_wantread(fd_to_gateway);

	  if (ctx_for_sockfd->still_to_copy)
	    io_wantread(sockfd);
	  else
	    io_dontwantread(sockfd);

	}
      }

      if (timeout_secs)
	io_timeout(fd_to_gateway,next);
      return fd_to_gateway;
    }
    x=x->next;
  }
  return -2;
}

int proxy_write_header(int sockfd,struct http_data* h) {
  /* assume we can write the header in full. */
  /* slight complication: we need to turn keep-alive off and we need to
   * add a X-Forwarded-For header so the handling web server can write
   * the real IP to the log file. */
  struct http_data* H=io_getcookie(h->buddy);
  int i,j=0;
  long hlen=array_bytes(&h->r);
  char* hdr=array_start(&h->r);
  char* newheader=0;
  if (h->proxyproto==HTTP) {
    newheader=alloca(hlen+200);
    for (i=j=0; i<hlen; ) {
      int k=str_chr(hdr+i,'\n');
      if (k==0) break;
      if (case_starts(hdr+i,"Connection: ") || case_starts(hdr+i,"X-Forwarded-For: "))
	i+=k+1;
      else {
	byte_copy(newheader+j,k+1,hdr+i);
	i+=k+1;
	j+=k+1;
      }
    }
    if (j) j-=2;
    H->keepalive=0;
    j+=fmt_str(newheader+j,"Connection: close\r\nX-Forwarded-For: ");
    j+=fmt_ip6c(newheader+j,H->peerip);
    j+=fmt_str(newheader+j,"\r\n\r\n");
  } else if (h->proxyproto==FASTCGI || h->proxyproto==SCGI) {
    newheader=array_start(&h->r);
    j=array_bytes(&h->r);
  }
  if (write(sockfd,newheader,j)!=j)
    return -1;
  if (h->proxyproto==SCGI)
    array_trunc(&h->r);
  H->sent+=j;
  return 0;
}



int proxy_is_readable(int sockfd,struct http_data* H) {
  /* read data from proxy and queue it for writing to browser
   * connection, also add "HTTP/1.0 200 OK" header if necessary */
  char Buf[8194];
  char* buf=Buf+1;
  int i;
  char* x;
  struct http_data* peer=io_getcookie(H->buddy);
  if (!peer) return -1;
  i=read(sockfd,buf,sizeof(Buf)-2);
  if (i==-1) return -1;
  H->sent+=i;
  /* TODO: need to parse fastcgi packets from proxy, remove fastcgi
   * headers */
  if (i==0) {
eof:
    if (logging) {
      char numbuf[FMT_ULONG];
      char r[FMT_ULONG];
      char s[FMT_ULONG];
      numbuf[fmt_ulong(numbuf,sockfd)]=0;
      r[fmt_ulonglong(r,peer->received)]=0;
      s[fmt_ulonglong(s,peer->sent)]=0;
      buffer_putmflush(buffer_1,"cgiproxy_read0 ",numbuf," ",r," ",s,"\n");
    }
    if (H->buddy) peer->buddy=-1;
    cleanup(sockfd);
    io_close(sockfd);
    return -3;
  } else {
    int needheader=0;
    size_t cl=0,rs=0;
    int gotone=0;

    if (H->proxyproto==FASTCGI) {
      /* For FastCGI, we get the data in packets, which we need to parse.
      * Which also means we have to deal with partial packets.  We do
      * this by putting the packets in our H->r until we have assembled
      * one. */
      array_catb(&H->r,buf,i);
      if (array_failed(&H->r)) return -1;
nextpacket:
      x=array_start(&H->r);
      rs=array_bytes(&H->r);
      if (rs<8) return 0;	/* not done, need more data */
      /* we have a header */
      errno=EINVAL;
      if (x[0]!=1) return -1;
      /* we expect one of FCGI_STDOUT, FCGI_STDERR, or
	* FCGI_END_REQUEST */
      if (x[1]!=6 && x[1]!=7 && x[1]!=3) return -1;
      /* the request ID must be 1, because that is what we sent */
      if (x[2]!=0 || x[3]!=1) return -1;
      cl=(x[4]<<8)|x[5];
      if (rs<8+cl+(unsigned char)(x[6])) {
	if (gotone) goto success;
	return 0;	/* not done, need more data */
      }
      /* got enough data for one packet.  look at packet. */
      if (x[1]==3) {
	io_wantwrite(H->buddy);
	H->buddy=-1;
	goto eof;	/* FCGI_END_REQUEST */
      }
      if (x[1]==6) { /* FCGI_STDOUT */
	buf=x+8;
	i=cl;
      }
    }

    if (!H->havefirst) {
      H->havefirst=1;
      if (H->proxyproto==SCGI) {
	if (case_starts(buf,"Status:")) {
	  --buf; ++i;
	  memcpy(buf,"HTTP/1.1 ",9);
	  ++i;
	} else
	  needheader=1;
      } else if (byte_diff(buf,5,"HTTP/"))
	/* No "HTTP/1.0 200 OK", need to write our own header. */
	needheader=1;
    }
    if (needheader) {
      size_t j;
      x=malloc(i+100);
      if (!x) goto nomem;
      j=fmt_str(x,"HTTP/1.1 200 Here you go\r\nServer: " RELEASE "\r\n");
      byte_copy(x+j,i,buf);
      i+=j;
    } else {
      x=malloc(i);
      if (!x) goto nomem;
      byte_copy(x,i,buf);
    }
    iob_addbuf_free(&peer->iob,x,i);
    gotone=1;

    if (H->proxyproto==FASTCGI) {
    /* now, if we got this far, we need to remove the packet from the
     * buffer */
      x=array_start(&H->r);
      cl+=8;
      if (rs>cl) byte_copy(x,rs-cl,x+cl);
      array_truncate(&H->r,1,rs-cl);
      if (rs>cl && rs-cl>=8) goto nextpacket;
    }
  }
success:
  io_dontwantread(sockfd);
  io_wantwrite(H->buddy);
  return 0;
nomem:
  if (logging) {
    char numbuf[FMT_ULONG];
    numbuf[fmt_ulong(numbuf,sockfd)]=0;
    buffer_putmflush(buffer_1,"outofmemory ",numbuf,"\n");
  }
  cleanup(sockfd);
  return -1;
}

int read_http_post(int sockfd,struct http_data* H) {
  /* read post data from browser, write to proxy */
  char buf[8192];
  int i;
  unsigned long long l=H->still_to_copy;
  if (l>sizeof(buf)) l=sizeof(buf);
#ifdef SUPPORT_HTTPS
  if (H->t==HTTPSPOST) {
    i=SSL_read(H->ssl,buf,l);
    if (i<0) {
      i=SSL_get_error(H->ssl,i);
      if (l==SSL_ERROR_WANT_READ || l==SSL_ERROR_WANT_WRITE) {
	io_eagain(sockfd);
	if (handle_ssl_error_code(sockfd,i,1)==-1)
	  return -1;
      }
      return 0;
    }
  } else
#endif
  i=read(sockfd,buf,l);
//  printf("read_http_post: want to read %ld bytes from %d; got %d\n",l,sockfd,i);
  if (i<1) return -1;

  H->received+=i;
  H->still_to_copy-=i;
//  printf("still_to_copy read_http_post: %p %llu -> %llu\n",H,H->still_to_copy+i,H->still_to_copy);
  /* we got some data.  Now, for FastCGI we need to add a header before
   * writing it to the proxy */
  if (H->proxyproto==FASTCGI) {
    char tmp[8]="\x01\x05\x00\x01\x00\x00\x00\x00";
    tmp[4]=i>>8;
    tmp[5]=i&0xff;
    array_catb(&H->r,tmp,8); /* FCGI_Record: FCGI_STDIN (5) */
  }
  array_catb(&H->r,buf,i);
  if (H->proxyproto==FASTCGI && H->still_to_copy==0)
    array_catb(&H->r,"\x01\x05\x00\x01\x00\x00\x00\x00",8); /* FCGI_Record: FCGI_STDIN (5) */
  if (array_failed(&H->r))
    return -1;
  return 0;
}

#endif




#ifdef SUPPORT_HTACCESS
/* check whether there is a .htaccess file in the current directory.
 * if it is, expect the following format:

Realm
username:password
username2:password2
...

 * Realm is the HTTP realm (transmitted in the http authentication
 * required message and usually displayed by the browser).  Only basic
 * authentication is supported.  Please note that .htaccess files are
 * not looked for in other directories.  If you want subdirectories
 * covered, use hard or symbolic links.  The function returns 0 if the
 * authentication was OK or -1 if authentication is needed (the HTTP
 * response was then already written to the iob). */
int http_dohtaccess(struct http_data* h,const char* filename,int nobody) {
  size_t filesize;
  char* map;
  char* s;
  char* auth;
  char* realm;
  int r=0;
  map=mmap_read(filename,&filesize);
  if (!map) return 1;
  for (s=map; (s<map+filesize) && (*s!='\n'); ++s);		/* XXX */
  if (s>=map+filesize) goto done;
  realm=alloca(s-map+1);
  memmove(realm,map,s-map);
  realm[s-map]=0;
  ++s;
  auth=http_header(h,"Authorization");
  if (auth) {
    if (str_start(auth,"Basic ")) {
      char* username,* password;
      char* decoded;
      int i;
      size_t l,dl,ul;
      auth+=6;
      while (*auth==' ' || *auth=='\t') ++auth;
      i=str_chr(auth,'\n');
      if (i && auth[i-1]=='\r') --i;
      decoded=alloca(i+1);
      l=scan_base64(auth,decoded,&dl);
      if (auth[l]!='\n' && auth[l]!='\r') goto needauth;
      decoded[dl]=0;
      l=str_rchr(decoded,':');
      if (decoded[l]!=':') goto needauth;
      username=decoded; ul=l;
      decoded[l]=0; password=decoded+l+1;

      for (l=0; l<filesize; ) {
	while (l<filesize && map[l]!='\n') ++l; if (map[l]=='\n') ++l;
	if (l>=filesize) break;
	if (byte_equal(map+l,ul,username) && map[l+ul]==':') {
	  char* crypted=crypt(password,map+l+ul+1);
	  i=str_len(crypted);
	  if (l+ul+1+i <= filesize)
	    if (byte_equal(map+l+ul+1,i,crypted)) {
	      r=1;
	      goto done;
	    }
	}
      }
    }
  }
needauth:
  httperror_realm(h,"401 Authorization Required","Authorization required to view this web page",realm,nobody);
done:
  munmap(map,filesize);
  return r;
}
#endif

int http_redirect(struct http_data* h,const char* Filename) {
#ifndef __MINGW32__
  char buf[2048];
  int i;
  if ((i=readlink(Filename,buf,sizeof(buf)))!=-1) {
    buf[i]=0;
    if (strstr(buf,"://")) {
      h->bodybuf=malloc(strlen(buf)+300);
      h->hdrbuf=malloc(strlen(buf)+300);
      if (h->bodybuf && h->hdrbuf) {
	int i;
	i=fmt_str(h->bodybuf,"Look <a href=\"");
	i+=fmt_str(h->bodybuf+i,buf);
	i+=fmt_str(h->bodybuf+i,"\">here</a>!\n");
	h->blen=i;

	i=fmt_str(h->hdrbuf,"HTTP/1.0 301 Go Away\r\nConnection: ");
	i+=fmt_str(h->hdrbuf+i,h->keepalive?"keep-alive":"close");
	i+=fmt_str(h->hdrbuf+i,"\r\nServer: " RELEASE "\r\nContent-Length: ");
	i+=fmt_ulong(h->hdrbuf+i,h->blen);
	i+=fmt_str(h->hdrbuf+i,"\r\nLocation: ");
	i+=fmt_str(h->hdrbuf+i,buf);
	i+=fmt_str(h->hdrbuf+i,"\r\n\r\n");
	h->hlen=i;
	return -4;
      }
      free(h->bodybuf); free(h->hdrbuf);
    }
  }
#endif
  return 0;
}

int64 http_openfile(struct http_data* h,char* filename,struct stat* ss,int sockfd,int nobody) {
#ifdef SUPPORT_PROXY
  int noproxy=0;
#endif
  char* dir=0;
  char* s;
  char* args;
  size_t i;
  int64 fd;
  int doesgzip;
#ifdef SUPPORT_BZIP2
  int doesbzip2;
#endif

  char* Filename;

  doesgzip=0; h->encoding=NORMAL;
#ifdef SUPPORT_BZIP2
  doesbzip2=0;
#endif
  {
    char* tmp=http_header(h,"Accept-Encoding");
    if (tmp) {	/* yeah this is crude, but it gets the job done */
      int end=str_chr(tmp,'\n');
      for (i=0; i+4<end; ++i)
	if (byte_equal(tmp+i,4,"gzip"))
	  doesgzip=1;
#ifdef SUPPORT_BZIP2
	else if (byte_equal(tmp+i,4,"bzip2"))
	  doesbzip2=1;
#endif
    }
  }

  args=0;
  /* the file name needs to start with a / */
  if (filename[0]!='/') return -1;


  /* first, we need to strip "?.*" from the end */
  i=str_chr(filename,'?');
  Filename=alloca(i+5);	/* enough space for .gz and .bz2 */
  byte_copy(Filename,i+1,filename);
  if (Filename[i]=='?') { Filename[i]=0; args=filename+i+1; }
  /* second, we need to un-urlencode the file name */
  /* we can do it in-place, the decoded string can never be longer */
  scan_urlencoded2(Filename,Filename,&i);
  Filename[i]=0;
  /* third, change /. to /: so .procmailrc is visible in ls as
   * :procmailrc, and it also thwarts most web root escape attacks */
  for (i=0; Filename[i]; ++i)
    if (Filename[i]=='/' && Filename[i+1]=='.')
      Filename[i+1]=':';
  /* fourth, try to do some el-cheapo virtual hosting */
  if (!(s=http_header(h,"Host"))) {
    /* construct artificial Host header from IP */
    s=alloca(IP6_FMT+7);
    i=fmt_ip6c(s,h->myip);
    i+=fmt_str(s+i,":");
    i+=fmt_ulong(s+i,h->myport);
    s[i]=0;
  } else {
    if (virtual_hosts>=0) {
      char* tmp;
      int j=str_chr(s,'\r');
      /* replace port in Host: with actual port */
      if (!s[i=str_chr(s,':')] || i>j || !transproxy) {	/* add :port */
	if (i>j) i=j;
	tmp=alloca(i+7);
	byte_copy(tmp,i,s);
	tmp[i]=':'; ++i;
	i+=fmt_ulong(tmp+i,h->myport);
	tmp[i]=0;
	s=tmp;
      }
    }
  }
#ifdef __MINGW32__
//  printf("chdir(\"%s\") -> %d\n",origdir,chdir(origdir));
  chdir(origdir);
#else
  fchdir(origdir);
#endif

  if (virtual_hosts>=0)
    if (chdir(dir=s)==-1)
      if (chdir(dir="default")==-1) {
	if (virtual_hosts==1) {
	  buffer_putsflush(buffer_2,"chdir FAILED and virtual_hosts is 1\n");
	  return -1;
	} else
	  dir=".";
      }
  if (!dir) dir=".";
  while (Filename[1]=='/') ++Filename;

#ifdef SUPPORT_HTACCESS
  if (http_dohtaccess(h,".htaccess_global",nobody)==0) return -5;
#endif

#ifdef SUPPORT_PROXY
  noproxy=0;
  {
    int res;
    switch ((res=proxy_connection(sockfd,Filename,dir,h,0,args))) {
    case -3: noproxy=1; /* fall through */
    case -2: break;
    case -1: return -1;
    default:
      if (res>=0) {
	h->buddy=res;
	return -3;
      }
    }
  }
#else
  (void)sockfd;		/* shut up gcc warning about unused variable */
#endif
  if (Filename[(i=str_len(Filename))-1] == '/') {
    /* Damn.  Directory. */
    if (Filename[1] && chdir(Filename+1)==-1) return -1;
#ifdef SUPPORT_HTACCESS
    if (http_dohtaccess(h,".htaccess",nobody)==0) return -5;
#endif
    h->mimetype="text/html";
    if (!open_for_reading(&fd,"index.html",ss)) {
      DIR* d;
      if (errno==ENOENT)
	if (http_redirect(h,"index.html")) return -4;
      if (!directory_index) return -1;
      if (!(d=opendir("."))) return -1;
      if (!http_dirlisting(h,d,Filename,args)) return -1;
#ifdef USE_ZLIB
      if (doesgzip) {
	uLongf destlen=h->blen+30+h->blen/1000;
	unsigned char *compressed=malloc(destlen+15);
	if (!compressed) return -2;
	if (compress2(compressed+8,&destlen,(unsigned char*)h->bodybuf,h->blen,3)==Z_OK && destlen<h->blen) {
	  /* I am absolutely _not_ sure why this works, but we
	   * apparently have to ignore the first two and the last four
	   * bytes of the output of compress2.  I got this from googling
	   * for "compress2 header" and finding some obscure gzip
	   * integration in aolserver */
	  unsigned int crc=crc32(0,0,0);
	  crc=crc32(crc,(unsigned char*)h->bodybuf,h->blen);
	  free(h->bodybuf);
	  h->bodybuf=(char*)compressed;
	  h->encoding=GZIP;
	  byte_zero(compressed,10);
	  compressed[0]=0x1f; compressed[1]=0x8b;
	  compressed[2]=8; /* deflate */
	  compressed[3]=1; /* indicate ASCII */
	  compressed[9]=3; /* OS = Unix */
	  uint32_pack((char*)compressed+10-2-4+destlen,crc);
	  uint32_pack((char*)compressed+14-2-4+destlen,h->blen);
	  h->blen=destlen+18-2-4;
	} else {
	  free(compressed);
	}
      }
#endif
      return -2;
    }
#ifdef SUPPORT_PROXY
    /* if index.html is executable, see if we have a file_executable
     * CGI rule */
    if (!noproxy && (ss->st_mode&S_IXOTH)) {
      char* temp=alloca(strlen(Filename)+10);
      if (pread(fd,temp,4,0)==4) {
	if (byte_equal(temp,2,"#!") || byte_equal(temp,4,"\177ELF")) {
	  int res;
	  i=fmt_str(temp,Filename);
	  i+=fmt_str(temp+i,"index.html");
	  temp[i]=0;
	  switch ((res=proxy_connection(sockfd,temp,dir,h,1,args))) {
	  case -2: break;
	  case -1: return -1;
	  default:
	    if (res>=0) {
	      close(fd);
	      h->buddy=res;
	      return -3;
	    }
	  }
	}
      }
    }
#endif
#ifdef SUPPORT_BZIP2
    if (doesbzip2) {
      int64 gfd;
      if (open_for_reading(&gfd,"index.html.bz2",ss)) {
	io_close(fd);
	fd=gfd;
	h->encoding=BZIP2;
      }
    }
#endif
    if (doesgzip) {
      int64 gfd;
      if (open_for_reading(&gfd,"index.html.gz",ss)) {
	io_close(fd);
	fd=gfd;
	h->encoding=GZIP;
      }
    }
  } else {
#ifdef SUPPORT_HTACCESS
    char* fn=Filename+1;
    char* x=alloca(strlen(fn)+30);
    int lso=str_rchr(fn,'/');
    if (fn[lso]=='/') {
      byte_copy(x,lso+1,fn);
      str_copy(x+lso+1,".htaccess");
      if (http_dohtaccess(h,x,nobody)==0) return -5;
    } else
      if (http_dohtaccess(h,".htaccess",nobody)==0) return -5;
#endif

    /* For /test/t.cgi/fnord open_for_reading fails with ENOTDIR. */
    if (!open_for_reading(&fd,Filename+1,ss)) {
      if (errno==ENOENT)
	if (http_redirect(h,Filename+1)) return -4;
      if (errno==ENOTDIR) {
	/* we have no choice: we need to test /test, then /test/t.cgi,
	 * to find the actual file name.  Fortunately, the CGI code
	 * already does that in forkslave(). */
	/* We could take it on faith here and let the CGI code handle the
	 * error, but that is very inefficient (one fork per 404). */
	char* fn=alloca(strlen(Filename));
	size_t i;
	strcpy(fn,Filename+1);
	for (i=0; fn[i]; ++i) {
	  if (fn[i]=='/') {
	    char c=fn[i];
	    fn[i]=0;
	    if (stat(fn,ss))
	      break;	/* genuine 404, can't happen (should have been ENOENT and not ENOTDIR) */
	    if (!S_ISDIR(ss->st_mode)) {	/* found first non-dir entry, hopefully our CGI */
	      if (!(ss->st_mode&S_IROTH) || !io_readfile(&fd,fn))
		return -1;
	      h->mimetype=mimetype(fn,fd);
	      fn[i]=c;
	      goto foundcgi;
	    }
	    fn[i]=c;
	  }
	}
      }
      return -1;
    }
    h->mimetype=mimetype(Filename,fd);
foundcgi:
#ifdef SUPPORT_PROXY
    if (!noproxy && (ss->st_mode&S_IXOTH)) {
      char temp[5];
      if (
#ifdef SUPPORT_MIMEMAGIC
	  /* no need to call pread twice */
          h->mimetype==magicelfvalue ||
#endif
         ((pread(fd,temp,4,0)==4) && (byte_equal(temp,2,"#!") || byte_equal(temp,4,"\177ELF")))) {
	int res;
	switch ((res=proxy_connection(sockfd,Filename,dir,h,1,args))) {
	case -2: break;
	case -1: return -1;
	default:
	  if (res>=0) {
	    close(fd);
	    h->buddy=res;
	    return -3;
	  }
	}
      }
    }
#endif
    if (h->mimetype==magicelfvalue) h->mimetype="application/octet-stream";
#ifdef DEBUG
    if (logging) {
      buffer_puts(buffer_1,"open_file ");
      buffer_putulong(buffer_1,sockfd);
      buffer_putspace(buffer_1);
      buffer_putulong(buffer_1,fd);
      buffer_putspace(buffer_1);
      buffer_puts(buffer_1,Filename);
      buffer_putnlflush(buffer_1);
    }
#endif
    if (doesgzip
#ifdef SUPPORT_BZIP2
                 || doesbzip2
#endif
                             ) {
      int64 gfd;
      i=str_len(Filename);
#ifdef SUPPORT_BZIP2
      if (doesbzip2) {
	Filename[i+fmt_str(Filename+i,".bz2")]=0;
	if (open_for_reading(&gfd,Filename+1,ss)) {
	  io_close(fd);
	  fd=gfd;
	  h->encoding=BZIP2;
	}
      }
#endif
      if (doesgzip && h->encoding==NORMAL) {
	Filename[i+fmt_str(Filename+i,".gz")]=0;
	if (open_for_reading(&gfd,Filename+1,ss)) {
	  io_close(fd);
	  fd=gfd;
	  h->encoding=GZIP;
	}
      }
      Filename[i]=0;
    }
  }
#ifndef __MINGW32__
  if (S_ISDIR(ss->st_mode)) {
    io_close(fd);
    return -1;
  }
#endif
  return fd;
}

#ifdef SUPPORT_FALLBACK_REDIR
const char* redir;

void do_redirect(struct http_data* h,const char* filename,int64 s) {
  char* nh=malloc((strlen(filename)+strlen(redir))*2+300);
  int i;
  if (!nh) {
    if (logging) {
      char numbuf[FMT_ULONG];
      numbuf[fmt_ulong(numbuf,s)]=0;
      buffer_putmflush(buffer_1,"outofmemory ",numbuf,"\n");
    }
    cleanup(s);
    return;
  }
  i=fmt_str(nh,"HTTP/1.0 302 Over There\r\nServer: " RELEASE "\r\nLocation: ");
  i+=fmt_str(nh+i,redir);
  i+=fmt_str(nh+i,filename);
  i+=fmt_str(nh+i,"\r\nContent-Type: text/html\r\nContent-Length: ");
  i+=fmt_ulong(nh+i,strlen(filename)+strlen(redir)+23);
  i+=fmt_str(nh+i,"\r\n\r\n");
  i+=fmt_str(nh+i,"Look <a href=");
  i+=fmt_str(nh+i,redir);
  i+=fmt_str(nh+i,filename);
  i+=fmt_str(nh+i,">here!</a>\n");
  iob_addbuf_free(&h->iob,nh,strlen(nh));
}
#endif

#ifdef SUPPORT_SERVERSTATUS
void do_server_status(struct http_data* h,int64 s) {
  char* nh=malloc(1000);
  int i,l;
  char buf[FMT_ULONG*10+600];
  if (!nh) {
    if (logging) {
      char numbuf[FMT_ULONG];
      numbuf[fmt_ulong(numbuf,s)]=0;
      buffer_putmflush(buffer_1,"outofmemory ",numbuf,"\n");
    }
    cleanup(s);
    return;
  }
  i=fmt_str(buf,"<title>Gatling Server Status</title>\n<h2>Open Connections</h2>\nHTTP: ");
  i+=fmt_ulong(buf+i,http_connections);
  i+=fmt_str(buf+i,"<br>\nHTTPS: ");
  i+=fmt_ulong(buf+i,https_connections);
  i+=fmt_str(buf+i,"<br>\nFTP: ");
  i+=fmt_ulong(buf+i,ftp_connections);
  i+=fmt_str(buf+i,"<br>\nSMB: ");
  i+=fmt_ulong(buf+i,smb_connections);
  i+=fmt_str(buf+i,"<p>\n<h2>Per second:</h2>Connections: ");
  i+=fmt_ulong(buf+i,cps);
  i+=fmt_str(buf+i,"<br>\nRequests: ");
  i+=fmt_ulong(buf+i,rps);
  i+=fmt_str(buf+i,"<br>\nEvents: ");
  i+=fmt_ulong(buf+i,eps);
  i+=fmt_str(buf+i,"<br>\nInbound Traffic: ");
  i+=fmt_ulong(buf+i,tin/1024);
  i+=fmt_str(buf+i," KiB<br>\nOutbound Traffic: ");
  i+=fmt_ulong(buf+i,tout/1024);
  i+=fmt_str(buf+i," KiB");
  buf[i]=0;
  l=i;

  i=fmt_str(nh,"HTTP/1.0 200 OK\r\nServer: " RELEASE "\r\nContent-Type: text/html\r\nConnection: close\r\nContent-Length: ");
  i+=fmt_ulong(nh+i,l);
  i+=fmt_str(nh+i,"\r\n\r\n");
  i+=fmt_str(nh+i,buf);
  iob_addbuf_free(&h->iob,nh,strlen(nh));
  h->keepalive=0;
  io_wantwrite(s);

  if (logging) {
    char buf[IP6_FMT+10];
    int x;
    char* tmp;
    x=fmt_ip6c(buf,h->myip);
    x+=fmt_str(buf+x,"/");
    x+=fmt_ulong(buf+x,h->myport);
    buf[x]=0;
#ifdef SUPPORT_HTTPS
    if (h->t == HTTPSREQUEST)
      buffer_puts(buffer_1,"HTTPS/");
#endif
    buffer_puts(buffer_1,"GET ");
    buffer_putulong(buffer_1,s);
    buffer_puts(buffer_1," ");
    buffer_putlogstr(buffer_1,"server-status");
    buffer_puts(buffer_1," ");
    buffer_putulonglong(buffer_1,l);
    buffer_puts(buffer_1," ");
    buffer_putlogstr(buffer_1,(tmp=http_header(h,"User-Agent"))?tmp:"[no_user_agent]");
    buffer_puts(buffer_1," ");
    buffer_putlogstr(buffer_1,(tmp=http_header(h,"Referer"))?tmp:"[no_referrer]");
    buffer_puts(buffer_1," ");
    buffer_putlogstr(buffer_1,(tmp=http_header(h,"Host"))?tmp:buf);
    buffer_putsflush(buffer_1,"\n");
  }
}
#endif

#ifdef SUPPORT_SERVERSTATUS
static int is_private_ip(const unsigned char* ip) {
  if (ip6_isv4mapped(ip))
    return byte_equal(ip+12,4,ip4loopback) ||	/* localhost */
	   (ip[12]==10) ||			/* rfc1918 */
	   (ip[12]==192 && ip[13]==168) ||
	   (ip[12]==172 && (ip[13]>=16 && ip[13]<=31));
  return byte_equal(ip,16,V6loopback) || (ip[0]==0xfe && (ip[1]==0x80 || ip[1]==0xc0));
  /* localhost or link-local or site-local */
}
#endif

static void get_md5_randomness(const uint8_t* randomness,size_t len,char digest[16]) {
  MD5_CTX temp;
  static int initialized;
  if (!initialized) {
    int fd=open("/dev/urandom",O_RDONLY);
    unsigned char buf[16];
    read(fd,buf,16);
    close(fd);
    MD5Init(&md5_ctx);
    MD5Update(&md5_ctx,buf,16);
    initialized=1;
  }
  MD5Update(&md5_ctx,randomness,len);
  memcpy(&temp,&md5_ctx,sizeof(temp));
  MD5Final((uint8_t*)digest,&temp);
}

size_t scan_range(const char* s,unsigned long long* x,size_t maxranges,unsigned long long filesize) {
  unsigned long long start,end;
  size_t used=0;
  /* possible formats: "-5", "1-3", "10-" */
  while (*s!='\r' && *s!='\n' && *s) {
    if (isdigit(*s))
      s+=scan_ulonglong(s,&start);
    else
      start=0;
    end=filesize;
    if (*s=='-') {
      ++s;
      if (isdigit(*s))
	s+=scan_ulonglong(s,&end);
    }
    if (used+1<maxranges) {
      x[used]=start;
      x[used+1]=end;
    } else
      return 0;
    used+=2;
    if (*s==',') {
      ++s;
      continue;
    }
    if (*s=='\r' || *s=='\n' || *s==0)
      return used;
  }
  return 0;
}

static int mytolower(int a) {
  return a>='A' && a<='Z' ? a-'A'+'a' : a;
}

static int header_diff(const char* s,const char* t) {
  /* like str_diff but s may also end with '\r' or '\n' */
  register int j;
  j=0;
  for (;;) {
    if ((j=(mytolower(*s)-mytolower(*t)))) break; if (!*t) break; ++s; ++t;
  }
  if (*s=='\r' || *s=='\n') j=-*t;
  return j;
}

void httpresponse(struct http_data* h,int64 s,long headerlen) {
  int head,post;
#ifdef SUPPORT_PUT
  int put;
#endif
  char* c;
  const char* m;
  time_t ims=0;
  unsigned long long range_first,range_last;
  h->filefd=-1;

  ++rps1;
  array_cat0(&h->r);
  c=array_start(&h->r);
  if (byte_diff(c,5,"GET /") && byte_diff(c,6,"POST /") &&
#ifdef SUPPORT_PUT
      byte_diff(c,5,"PUT /") &&
#endif
      byte_diff(c,6,"HEAD /")) {
e400:
    httperror(h,"400 Invalid Request","This server does not understand this HTTP verb.",0);

    if (logging) {
      char numbuf[FMT_ULONG];
      numbuf[fmt_ulong(numbuf,s)]=0;
      buffer_putmflush(buffer_1,"error_400 ",numbuf,"\n");
    }

  } else {
    char *d;
    int64 fd;
    struct stat ss;
    char* tmp;
    head=c[0]=='H';
    post=c[1]=='O';
#ifdef SUPPORT_PUT
    put=c[1]=='U';
#endif
    c+=(head||post)?5:4;
    for (d=c; *d!=' '&&*d!='\t'&&*d!='\n'&&*d!='\r'; ++d) ;
    if (*d!=' ') goto e400;
    *d=0;

    if ((m=http_header(h,"Connection"))) {
      if (!header_diff(m,"keep-alive"))
	h->keepalive=1;
      else
	h->keepalive=0;
    } else {
      if (byte_equal(d+1,8,"HTTP/1.0"))
	h->keepalive=0;
      else
	h->keepalive=1;
    }

    if (c[0]!='/') goto e404;
#ifdef SUPPORT_SERVERSTATUS
    if (!strcmp(c,"/server-status") && is_private_ip((const unsigned char*)h->myip)) {
      do_server_status(h,s);
      return;
    }
#endif
    fd=http_openfile(h,c,&ss,s,head);
    if (fd==-1) {
e404:
#ifdef SUPPORT_FALLBACK_REDIR
      if (redir)
	do_redirect(h,c,s);
#endif
      if (logging) {
	char buf[IP6_FMT+10];
	int x;
	x=fmt_ip6c(buf,h->myip);
	x+=fmt_str(buf+x,"/");
	x+=fmt_ulong(buf+x,h->myport);
	buf[x]=0;
#ifdef SUPPORT_HTTPS
	if (h->t == HTTPSREQUEST)
	  buffer_puts(buffer_1,"HTTPS/");
#endif
#ifdef SUPPORT_PUT
	if (put) buffer_puts(buffer_1,"PUT/404 "); else
#endif
	buffer_puts(buffer_1,head?"HEAD/404 ":post?"POST/404 ":"GET/404 ");
	buffer_putulong(buffer_1,s);
	buffer_puts(buffer_1," ");
	buffer_putlogstr(buffer_1,c);
	buffer_puts(buffer_1," 0 ");
	buffer_putlogstr(buffer_1,(tmp=http_header(h,"User-Agent"))?tmp:"[no_user_agent]");
	buffer_puts(buffer_1," ");
	buffer_putlogstr(buffer_1,(tmp=http_header(h,"Referer"))?tmp:"[no_referrer]");
	buffer_puts(buffer_1," ");
	buffer_putlogstr(buffer_1,(tmp=http_header(h,"Host"))?tmp:buf);
	buffer_putsflush(buffer_1,"\n");
      }
#ifdef SUPPORT_FALLBACK_REDIR
      if (redir)
	goto fini;
#endif
      httperror(h,"404 Not Found","No such file or directory.",head);

    } else {
      char* filename=c;
      if (fd==-4) {	/* redirect */
	iob_addbuf_free(&h->iob,h->hdrbuf,h->hlen);
	iob_addbuf_free(&h->iob,h->bodybuf,h->blen);
      } else if (fd==-5) {
	/* 401 -> log nothing. */
      } else if (fd==-2) {
	char* c;
	c=h->hdrbuf=(char*)malloc(250);
	if (!c)
	  httperror(h,"500 Sorry","Out of Memory.",head);
	else {

	  if (logging) {
	    char buf[IP6_FMT+10];
	    int x;
	    x=fmt_ip6c(buf,h->myip);
	    x+=fmt_str(buf+x,"/");
	    x+=fmt_ulong(buf+x,h->myport);
	    buf[x]=0;
#ifdef SUPPORT_HTTPS
	    if (h->t == HTTPSREQUEST)
	      buffer_puts(buffer_1,"HTTPS/");
#endif
	    buffer_puts(buffer_1,head?"HEAD ":"GET ");
	    buffer_putulong(buffer_1,s);
	    buffer_puts(buffer_1," ");
	    buffer_putlogstr(buffer_1,filename);
	    buffer_puts(buffer_1," ");
	    buffer_putulonglong(buffer_1,h->blen);
	    buffer_puts(buffer_1," ");
	    buffer_putlogstr(buffer_1,(tmp=http_header(h,"User-Agent"))?tmp:"[no_user_agent]");
	    buffer_puts(buffer_1," ");
	    buffer_putlogstr(buffer_1,(tmp=http_header(h,"Referer"))?tmp:"[no_referrer]");
	    buffer_puts(buffer_1," ");
	    buffer_putlogstr(buffer_1,(tmp=http_header(h,"Host"))?tmp:buf);
	    buffer_putsflush(buffer_1,"\n");
	  }

	  c+=fmt_str(c,"HTTP/1.1 200 Here you go\r\nContent-Type: text/html\r\nConnection: ");
	  c+=fmt_str(c,h->keepalive?"keep-alive":"close");
	  c+=fmt_str(c,"\r\nServer: " RELEASE "\r\nContent-Length: ");
	  c+=fmt_ulong(c,h->blen);
	  if (h->encoding!=NORMAL) {
	    c+=fmt_str(c,"\r\nContent-Encoding: ");
#ifdef SUPPORT_BZIP2
	    c+=fmt_str(c,h->encoding==GZIP?"gzip":"bzip2");
#else
	    c+=fmt_str(c,"gzip");
#endif
	  }
	  c+=fmt_str(c,"\r\n\r\n");
	  h->hlen=c-h->hdrbuf;
	  iob_addbuf_free(&h->iob,h->hdrbuf,h->hlen);
	  if (head)
	    free(h->bodybuf);
	  else
	    iob_addbuf_free(&h->iob,h->bodybuf,h->blen);
	}
#ifdef SUPPORT_PROXY
      } else if (fd==-3) {
	return;
#endif
      } else {
	char* multirange=0;
	unsigned long long ranges[20];
	unsigned long long bytes=0;
	size_t n=0,headersize=0;
	char hex[16];
#ifdef DEBUG
	if (logging) {
	  buffer_puts(buffer_1,"filefd ");
	  buffer_putulong(buffer_1,s);
	  buffer_putspace(buffer_1);
	  buffer_putulong(buffer_1,fd);
	  buffer_putnlflush(buffer_1);
	}
#endif
	h->filefd=fd;
	range_first=0; range_last=ss.st_size;
	if ((c=http_header(h,"If-Modified-Since")))
	  if ((unsigned char)(c[scan_httpdate(c,&ims)])>' ')
	    ims=0;
	if ((c=http_header(h,"Range"))) {
	  if (byte_equal(c,6,"bytes=")) {
	    size_t i;
	    c+=6;
	    n=scan_range(c,ranges,sizeof(ranges)/sizeof(ranges[0])/2,ss.st_size);

	    /* the ranges could still be bogus, i.e. 4-2, or the sum
	      * could be more than just sending the whole file. */
	    for (i=0; i<n; i+=2) {
	      if (ranges[i]>=ranges[i+1] ||	// zero or less size
	          bytes+(ranges[i+1]-ranges[i]+1) < bytes) {	/* int overflow */
		n=0;
		break;
	      }
	      bytes+=(ranges[i+1]-ranges[i]+1);
	      if (bytes>ss.st_size+1) {
		n=0;
		break;
	      }
	    }

	    if (n) {
	      /* n will be a multiple of two here */
	      if (n==2) {
		/* just one range, common case */
		range_first=ranges[0];
		range_last=ranges[1];
	      } else {
		size_t overhead=(sizeof("\r\n--eba5aaeb1a3913f0ed90259cf85a1ea7\r\nContent-Type: \r\nContent-Range: bytes -/\r\n\r\n")-1+
		  strlen(h->mimetype)+fmt_ulonglong(NULL,ss.st_size))*(n/2)+
		  sizeof("\r\n--eba5aaeb1a3913f0ed90259cf85a1ea7--\r\n")-1;
		for (i=0; i<n; i+=2)
		  overhead+=fmt_ulonglong(NULL,ranges[i])+fmt_ulonglong(NULL,ranges[i+1]);
		if (bytes+overhead<bytes)
		  goto rangekaputt;
		headersize=overhead;
//		printf("bytes=%llu, overhead=%zu, header size=%zu\n",bytes,overhead,headersize);
		bytes+=overhead;
		if (bytes<ss.st_size)
		  multirange=c;
	      }
	    } else {
rangekaputt:
#ifdef DEBUG
	      if (logging) {
		buffer_puts(buffer_1,"bad_range_close ");
		buffer_putulong(buffer_1,s);
		buffer_putspace(buffer_1);
		buffer_putulong(buffer_1,fd);
		buffer_putnlflush(buffer_1);
	      }
#endif
	      io_close(h->filefd); h->filefd=-1;
	      httperror(h,"416 Bad Range","The requested range can not be satisfied.",head);
	      goto fini;
	    }
	  }
	}
	if (range_last<range_first) {
	  /* rfc2616, page 123 */
	  range_first=0; range_last=ss.st_size;
	}
	if (range_last>ss.st_size) range_last=ss.st_size;

	c=h->hdrbuf=(char*)malloc(500);
	if (ss.st_mtime<=ims) {
	  c+=fmt_str(c,"HTTP/1.1 304 Not Changed");
	  head=1; range_last=range_first;
	  io_close(fd); fd=-1;
	  multirange=0;
	} else {
	  if (multirange || range_first || range_last!=ss.st_size)
	    c+=fmt_str(c,"HTTP/1.1 206 Partial Content");
	  else
	    c+=fmt_str(c,"HTTP/1.1 200 Coming Up");
	}

	c+=fmt_str(c,"\r\nAccept-Ranges: bytes\r\nServer: " RELEASE "\r\nContent-Type: ");
	if (multirange) {
	  c+=fmt_str(c,"multipart/byteranges; boundary=");
	  get_md5_randomness((uint8_t*)multirange,str_chr(multirange,'\n'),hex);
	  c+=fmt_hexdump(c,hex,16);
	  c+=fmt_str(c,"\r\nContent-Length: ");
	  c+=fmt_ulonglong(c,bytes);
	} else {
	  c+=fmt_str(c,h->mimetype);
	  c+=fmt_str(c,"\r\nContent-Length: ");
	  c+=fmt_ulonglong(c,range_last-range_first);
	}

	c+=fmt_str(c,"\r\nDate: ");
	c+=fmt_httpdate(c,now.sec.x&0xfffffffffffull);

	c+=fmt_str(c,"\r\nLast-Modified: ");
	c+=fmt_httpdate(c,ss.st_mtime);
	if (h->encoding!=NORMAL) {
	  c+=fmt_str(c,"\r\nContent-Encoding: ");
#ifdef SUPPORT_BZIP2
	  c+=fmt_str(c,h->encoding==GZIP?"gzip":"bzip2");
#else
	  c+=fmt_str(c,"gzip");
#endif
	}
	if ((range_first || range_last!=ss.st_size)) {
	  c+=fmt_str(c,"\r\nContent-Range: bytes ");
	  c+=fmt_ulonglong(c,range_first);
	  c+=fmt_str(c,"-");
	  c+=fmt_ulonglong(c,range_last-1);
	  c+=fmt_str(c,"/");
	  c+=fmt_ulonglong(c,ss.st_size);
	}
	if (range_first>ss.st_size) {
	  free(c);
	  httperror(h,"416 Bad Range","The requested range can not be satisfied.",head);
	  buffer_puts(buffer_1,"error_416 ");
	} else {
	  c+=fmt_str(c,"\r\nConnection: ");
	  c+=fmt_str(c,h->keepalive?"keep-alive":"close");
	  c+=fmt_str(c,"\r\n\r\n");
	  iob_addbuf_free(&h->iob,h->hdrbuf,c - h->hdrbuf);
	  if (!head) {
	    if (multirange) {
	      char* buf=malloc(headersize+5);
	      char* c,* x;
	      size_t i,flen;

	      c=buf+fmt_str(buf,"\r\n--");
	      c+=fmt_hexdump(c,hex,16);
	      c+=fmt_str(c,"--\r\n");
	      flen=c-buf;

	      x=c;

	      for (i=0; i<n; i+=2) {
		c=x+fmt_str(x,"\r\n--");
		c+=fmt_hexdump(c,hex,16);
		c+=fmt_str(c,"\r\nContent-Type: ");
		c+=fmt_str(c,h->mimetype);
		c+=fmt_str(c,"\r\nContent-Range: bytes ");
		c+=fmt_ulonglong(c,ranges[i]);
		c+=fmt_str(c,"-");
		c+=fmt_ulonglong(c,ranges[i+1]);
		c+=fmt_str(c,"/");
		c+=fmt_ulonglong(c,ss.st_size);
		c+=fmt_str(c,"\r\n\r\n");
		iob_addbuf(&h->iob,x,c-x);
		if (i+2<n)
		  iob_addfile(&h->iob,fd,ranges[i],ranges[i+1]-ranges[i]+1);
		else
		  iob_addfile_close(&h->iob,fd,ranges[i],ranges[i+1]-ranges[i]+1);
		x=c;
	      }
	      iob_addbuf_free(&h->iob,buf,flen);
	    } else
	      iob_addfile_close(&h->iob,fd,range_first,range_last-range_first);
	  } else
	    if (fd!=-1) io_close(fd);
	  if (logging) {
	    if (h->hdrbuf[9]=='3') {
	      buffer_puts(buffer_1,head?"HEAD/304 ":"GET/304 ");
	    } else {
	      buffer_puts(buffer_1,head?"HEAD ":"GET ");
	    }
	  }
	}

	if (logging) {
	  char buf[IP6_FMT+10];
	  int x;
	  x=fmt_ip6c(buf,h->myip);
	  x+=fmt_str(buf+x,"/");
	  x+=fmt_ulong(buf+x,h->myport);
	  buf[x]=0;
	  buffer_putulong(buffer_1,s);
	  buffer_puts(buffer_1," ");
	  buffer_putlogstr(buffer_1,filename);
	  switch (h->encoding) {
	  case GZIP: buffer_puts(buffer_1,".gz"); break;
#ifdef SUPPORT_BZIP2
	  case BZIP2: buffer_puts(buffer_1,".bz2");
#endif
	  case NORMAL: break;
	  }
	  buffer_puts(buffer_1," ");
	  buffer_putulonglong(buffer_1,range_last-range_first);
	  buffer_puts(buffer_1," ");
	  buffer_putlogstr(buffer_1,(tmp=http_header(h,"User-Agent"))?tmp:"[no_user_agent]");
	  buffer_puts(buffer_1," ");
	  buffer_putlogstr(buffer_1,(tmp=http_header(h,"Referer"))?tmp:"[no_referrer]");
	  buffer_puts(buffer_1," ");
	  buffer_putlogstr(buffer_1,(tmp=http_header(h,"Host"))?tmp:buf);
	  buffer_putsflush(buffer_1,"\n");
	}
      }
    }
  }
fini:
  io_dontwantread(s);
  io_wantwrite(s);
}


#ifdef SUPPORT_PROXY
void handle_read_proxypost(int64 i,struct http_data* H) {
  switch (proxy_is_readable(i,H)) {
  case -1:
    {
      if (logging) {
	char numbuf[FMT_ULONG];
	numbuf[fmt_ulong(numbuf,i)]=0;

	buffer_putmflush(buffer_1,"proxy_read_error ",numbuf," ",strerror(errno),"\nclose/acceptfail ",numbuf,"\n");
      }
      cleanup(i);
    }
    break;
  }
}

void handle_read_httppost(int64 i,struct http_data* H) {
  /* read POST data. */
//	printf("read POST data state for %d\n",i);
  if (H->still_to_copy) {
    if (array_bytes(&H->r)>0) {
//	    printf("  but there was still data in H->r!\n");
      io_dontwantread(i);
      io_wantwrite(H->buddy);
    } else if (read_http_post(i,H)==-1) {
      if (logging) {
	char a[FMT_ULONG];
	a[fmt_ulong(a,i)]=0;
	buffer_putmflush(buffer_1,"http_postdata_read_error ",a," ",strerror(errno),"\nclose/acceptfail ",a,"\n");
      }
      cleanup(i);
    } else {
//	    printf("  read something\n");
      io_dontwantread(i);
      io_wantwrite(H->buddy);
    }
  } else {
    /* should not happen */
    io_dontwantread(i);
//	  printf("ARGH!!!\n");
  }
}

void handle_write_proxypost(int64 i,struct http_data* h) {
  struct http_data* H=io_getcookie(h->buddy);
  /* do we have some POST data to write? */
//	printf("event: write POST data (%llu) to proxy on %d\n",h->still_to_copy,i);
  if (!array_bytes(&H->r)) {
//	  printf("  but nothing here to write!\n");
    io_dontwantwrite(i);	/* nope */
    io_wantread(h->buddy);
  } else {
//	  printf("  yeah!\n");
    if (H) {
      char* c=array_start(&H->r);
      long alen=array_bytes(&H->r);
      long l;
//	    printf("%ld bytes still in H->r (%ld in h->r), still to copy: %lld (%lld in h)\n",alen,(long)array_bytes(&h->r),H->still_to_copy,h->still_to_copy);
      if (alen>h->still_to_copy) alen=h->still_to_copy;
      if (alen==0) goto nothingmoretocopy;
      l=write(i,c,alen);
//	    printf("wrote %ld bytes (wanted to write %ld; had %lld still to copy)\n",l,alen,H->still_to_copy);
      if (l<1) {
	/* ARGH!  Proxy crashed! *groan* */
	if (logging) {
	  buffer_puts(buffer_1,"http_postdata_write_error ");
	  buffer_putulong(buffer_1,i);
	  buffer_putspace(buffer_1);
	  buffer_puterror(buffer_1);
	  buffer_puts(buffer_1,"\nclose/acceptfail ");
	  buffer_putulong(buffer_1,i);
	  buffer_putnlflush(buffer_1);
	}
	cleanup(i);
      } else {
	byte_copy(c,alen-l,c+l);
	array_truncate(&H->r,1,alen-l);
//	      printf("still_to_copy PROXYPOST write handler: %p %llu -> %llu\n",H,H->still_to_copy,H->still_to_copy-l);
	h->still_to_copy-=l;
//	      printf("still_to_copy PROXYPOST write handler: %p %llu -> %llu\n",h,h->still_to_copy,h->still_to_copy-i);
//	      h->still_to_copy-=i;
	if (alen-l==0) {
	  /* we wrote everything we have in the buffer */
	  io_dontwantwrite(i);
	  /* check if we need to copy more data */
	  if (h->still_to_copy)
	    io_wantread(h->buddy);
	}
	if (h->still_to_copy==0) {
	  /* we got all we asked for */
nothingmoretocopy:
	  io_dontwantwrite(i);
	  io_wantread(i);
	  io_dontwantread(h->buddy);
	  io_wantwrite(h->buddy);
	}
      }
    }
  }
}

void handle_write_httppost(int64 i,struct http_data* h) {
  int64 r;
#ifdef SUPPORT_HTTPS
  if (h->t==HTTPSPOST)
    r=iob_write(i,&h->iob,https_write_callback);
  else 
#endif
  r=iob_send(i,&h->iob);
  if (r==-1)
    io_eagain(i);
  else if (r<=0) {
    if (r==-3) {
      if (logging) {
	char a[FMT_ULONG];
	char r[FMT_ULONG];
	char s[FMT_ULONG];
	a[fmt_ulong(a,i)]=0;
	r[fmt_ulonglong(r,h->received)]=0;
	s[fmt_ulonglong(s,h->sent)]=0;
	buffer_putmflush(buffer_1,"socket_error ",a," ",strerror(errno),"\nclose/writefail ",a," ",r," ",s,"\n");
      }
      cleanup(i);
      return;
    }
    if (h->buddy==-1) {
      if (logging) {
	char a[FMT_ULONG];
	char r[FMT_ULONG];
	char s[FMT_ULONG];
	a[fmt_ulong(a,i)]=0;
	r[fmt_ulonglong(r,h->received)]=0;
	s[fmt_ulonglong(s,h->sent)]=0;
	buffer_putmflush(buffer_1,"close/proxydone ",a," ",r," ",s,"\n");
      }
      cleanup(i);
    } else {
      io_dontwantwrite(i);
      io_wantread(h->buddy);
    }
  } else
    h->sent+=r;
}

void handle_write_proxyslave(int64 i,struct http_data* h) {
  /* the connect() to the proxy just finished or failed */
  struct http_data* H;
  H=io_getcookie(h->buddy);
  if (proxy_write_header(i,h)==-1) {
kaputt:
    if (logging) {
      buffer_puts(buffer_1,"proxy_connect_error ");
      buffer_putulong(buffer_1,i);
      buffer_putspace(buffer_1);
      buffer_puterror(buffer_1);
      buffer_puts(buffer_1,"\nclose/connectfail ");
      buffer_putulong(buffer_1,i);
      buffer_putnlflush(buffer_1);
    }
    H->buddy=-1;
    httperror(H,"502 Gateway Broken","Request relaying error.",0); /* FIXME, what about HEAD? */
    h->buddy=-1;
    free(h);
    io_close(i);
  }
  /* it worked.  We wrote the header.  Now see if there is
    * POST data to write.  h->still_to_copy is Content-Length. */
//	printf("wrote header to %d for %d; Content-Length: %d\n",(int)i,(int)h->buddy,(int)h->still_to_copy);
  changestate(h,PROXYPOST);
  array_trunc(&h->r);
  if (h->still_to_copy) {
    size_t l=h->still_to_copy;
    if (l>array_bytes(&H->r)) l=array_bytes(&H->r);
    if (l) {
      /* for FASTCGI, we need to add a header */
      if (H->proxyproto==FASTCGI) {
	char* tmp,* cur;
	cur=array_start(&H->r);
	while (l) {	/* this basically can't happen */
	  size_t chunk=l;
	  if (chunk>32768) chunk=32768;
	  tmp=malloc(8);
	  if (!tmp) goto kaputt;
	  memcpy(tmp,"\x01\x05\x00\x01\x00\x00\x00\x00",8);
	  tmp[4]=chunk>>8;
	  tmp[5]=chunk&0xff;
	  iob_addbuf_free(&H->iob,tmp,8);
	  iob_addbuf(&H->iob,cur,chunk);
	  cur+=chunk;
	  l-=chunk;
	}
      } else
	iob_addbuf(&H->iob,array_start(&H->r),l);
    }
    handle_write_httppost(i,H);
  } else {
    io_dontwantwrite(i);
    io_wantread(i);
  }
}

#endif

#ifdef SUPPORT_CGI
/* gatling is expected to have 10000 file descriptors open.
 * so forking off CGIs is bound to be expensive because after the fork
 * all the file descriptors have to be closed.  So this code makes
 * gatling fork off a child first thing in main().  gatling has a Unix
 * domain socket open to the child.  When gatling needs to start a CGI,
 * it sends a message to the child.  The child then creates a new socket
 * pair, sets up the CGI environment, forks a grandchild, and passes the
 * socket to the grandchild back to gatling over the Unix domain socket. */
char fsbuf[8192];

static const char *cgivars[] = {
  "GATEWAY_INTERFACE=",
  "SERVER_PROTOCOL=",
  "SERVER_SOFTWARE=",
  "SERVER_NAME=",
  "SERVER_PORT=",
  "REQUEST_METHOD=",
  "REQUEST_URI=",
  "SCRIPT_NAME=",
  "REMOTE_ADDR=",
  "REMOTE_PORT=",
  "REMOTE_IDENT=",
  "AUTH_TYPE=",
  "CONTENT_TYPE=",
  "CONTENT_LENGTH=",
  "QUERY_STRING=",
  "PATH_INFO=",
  "PATH_TRANSLATED=",
  "REMOTE_USER=",
  0
};

int cgienvneeded(const char* httpreq,size_t reqlen) {
  int i,j,envc;
  for (i=envc=0; _envp[i]; ++i) {
    int found=0;
    if (str_start(_envp[i],"HTTP_"))
      found=1;
    else
      for (j=0; cgivars[j]; ++j)
	if (str_start(_envp[i],cgivars[j])) { found=1; break; }
    if (!found) ++envc;
  }

  /* now collect all normal HTTP headers */

  {
    const char* x=httpreq;
    const char* max=x+reqlen;
    for (;x<max && *x!='\n';++x) ;	/* Skip GET */
    for (;x<max;++x)
      if (*x=='\n')
	++envc;
  }
  return envc;
}

extern int switch_uid();

void forkslave(int fd,buffer* in,int savedir) {
  /* receive query, create socketpair, fork, set up environment,
   * pass file descriptor of our side of socketpair */

  /* protocol:
   * in:
   *   uint32 reqlen,dirlen,ralen
   *   char httprequest[reqlen]
   *   char dir[dirlen]		// "www.fefe.de:80"
   *   char remoteaddr[ralen]
   *   uint16 remoteport
   *   uint16 myport
   * out:
   *   uint32 code,alen
   *   char answer[alen]

   * reqlen==0 means sshd mode.  In this case a connection on port 443
   * came in, ssh forwarding is activated, and the timeout expired
   * before the client sent anything.  Fork an sshd, and pass the
   * descriptor.
   */

  uint32 i,reqlen,dirlen,code,ralen;
  uint16 port,myport;
  const char* msg="protocol error";

  code=1;
  if (read(fd,(char*)&reqlen,4)!=4) goto error;

//  printf("CGI: reqlen %u\n",reqlen);

#ifdef SUPPORT_HTTPS
  if (reqlen==0) { /* SSH MODE */
    int s,r;
    if ((s=io_receivefd(fd))==-1) goto error;
#ifdef sgi
    r=fork();
#else
    r=vfork();
#endif
    if (r==-1) { close(s); msg="vfork failed"; goto error; }
    if (r==0) { /* child */
      /* sshd might be something like /opt/diet/bin/sshd -u0 */
      /* so tokenize and add -i (inetd mode) */
      size_t args,i;
      char** argv;
      close(savedir);
      for (i=0,args=3; sshd[i]; ++i)
	if (sshd[i]==' ') ++args;
      argv=malloc(args*sizeof(argv[0]));
      argv[0]=sshd; args=1;
      for (i=0; sshd[i]; ++i) {
	if (sshd[i]==' ') {
	  do {
	    sshd[i]=0;
	    ++i;
	  } while (sshd[i]==' ');
	  argv[args]=sshd+i;
	  ++args;
	}
      }
      argv[args]="-i";
      argv[args+1]=0;
      dup2(s,0);
      dup2(s,1);
      close(s);
      close(fd);
      execvp(argv[0],argv);
      exit(127);
    }
    close(s);
    return;
  }
#endif

  if (buffer_get(in,(char*)&dirlen,4)==4 &&
      buffer_get(in,(char*)&ralen,4)==4) {
//    printf("CGI: dirlen %u, ralen %u\n",dirlen,ralen);
    if (dirlen<PATH_MAX && reqlen<MAX_HEADER_SIZE) {
      char* httpreq=alloca(reqlen+1);
      char* path=alloca(dirlen+1);
      char* remoteaddr=alloca(ralen+1);
      char* servername,* httpversion,* authtype,* contenttype,* contentlength,* remoteuser;
      char* path_translated;

      if (buffer_get(in,httpreq,reqlen) == reqlen &&
	  buffer_get(in,path,dirlen) == dirlen &&
	  buffer_get(in,remoteaddr,ralen) == ralen &&
	  buffer_get(in,(char*)&port,2) == 2 &&
	  buffer_get(in,(char*)&myport,2) == 2) {

	httpreq[reqlen]=0;
	path[dirlen]=0;
	remoteaddr[ralen]=0;

	if (dirlen==0 || chdir(path)==0) {
	  /* now find cgi */
	  char* cginame,* origcginame;

	  origcginame=cginame=httpreq+5+(httpreq[0]=='P');
	  while (*cginame=='/') ++cginame;
	  for (i=0; cginame+i<httpreq+reqlen; ++i)
	    if (cginame[i]==' ' || cginame[i]=='\r' || cginame[i]=='\n') break;

	  if (cginame[i]==' ') {
	    char* args,* pathinfo;
	    int j,k;
	    struct stat ss;
	    cginame[i]=0; args=0; pathinfo=0;

	    httpversion=alloca(30+(j=str_chr(cginame+i+1,'\n')));
	    k=fmt_str(httpversion,"SERVER_PROTOCOL=");
	    byte_copy(httpversion+k,j,cginame+i+1);
	    if (j && httpversion[k+j-1]=='\r') --j; httpversion[k+j]=0;

	    /* now cginame is something like "test/t.cgi?foo=bar"
	     * but it might also be "test/t.cgi/something/else" or even
	     * "test/t.cgi/something/?uid=23" */

	    /* extract ?foo=bar */
	    j=str_chr(cginame,'?');
	    if (cginame[j]=='?') {
	      args=cginame+j+1;
	      cginame[j]=0;
	      i=j;
	    }

	    /* now cginame is test/t.cgi/something */
	    if (stat(cginame,&ss)==0)
	      /* no "/something" */
	      pathinfo=0;
	    else {
	      errno=0;
	      /* try paths */
	      for (j=0; j<i; ++j) {
		if (cginame[j]=='/') {
		  cginame[j]=0;
		  if (stat(cginame,&ss)==0 && !S_ISDIR(ss.st_mode)) {
		    pathinfo=cginame+j+1;
		    break;
		  }
		  cginame[j]='/';
		  if (errno==ENOENT || errno==ENOTDIR) {
		    msg="404";
		    goto error;
		  }
		}
	      }
	    }

	    {
	      char* x=http_header_blob(httpreq,reqlen,"Host");
	      if (x) {
		j=str_chr(x,'\n'); if (j && x[j-1]=='\r') { --j; }
	      } else {
		x=remoteaddr; j=str_len(x);
	      }
	      servername=alloca(30+j+1);
	      i=fmt_str(servername,"SERVER_NAME=");
	      byte_copy(servername+i,j,x);
	      servername[i+j]=0;

	      if (pathinfo) {
		size_t pilen;
		scan_urlencoded2(pathinfo,pathinfo,&pilen); pathinfo[pilen]=0;
		path_translated=alloca(PATH_MAX+30);
		i=fmt_str(path_translated,"PATH_TRANSLATED=");
		if (!realpath(pathinfo,path_translated+i))
		  path_translated=0;
	      } else
		path_translated=0;

	      x=http_header_blob(httpreq,reqlen,"Authorization");
	      if (x) {
		int k;
		remoteuser=0;

		j=str_chr(x,'\n'); if (j && x[j-1]=='\r') { --j; }
		k=str_chr(x,' ');
		if (k<j) {
		  size_t dl;
		  remoteuser=alloca(20+k-j);
		  i=fmt_str(remoteuser,"REMOTE_USER=");
		  scan_base64(x+k+1,remoteuser+i,&dl);
		  remoteuser[i+dl]=0;
		  dl=str_chr(remoteuser+i,':');
		  if (remoteuser[i+dl]==':') remoteuser[i+dl]=0;
		  j=k;
		}
		authtype=alloca(20+j+1);
		i=fmt_str(authtype,"AUTH_TYPE=");
		byte_copy(authtype+i,j,x);
		authtype[i+j]=0;
	      } else
		authtype=remoteuser=0;

	      x=http_header_blob(httpreq,reqlen,"Content-Type");
	      if (x) {
		j=str_chr(x,'\n'); if (j && x[j-1]=='\r') { --j; }
		contenttype=alloca(30+j+1);
		i=fmt_str(contenttype,"CONTENT_TYPE=");
		byte_copy(contenttype+i,j,x);
		contenttype[i+j]=0;
	      } else
		contenttype=0;

	      x=http_header_blob(httpreq,reqlen,"Content-Length");
	      if (x) {
		j=str_chr(x,'\n'); if (j && x[j-1]=='\r') { --j; }
		contentlength=alloca(30+j+1);
		i=fmt_str(contentlength,"CONTENT_LENGTH=");
		byte_copy(contentlength+i,j,x);
		contentlength[i+j]=0;
	      } else
		contentlength=0;
	    }

	    {
	      int sock[2];
	      if (socketpair(AF_UNIX,SOCK_STREAM,0,sock)==0) {
#ifdef sgi
		int r=fork();
#else
		int r=vfork();
#endif
		if (r==-1)
		  msg="vfork failed!";
		else if (r==0) {
		  /* child */
		  pid_t pid;
		  close(savedir);
		  code=0;
		  write(fd,&code,4);
		  write(fd,&code,4);
		  pid=getpid();
		  write(fd,&pid,sizeof(pid));
		  if (cginame[(j=strlen(cginame))-1]=='/') {	/* can happen in the -C+x case */
		    char* temp=alloca(j+10);
		    j=fmt_str(temp,cginame);
		    j+=fmt_str(temp+j,"index.html");
		    temp[j]=0;
		    cginame=temp;
		  }
		  if (io_passfd(fd,sock[0])==0) {
		    char* argv[]={cginame,0};
		    char** envp;
		    int envc;

		    envc=cgienvneeded(httpreq,reqlen);

		    envp=(char**)alloca(sizeof(char*)*(envc+20));
		    envc=0;

		    for (i=0; _envp[i]; ++i) {
		      int found=0;
		      if (str_start(_envp[i],"HTTP_"))
			found=1;
		      else
			for (j=0; cgivars[j]; ++j)
			  if (str_start(_envp[i],cgivars[j])) { found=1; break; }
		      if (!found) envp[envc++]=_envp[i];
		    }
		    envp[envc++]="SERVER_SOFTWARE=" RELEASE;
		    envp[envc++]=servername;
		    envp[envc++]="GATEWAY_INTERFACE=CGI/1.1";
		    envp[envc++]=httpversion;

		    envp[envc]=alloca(30);
		    i=fmt_str(envp[envc],"SERVER_PORT=");
		    i+=fmt_ulong(envp[envc]+i,myport);
		    envp[envc][i]=0;
		    ++envc;

		    envp[envc++]=httpreq[0]=='G'?"REQUEST_METHOD=GET":"REQUEST_METHOD=POST";
		    if (pathinfo) envp[envc++]=fmt_strm_alloca("PATH_INFO=",pathinfo);
		    if (path_translated) envp[envc++]=path_translated;

		    envp[envc]=alloca(30+str_len(origcginame));
		    i=fmt_str(envp[envc],"SCRIPT_NAME=");
		    i+=fmt_str(envp[envc]+i,origcginame-1);
		    envp[envc][i]=0;
		    ++envc;

		    if (args) {
		      envp[envc]=alloca(30+str_len(args));
		      i=fmt_str(envp[envc],"QUERY_STRING=");
		      i+=fmt_str(envp[envc]+i,args);
		      envp[envc][i]=0;
		      ++envc;
		    }

		    envp[envc]=alloca(30+str_len(remoteaddr));
		    i=fmt_str(envp[envc],"REMOTE_ADDR=");
		    i+=fmt_str(envp[envc]+i,remoteaddr);
		    envp[envc][i]=0;
		    ++envc;

		    envp[envc]=alloca(30);
		    i=fmt_str(envp[envc],"REMOTE_PORT=");
		    i+=fmt_ulong(envp[envc]+i,port);
		    envp[envc][i]=0;
		    ++envc;

		    if (authtype) envp[envc++]=authtype;
		    if (remoteuser) envp[envc++]=remoteuser;
		    if (contenttype) envp[envc++]=contenttype;
		    if (contentlength) envp[envc++]=contentlength;

		    {
		      char* x=httpreq;
		      char* max=x+reqlen;
		      char* y;

		      for (;x<max && *x!='\n';++x) ;	/* Skip GET */

		      for (y=++x;x<max;++x)
			if (*x=='\n') {

			  if (x>y && x[-1]=='\r') --x;

			  if (x>y) {
			    char* s=alloca(x-y+7);
			    int i,j;

			    byte_copy(s,5,"HTTP_");
			    j=5;
			    for (i=0; i<x-y; ++i) {
			      if (y[i]==':') {
				++i;
				while (i<x-y && (y[i]==' ' || y[i]=='\t')) ++i;
				s[j]='='; ++j;
				for (; i<x-y; ++i) {
				  s[j]=y[i];
				  ++j;
				}
				s[j]=0;
				envp[envc]=s;
				++envc;
				break;
			      }
			      if (y[i]=='-')
				s[j]='_';
			      else if (y[i]>='a' && y[i]<='z')
				s[j]=y[i]-'a'+'A';
			      else if (y[i]>='A' && y[i]<='Z')
				s[j]=y[i];
			      else {
				s=0; break;
			      }
			      ++j;
			    }
			  }
			  if (*x=='\r') ++x;
			  y=x+1;
			}
		    }

		    envp[envc]=0;

		    dup2(sock[1],0);
		    dup2(sock[1],1);
		    dup2(sock[1],2);
		    close(sock[0]); close(sock[1]); close(fd);

		    {
		      char* path,* file;
		      path=cginame;
		      file=strrchr(path,'/');
		      if (file) {
			*file=0;
			++file;
			chdir(path);
			cginame=file;
		      }
		      if (switch_uid()==0)
			execve(cginame,argv,envp);
		    }
		  }
		  {
		    static char e[]="HTTP/1.0 503 Gateway Broken\r\nServer: " RELEASE "\r\nContent-Length: 15\r\nContent-Type: text/html\r\n\r\nGateway Broken.";
		    write(1,e,sizeof(e)-1);
		  }
		  exit(127);
		} else {
		  /* father */
		  close(sock[0]);
		  close(sock[1]);
		  return;
		}
	      } else
		msg="socketpair failed!";
	    }

	  }
	}
      }
    }
  }
error:
  if (write(fd,&code,4)!=4) exit(0);
  code=strlen(msg);
  write(fd,&code,4);
  {
    pid_t pid=0;
    write(fd,&pid,sizeof(pid));
  }
  write(fd,msg,code);
}
#endif