summaryrefslogtreecommitdiff
path: root/src/c/urweb.c
blob: 0c6eefd5019de4b38b21a8708a4825d8f962de56 (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
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
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
#define _XOPEN_SOURCE 500

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <setjmp.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include <pthread.h>

#include "types.h"

uw_unit uw_unit_v = {};


// Socket extras

int uw_really_send(int sock, const void *buf, size_t len) {
  while (len > 0) {
    size_t n = send(sock, buf, len, 0);

    if (n < 0)
      return n;

    buf += n;
    len -= n;
  }

  return 0;
}


// Buffers

typedef struct {
  char *start, *front, *back;
} buf;

static void buf_init(buf *b, size_t s) {
  b->front = b->start = malloc(s);
  b->back = b->front + s;
}

static void buf_free(buf *b) {
  free(b->start);
}

static void buf_reset(buf *b) {
  b->front = b->start;
}

static void buf_check(buf *b, size_t extra) {
  if (b->back - b->front < extra) {
    size_t desired = b->front - b->start + extra, next;
    char *new_heap;

    next = b->back - b->start;
    if (next == 0)
      next = 1;
    for (; next < desired; next *= 2);

    new_heap = realloc(b->start, next);
    b->front = new_heap + (b->front - b->start);
    b->back = new_heap + next;
    b->start = new_heap;
  }
}

static size_t buf_used(buf *b) {
  return b->front - b->start;
}

static size_t buf_avail(buf *b) {
  return b->back - b->start;
}

static void buf_append(buf *b, const char *s, size_t len) {
  buf_check(b, len+1);
  memcpy(b->front, s, len);
  b->front += len;
  *b->front = 0;
}


// Persistent state types

typedef enum { UNUSED, USED } usage;

typedef struct client {
  unsigned id;
  usage mode;
  int pass;
  struct client *next;
  pthread_mutex_t lock, pull_lock;
  buf msgs;
  int sock;
  time_t last_contact;
  unsigned n_channels;
  unsigned refcount;
} client;


// Persistent client state

static client **clients, *clients_free, *clients_used;
static unsigned n_clients;

static pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;

static client *new_client() {
  client *c;

  pthread_mutex_lock(&clients_mutex);

  if (clients_free) {
    c = clients_free;
    clients_free = clients_free->next;
  }
  else {
    ++n_clients;
    clients = realloc(clients, sizeof(client) * n_clients);
    c = malloc(sizeof(client));
    c->id = n_clients-1;
    pthread_mutex_init(&c->lock, NULL);
    pthread_mutex_init(&c->pull_lock, NULL);
    buf_init(&c->msgs, 0);
    clients[n_clients-1] = c;
  }

  pthread_mutex_lock(&c->lock);
  c->mode = USED;
  c->pass = rand();
  c->sock = -1;
  c->last_contact = time(NULL);
  buf_reset(&c->msgs);
  c->n_channels = 0;
  c->refcount = 0;
  pthread_mutex_unlock(&c->lock);

  c->next = clients_used;
  clients_used = c;

  pthread_mutex_unlock(&clients_mutex);

  return c;
}

static void use_client(client *c) {
  pthread_mutex_lock(&c->lock);
  ++c->refcount;
  pthread_mutex_unlock(&c->lock);
  pthread_mutex_lock(&c->pull_lock);
}

static void release_client(client *c) {
  pthread_mutex_unlock(&c->pull_lock);
  pthread_mutex_lock(&c->lock);
  --c->refcount;
  pthread_mutex_unlock(&c->lock);

}

static const char begin_msgs[] = "HTTP/1.1 200 OK\r\nContent-type: text/plain\r\n\r\n";

static client *find_client(unsigned id) {
  client *c;

  pthread_mutex_lock(&clients_mutex);

  if (id >= n_clients) {
    pthread_mutex_unlock(&clients_mutex);
    return NULL;
  }

  c = clients[id];

  pthread_mutex_unlock(&clients_mutex);
  return c;
}

void uw_client_connect(unsigned id, int pass, int sock) {
  client *c = find_client(id);

  if (c == NULL) {
    close(sock);
    fprintf(stderr, "Out-of-bounds client request (%u)\n", id);
    return;
  }

  pthread_mutex_lock(&c->lock);

  if (c->mode != USED) {
    pthread_mutex_unlock(&c->lock);
    close(sock);
    fprintf(stderr, "Client request for unused slot (%u)\n", id);
    return;
  }

  if (pass != c->pass) {
    pthread_mutex_unlock(&c->lock);
    close(sock);
    fprintf(stderr, "Wrong client password (%u, %d)\n", id, pass);
    return;
  }

  if (c->sock != -1) {
    close(c->sock);
    c->sock = -1;
  }

  c->last_contact = time(NULL);

  if (buf_used(&c->msgs) > 0) {
    uw_really_send(sock, begin_msgs, sizeof(begin_msgs) - 1);
    uw_really_send(sock, c->msgs.start, buf_used(&c->msgs));
    buf_reset(&c->msgs);
    close(sock);
  }
  else
    c->sock = sock;

  pthread_mutex_unlock(&c->lock);
}

static void free_client(client *c) {
  printf("Freeing client %u\n", c->id);

  c->mode = UNUSED;
  c->pass = -1;

  c->next = clients_free;
  clients_free = c;
}

static uw_Basis_channel new_channel(client *c) {
  uw_Basis_channel ch = {c->id, c->n_channels++};
  return ch;
}

static void client_send(client *c, buf *msg) {
  pthread_mutex_lock(&c->lock);

  if (c->sock != -1) {
    uw_really_send(c->sock, begin_msgs, sizeof(begin_msgs) - 1);
    uw_really_send(c->sock, msg->start, buf_used(msg));
    close(c->sock);
    c->sock = -1;
  } else
    buf_append(&c->msgs, msg->start, buf_used(msg));

  pthread_mutex_unlock(&c->lock);
}


// Global entry points

void uw_global_init() {
  srand(time(NULL) ^ getpid());

  clients = malloc(0);
}


// Single-request state

#define ERROR_BUF_LEN 1024

typedef struct regions {
  struct regions *next;
} regions;

typedef struct {
  void (*func)(void*);
  void *arg;
} cleanup;

typedef struct {
  unsigned client;
  buf msgs;
} delta;

typedef enum {
  UNSET, NORMAL, FIL, SUBFORM, SUBFORMS, ENTRY
} input_kind;

typedef struct input {
  input_kind kind;
  union {
    char *normal;
    uw_Basis_file file;
    struct {
      struct input *fields, *parent;
    } subform;
    struct {
      struct input *entries, *parent;
    } subforms;
    struct {
      struct input *fields, *next, *parent;
    } entry;
  } data;
} input;

typedef struct {
  void *data;
  uw_callback commit, rollback, free;
} transactional;

struct uw_context {
  char *headers, *headers_end;

  buf outHeaders, page, heap, script;
  input *inputs, *subinputs, *cur_container;
  size_t n_subinputs, used_subinputs;

  int source_count;

  void *db;

  jmp_buf jmp_buf;

  regions *regions;

  cleanup *cleanup, *cleanup_front, *cleanup_back;

  const char *script_header, *url_prefix;

  int needs_push, needs_sig;

  size_t n_deltas, used_deltas;
  delta *deltas;

  int timeout;

  client *client;

  transactional *transactionals;
  size_t n_transactionals, used_transactionals;

  char error_message[ERROR_BUF_LEN];
};

extern int uw_inputs_len, uw_timeout;

uw_context uw_init() {
  uw_context ctx = malloc(sizeof(struct uw_context));

  ctx->headers = ctx->headers_end = NULL;

  buf_init(&ctx->outHeaders, 0);
  buf_init(&ctx->page, 0);
  buf_init(&ctx->heap, 0);
  buf_init(&ctx->script, 1);
  ctx->script.start[0] = 0;

  ctx->inputs = calloc(uw_inputs_len, sizeof(input));
  ctx->cur_container = NULL;
  ctx->subinputs = malloc(0);
  ctx->n_subinputs = ctx->used_subinputs = 0;

  ctx->db = NULL;

  ctx->regions = NULL;

  ctx->cleanup_front = ctx->cleanup_back = ctx->cleanup = malloc(0);

  ctx->script_header = "";
  ctx->url_prefix = "/";
  ctx->needs_push = 0;
  ctx->needs_sig = 0;
  
  ctx->error_message[0] = 0;

  ctx->source_count = 0;

  ctx->n_deltas = ctx->used_deltas = 0;
  ctx->deltas = malloc(0);

  ctx->timeout = uw_timeout;

  ctx->client = NULL;

  ctx->error_message[0] = 0;

  ctx->transactionals = malloc(0);
  ctx->n_transactionals = ctx->used_transactionals = 0;

  return ctx;
}

void uw_set_db(uw_context ctx, void *db) {
  ctx->db = db;
}

void *uw_get_db(uw_context ctx) {
  return ctx->db;
}

void uw_free(uw_context ctx) {
  size_t i;

  buf_free(&ctx->outHeaders);
  buf_free(&ctx->script);
  buf_free(&ctx->page);
  buf_free(&ctx->heap);
  free(ctx->inputs);
  free(ctx->subinputs);
  free(ctx->cleanup);
  free(ctx->transactionals);

  for (i = 0; i < ctx->n_deltas; ++i)
    buf_free(&ctx->deltas[i].msgs);

  free(ctx);
}

void uw_reset_keep_error_message(uw_context ctx) {
  size_t i;

  buf_reset(&ctx->outHeaders);
  buf_reset(&ctx->script);
  ctx->script.start[0] = 0;
  buf_reset(&ctx->page);
  buf_reset(&ctx->heap);
  ctx->regions = NULL;
  ctx->cleanup_front = ctx->cleanup;
  ctx->source_count = 0;
  ctx->used_deltas = 0;
  ctx->client = NULL;
  ctx->cur_container = NULL;
  ctx->used_transactionals = 0;
}

void uw_reset_keep_request(uw_context ctx) {
  uw_reset_keep_error_message(ctx);
  ctx->error_message[0] = 0;
}

void uw_reset(uw_context ctx) {
  uw_reset_keep_request(ctx);
  memset(ctx->inputs, 0, uw_inputs_len * sizeof(input));
  memset(ctx->subinputs, 0, ctx->n_subinputs * sizeof(input));
  ctx->used_subinputs = 0;
}

void uw_db_init(uw_context);
void uw_handle(uw_context, char *);

failure_kind uw_begin_init(uw_context ctx) {
  int r = setjmp(ctx->jmp_buf);

  if (r == 0)
    uw_db_init(ctx);

  return r;
}

void uw_set_headers(uw_context ctx, char *headers) {
  char *s = headers, *s2;
  ctx->headers = headers;

  while (s2 = strchr(s, '\r')) {
    s = s2;

    if (s[1] == 0)
      break;

    *s = 0;
    s += 2;
  }

  ctx->headers_end = s;
}

void uw_headers_moved(uw_context ctx, char *headers) {
  ctx->headers_end = headers + (ctx->headers_end - ctx->headers);
  ctx->headers = headers;
}

int uw_db_begin(uw_context);

static void uw_set_error(uw_context ctx, const char *fmt, ...) {
  va_list ap;
  va_start(ap, fmt);

  vsnprintf(ctx->error_message, ERROR_BUF_LEN, fmt, ap);
}

__attribute__((noreturn)) void uw_error(uw_context ctx, failure_kind fk, const char *fmt, ...) {
  cleanup *cl;

  va_list ap;
  va_start(ap, fmt);

  vsnprintf(ctx->error_message, ERROR_BUF_LEN, fmt, ap);

  for (cl = ctx->cleanup; cl < ctx->cleanup_front; ++cl)
    cl->func(cl->arg);

  ctx->cleanup_front = ctx->cleanup;

  longjmp(ctx->jmp_buf, fk);
}

void uw_push_cleanup(uw_context ctx, void (*func)(void *), void *arg) {
  if (ctx->cleanup_front >= ctx->cleanup_back) {
    int len = ctx->cleanup_back - ctx->cleanup, newLen;
    if (len == 0)
      newLen = 1;
    else
      newLen = len * 2;
    ctx->cleanup = realloc(ctx->cleanup, newLen * sizeof(cleanup));
    ctx->cleanup_front = ctx->cleanup + len;
    ctx->cleanup_back = ctx->cleanup + newLen;
  }

  ctx->cleanup_front->func = func;
  ctx->cleanup_front->arg = arg;
  ++ctx->cleanup_front;
}

uw_Basis_string uw_Basis_requestHeader(uw_context ctx, uw_Basis_string h) {
  int len = strlen(h);
  char *s = ctx->headers, *p;

  while (p = strchr(s, ':')) {
    if (p - s == len && !strncasecmp(s, h, len)) {
      return p + 2;
    } else {
      if ((s = strchr(p, 0)) && s < ctx->headers_end)
        s += 2;
      else
        return NULL;
    }
  }

  return NULL;
}

void uw_login(uw_context ctx) {
  if (ctx->needs_push) {
    char *id_s, *pass_s;

    if ((id_s = uw_Basis_requestHeader(ctx, "UrWeb-Client"))
        && (pass_s = uw_Basis_requestHeader(ctx, "UrWeb-Pass"))) {
      unsigned id = atoi(id_s);
      int pass = atoi(pass_s);
      client *c = find_client(id);

      if (c == NULL)
        uw_error(ctx, FATAL, "Unknown client ID in HTTP headers (%s, %s)", id_s, pass_s);
      else {
        use_client(c);
        ctx->client = c;

        if (c->mode != USED)
          uw_error(ctx, FATAL, "Stale client ID (%u) in subscription request", id);
        if (c->pass != pass)
          uw_error(ctx, FATAL, "Wrong client password (%u, %d) in subscription request", id, pass);
      }
    } else {
      client *c = new_client();
      use_client(c);
      ctx->client = c;
    }  
  }
}

failure_kind uw_begin(uw_context ctx, char *path) {
  int r = setjmp(ctx->jmp_buf);

  if (r == 0) {
    if (uw_db_begin(ctx))
      uw_error(ctx, BOUNDED_RETRY, "Error running SQL BEGIN");

    uw_handle(ctx, path);
  }

  return r;
}

uw_Basis_client uw_Basis_self(uw_context ctx) {
  if (ctx->client == NULL)
    uw_error(ctx, FATAL, "Call to Basis.self() from page that has only server-side code");

  return ctx->client->id;
}

void uw_pop_cleanup(uw_context ctx) {
  if (ctx->cleanup_front == ctx->cleanup)
    uw_error(ctx, FATAL, "Attempt to pop from empty cleanup action stack");

  --ctx->cleanup_front;
  ctx->cleanup_front->func(ctx->cleanup_front->arg);
}

char *uw_error_message(uw_context ctx) {
  return ctx->error_message;
}

extern int uw_input_num(const char*);

static input *INP(uw_context ctx) {
  if (ctx->cur_container == NULL)
    return ctx->inputs;
  else if (ctx->cur_container->kind == SUBFORM)
    return ctx->cur_container->data.subform.fields;
  else if (ctx->cur_container->kind == ENTRY)
    return ctx->cur_container->data.entry.fields;
  else
    uw_error(ctx, FATAL, "INP: Wrong kind (%d, %p)", ctx->cur_container->kind, ctx->cur_container);
}

static void adjust_pointer(input **ptr, input *old_start, input *new_start, size_t len) {
  if (*ptr != NULL && *ptr >= old_start && *ptr < old_start + len)
    *ptr += new_start - old_start;
}

static void adjust_input(input *x, input *old_start, input *new_start, size_t len) {
  switch (x->kind) {
  case SUBFORM:
    adjust_pointer(&x->data.subform.fields, old_start, new_start, len);
    adjust_pointer(&x->data.subform.parent, old_start, new_start, len);
    break;
  case SUBFORMS:
    adjust_pointer(&x->data.subforms.entries, old_start, new_start, len);
    adjust_pointer(&x->data.subforms.parent, old_start, new_start, len);
    break;
  case ENTRY:
    adjust_pointer(&x->data.entry.fields, old_start, new_start, len);
    adjust_pointer(&x->data.entry.next, old_start, new_start, len);
    adjust_pointer(&x->data.entry.parent, old_start, new_start, len);
  }  
}

static input *check_input_space(uw_context ctx, size_t len) {
  size_t i;
  input *r;

  if (ctx->used_subinputs + len >= ctx->n_subinputs) {
    input *new_subinputs = realloc(ctx->subinputs, sizeof(input) * (ctx->used_subinputs + len));
    size_t offset = new_subinputs - ctx->subinputs;

    if (ctx->subinputs != new_subinputs) {
      for (i = 0; i < ctx->used_subinputs; ++i)
        adjust_input(&new_subinputs[i], ctx->subinputs, new_subinputs, ctx->used_subinputs);
      for (i = 0; i < uw_inputs_len; ++i)
        adjust_input(&ctx->inputs[i], ctx->subinputs, new_subinputs, ctx->used_subinputs);

      adjust_pointer(&ctx->cur_container, ctx->subinputs, new_subinputs, ctx->used_subinputs);

      ctx->n_subinputs = ctx->used_subinputs + len;
      ctx->subinputs = new_subinputs;
    }
  }

  r = &ctx->subinputs[ctx->used_subinputs];

  for (i = 0; i < len; ++i)
    ctx->subinputs[ctx->used_subinputs++].kind = UNUSED;

  return r;
}

int uw_set_input(uw_context ctx, const char *name, char *value) {
  if (!strcasecmp(name, ".b")) {
    int n = uw_input_num(value);
    input *inps;

    if (n < 0) {
      uw_set_error(ctx, "Bad subform name %s", value);
      return -1;
    }

    if (n >= uw_inputs_len) {
      uw_set_error(ctx, "For subform name %s, index %d is out of range", value, n);
      return -1;
    }

    inps = check_input_space(ctx, uw_inputs_len);

    INP(ctx)[n].kind = SUBFORM;
    INP(ctx)[n].data.subform.parent = ctx->cur_container;
    INP(ctx)[n].data.subform.fields = inps;
    ctx->cur_container = &INP(ctx)[n];
  } else if (!strcasecmp(name, ".e")) {
    input *tmp;

    if (ctx->cur_container == NULL) {
      uw_set_error(ctx, "Unmatched subform closer");
      return -1;
    }

    tmp = ctx->cur_container;
    switch (tmp->kind) {
    case SUBFORM:
      ctx->cur_container = tmp->data.subform.parent;
      tmp->data.subform.parent = NULL;
      break;
    case SUBFORMS:
      ctx->cur_container = tmp->data.subforms.parent;
      tmp->data.subforms.parent = NULL;
      break;
    case ENTRY:
      ctx->cur_container = tmp->data.entry.parent;
      break;
    default:
      uw_set_error(ctx, "uw_set_input: Wrong kind");
      return -1;
    }
  } else if (!strcasecmp(name, ".s")) {
    int n = uw_input_num(value);

    if (n < 0) {
      uw_set_error(ctx, "Bad subforms name %s", value);
      return -1;
    }

    if (n >= uw_inputs_len) {
      uw_set_error(ctx, "For subforms name %s, index %d is out of range", value, n);
      return -1;
    }

    INP(ctx)[n].kind = SUBFORMS;
    INP(ctx)[n].data.subforms.parent = ctx->cur_container;
    INP(ctx)[n].data.subforms.entries = NULL;
    ctx->cur_container = &INP(ctx)[n];
  } else if (!strcasecmp(name, ".i")) {
    input *inps;

    if (!ctx->cur_container) {
      uw_set_error(ctx, "New entry without container");
      return -1;
    }

    if (ctx->cur_container->kind != SUBFORMS) {
      uw_set_error(ctx, "Bad kind for entry parent");
      return -1;
    }

    inps = check_input_space(ctx, uw_inputs_len + 1);

    inps->kind = ENTRY;
    inps->data.entry.parent = ctx->cur_container;
    inps->data.entry.next = ctx->cur_container->data.subforms.entries;
    ctx->cur_container->data.subforms.entries = inps;

    inps->data.entry.fields = inps+1;
    ctx->cur_container = inps;
  } else {
    int n = uw_input_num(name);

    if (n < 0) {
      uw_set_error(ctx, "Bad input name %s", name);
      return -1;
    }

    if (n >= uw_inputs_len) {
      uw_set_error(ctx, "For input name %s, index %d is out of range", name, n);
      return -1;
    }

    INP(ctx)[n].kind = NORMAL;
    INP(ctx)[n].data.normal = value;
  }

  return 0;
}

char *uw_get_input(uw_context ctx, int n) {
  if (n < 0)
    uw_error(ctx, FATAL, "Negative input index %d", n);
  if (n >= uw_inputs_len)
    uw_error(ctx, FATAL, "Out-of-bounds input index %d", n);

  switch (INP(ctx)[n].kind) {
  case UNSET:
    return NULL;
  case FIL:
    uw_error(ctx, FATAL, "Tried to read a file form input as normal");
  case SUBFORM:
    uw_error(ctx, FATAL, "Tried to read a subform form input as normal");
  case SUBFORMS:
    uw_error(ctx, FATAL, "Tried to read a subforms form input as normal");
  case ENTRY:
    uw_error(ctx, FATAL, "Tried to read an entry form input as normal");
  case NORMAL:
    return INP(ctx)[n].data.normal;
  default:
    uw_error(ctx, FATAL, "Impossible input kind");
  }
}

char *uw_get_optional_input(uw_context ctx, int n) {
  if (n < 0)
    uw_error(ctx, FATAL, "Negative input index %d", n);
  if (n >= uw_inputs_len)
    uw_error(ctx, FATAL, "Out-of-bounds input index %d", n);

  switch (INP(ctx)[n].kind) {
  case UNSET:
    return "";
  case FIL:
    uw_error(ctx, FATAL, "Tried to read a file form input as normal");
  case SUBFORM:
    uw_error(ctx, FATAL, "Tried to read a subform form input as normal");
  case SUBFORMS:
    uw_error(ctx, FATAL, "Tried to read a subforms form input as normal");
  case ENTRY:
    uw_error(ctx, FATAL, "Tried to read an entry form input as normal");
  case NORMAL:
    return INP(ctx)[n].data.normal;
  default:
    uw_error(ctx, FATAL, "Impossible input kind");
  }
}

int uw_set_file_input(uw_context ctx, const char *name, uw_Basis_file f) {
  int n = uw_input_num(name);

  if (n < 0) {
    uw_set_error(ctx, "Bad file input name %s", name);
    return -1;
  }

  if (n >= uw_inputs_len) {
    uw_set_error(ctx, "For file input name %s, index %d is out of range", name, n);
    return -1;
  }

  ctx->inputs[n].kind = FIL;
  ctx->inputs[n].data.file = f;

  return 0;
}

void *uw_malloc(uw_context ctx, size_t len);


static void parents(input *inp) {
  printf("Stack: %p\n", inp);
  while (inp) {
    switch (inp->kind) {
    case NORMAL:
      printf("Normal(%p)\n", inp);
      break;
    case FIL:
      printf("File(%p)\n", inp);
      break;
    case SUBFORM:
      printf("Subform; fields = %p\n", inp->data.subform.fields);
      inp = inp->data.subform.parent;
      break;
    case SUBFORMS:
      printf("Subforms; entries = %p\n", inp->data.subforms.entries);
      inp = inp->data.subforms.parent;
      break;
    case ENTRY:
      printf("Entry; fields = %p; next = %p\n", inp->data.entry.fields, inp->data.entry.next);
      inp = inp->data.entry.parent;
      break;
    default:
      inp = NULL;
    }
  }
}

uw_Basis_file uw_get_file_input(uw_context ctx, int n) {
  if (n < 0)
    uw_error(ctx, FATAL, "Negative file input index %d", n);
  if (n >= uw_inputs_len)
    uw_error(ctx, FATAL, "Out-of-bounds file input index %d", n);

  switch (INP(ctx)[n].kind) {
  case UNSET:
    {
      char *data = uw_malloc(ctx, 0);
      uw_Basis_file f = {NULL, "", {0, data}};
      return f;
    }
  case FIL:
    return INP(ctx)[n].data.file;
  case NORMAL:
    uw_error(ctx, FATAL, "Tried to read a normal form input as files");
  case SUBFORM:
    uw_error(ctx, FATAL, "Tried to read a subform form input as files");
  case SUBFORMS:
    uw_error(ctx, FATAL, "Tried to read a subforms form input as files");
  case ENTRY:
    uw_error(ctx, FATAL, "Tried to read an entry form input as files");
  default:
    uw_error(ctx, FATAL, "Impossible input kind");
  }
}

void uw_enter_subform(uw_context ctx, int n) {
  if (n < 0)
    uw_error(ctx, FATAL, "Negative subform index %d", n);
  if (n >= uw_inputs_len)
    uw_error(ctx, FATAL, "Out-of-bounds subform index %d", n);

  switch (INP(ctx)[n].kind) {
  case UNSET:
    uw_error(ctx, FATAL, "Missing subform");
  case FIL:
    uw_error(ctx, FATAL, "Tried to read a file form input as subform");
  case NORMAL:
    uw_error(ctx, FATAL, "Tried to read a normal form input as subform");
  case SUBFORMS:
    uw_error(ctx, FATAL, "Tried to read a subforms form input as subform");
  case ENTRY:
    uw_error(ctx, FATAL, "Tried to read an entry form input as subform");
  case SUBFORM:
    INP(ctx)[n].data.subform.parent = ctx->cur_container;
    ctx->cur_container = &INP(ctx)[n];
    return;
  default:
    uw_error(ctx, FATAL, "Impossible input kind");
  }
}

void uw_leave_subform(uw_context ctx) {
  input *tmp;

  if (ctx->cur_container == NULL)
    uw_error(ctx, FATAL, "Unmatched uw_leave_subform");

  tmp = ctx->cur_container;
  ctx->cur_container = tmp->data.subform.parent;
  tmp->data.subform.parent = NULL;
}

int uw_enter_subforms(uw_context ctx, int n) {
  input *inps;

  if (n < 0)
    uw_error(ctx, FATAL, "Negative subforms index %d", n);
  if (n >= uw_inputs_len)
    uw_error(ctx, FATAL, "Out-of-bounds subforms index %d", n);

  switch (INP(ctx)[n].kind) {
  case UNSET:
    uw_error(ctx, FATAL, "Missing subforms");
  case FIL:
    uw_error(ctx, FATAL, "Tried to read a file form input as subforms");
  case NORMAL:
    uw_error(ctx, FATAL, "Tried to read a normal form input %p as subforms", &INP(ctx)[n]);
  case SUBFORM:
    uw_error(ctx, FATAL, "Tried to read a subform form input as subforms");
  case ENTRY:
    uw_error(ctx, FATAL, "Tried to read an entry form input as subforms");
  case SUBFORMS:
    inps = INP(ctx)[n].data.subforms.entries;
    if (inps) {
      INP(ctx)[n].data.subforms.parent = ctx->cur_container;
      ctx->cur_container = INP(ctx)[n].data.subforms.entries;
      return 1;
    } else
      return 0;
  default:
    uw_error(ctx, FATAL, "Impossible input kind");
  }
}

int uw_next_entry(uw_context ctx) {
  if (ctx->cur_container == NULL)
    uw_error(ctx, FATAL, "uw_next_entry(NULL)");

  switch (ctx->cur_container->kind) {
  case UNSET:
    uw_error(ctx, FATAL, "Missing entry");
  case FIL:
    uw_error(ctx, FATAL, "Tried to read a file form input as entry");
  case NORMAL:
    uw_error(ctx, FATAL, "Tried to read a normal form input as entry");
  case SUBFORM:
    uw_error(ctx, FATAL, "Tried to read a subform form input as entry");
  case SUBFORMS:
    uw_error(ctx, FATAL, "Tried to read a subforms form input as entry");
  case ENTRY:
    if (ctx->cur_container->data.entry.next) {
      ctx->cur_container = ctx->cur_container->data.entry.next;
      return 1;
    } else {
      ctx->cur_container = ctx->cur_container->data.entry.parent->data.subforms.parent;
      return 0;
    }
  default:
    uw_error(ctx, FATAL, "Impossible input kind");
  }
}

void uw_set_script_header(uw_context ctx, const char *s) {
  ctx->script_header = s;
}

void uw_set_url_prefix(uw_context ctx, const char *s) {
  ctx->url_prefix = s;
}

void uw_set_needs_push(uw_context ctx, int n) {
  ctx->needs_push = n;
}

void uw_set_needs_sig(uw_context ctx, int n) {
  ctx->needs_sig = n;
}


static void buf_check_ctx(uw_context ctx, buf *b, size_t extra, const char *desc) {
  if (b->back - b->front < extra) {
    size_t desired = b->front - b->start + extra, next;
    char *new_heap;

    next = b->back - b->start;
    if (next == 0)
      next = 1;
    for (; next < desired; next *= 2);

    new_heap = realloc(b->start, next);
    b->front = new_heap + (b->front - b->start);
    b->back = new_heap + next;

    if (new_heap != b->start) {
      b->start = new_heap;
      uw_error(ctx, UNLIMITED_RETRY, "Couldn't allocate new %s contiguously", desc);
    }

    b->start = new_heap;
  }
}

void uw_check_heap(uw_context ctx, size_t extra) {
  buf_check_ctx(ctx, &ctx->heap, extra, "heap chunk");
}

char *uw_heap_front(uw_context ctx) {
  return ctx->heap.front;
}

void uw_set_heap_front(uw_context ctx, char *fr) {
  ctx->heap.front = fr;
}

void *uw_malloc(uw_context ctx, size_t len) {
  void *result;

  uw_check_heap(ctx, len);

  result = ctx->heap.front;
  ctx->heap.front += len;
  return result;
}

void uw_begin_region(uw_context ctx) {
  regions *r = (regions *) ctx->heap.front;

  uw_check_heap(ctx, sizeof(regions));

  ctx->heap.front += sizeof(regions);

  r->next = ctx->regions;
  ctx->regions = r;
}

void uw_end_region(uw_context ctx) {
  regions *r = ctx->regions;

  if (r == NULL)
    uw_error(ctx, FATAL, "Region stack underflow");

  ctx->heap.front = (char *) r;
  ctx->regions = r->next;
}

void uw_memstats(uw_context ctx) {
  printf("Headers: %d/%d\n", buf_used(&ctx->outHeaders), buf_avail(&ctx->outHeaders));
  printf("Script: %d/%d\n", buf_used(&ctx->script), buf_avail(&ctx->script));
  printf("Page: %d/%d\n", buf_used(&ctx->page), buf_avail(&ctx->page));
  printf("Heap: %d/%d\n", buf_used(&ctx->heap), buf_avail(&ctx->heap));
}

int uw_send(uw_context ctx, int sock) {
  int n = uw_really_send(sock, ctx->outHeaders.start, ctx->outHeaders.front - ctx->outHeaders.start);

  if (n < 0)
    return n;

  n = uw_really_send(sock, "\r\n", 2);

  if (n < 0)
    return n;

  return uw_really_send(sock, ctx->page.start, ctx->page.front - ctx->page.start);
}

static void uw_check_headers(uw_context ctx, size_t extra) {
  buf_check(&ctx->outHeaders, extra);
}

void uw_write_header(uw_context ctx, uw_Basis_string s) {
  int len = strlen(s);

  uw_check_headers(ctx, len + 1);
  strcpy(ctx->outHeaders.front, s);
  ctx->outHeaders.front += len;
}

static void uw_check_script(uw_context ctx, size_t extra) {
  buf_check(&ctx->script, extra);
}

void uw_write_script(uw_context ctx, uw_Basis_string s) {
  int len = strlen(s);

  uw_check_script(ctx, len + 1);
  strcpy(ctx->script.front, s);
  ctx->script.front += len;
}

const char *uw_Basis_get_script(uw_context ctx, uw_unit u) {
  if (ctx->script_header[0] == 0)
    return "";
  else if (buf_used(&ctx->script) == 0)
    return ctx->script_header;
  else {
    char *r = uw_malloc(ctx, strlen(ctx->script_header) + 42 + buf_used(&ctx->script));
    sprintf(r, "%s<script type=\"text/javascript\">%s</script>",
            ctx->script_header,
            ctx->script.start);
    return r;
  }
}

uw_Basis_string uw_Basis_maybe_onload(uw_context ctx, uw_Basis_string s) {
  if (s[0] == 0)
    return "";
  else {
    char *r = uw_malloc(ctx, 11 + strlen(s));
    sprintf(r, " onload='%s'", s);
    return r;
  }
}

extern uw_Basis_string uw_cookie_sig(uw_context);

const char *uw_Basis_get_settings(uw_context ctx, uw_unit u) {
  if (ctx->client == NULL) {
    if (ctx->needs_sig) {
      char *sig = uw_cookie_sig(ctx);
      char *r = uw_malloc(ctx, strlen(sig) + 8);
      sprintf(r, "sig=\"%s\";", sig);
      return r;
    }
    else
      return "";
  } else {
    char *sig = ctx->needs_sig ? uw_cookie_sig(ctx) : "";
    char *r = uw_malloc(ctx, 59 + 3 * INTS_MAX + strlen(ctx->url_prefix)
                        + (ctx->needs_sig ? strlen(sig) + 7 : 0));
    sprintf(r, "client_id=%u;client_pass=%d;url_prefix=\"%s\";timeout=%d;%s%s%slistener();",
            ctx->client->id,
            ctx->client->pass,
            ctx->url_prefix,
            ctx->timeout,
            ctx->needs_sig ? "sig=\"" : "",
            sig,
            ctx->needs_sig ? "\";" : "");
    return r;
  }
}

uw_Basis_string uw_Basis_jsifyString(uw_context ctx, uw_Basis_string s) {
  char *r, *s2;

  uw_check_heap(ctx, strlen(s) * 4 + 2);

  r = s2 = ctx->heap.front;
  *s2++ = '"';

  for (; *s; s++) {
    char c = *s;

    switch (c) {
    case '"':
      strcpy(s2, "\\\"");
      s2 += 2;
      break;
    case '\\':
      strcpy(s2, "\\\\");
      s2 += 2;
      break;
    default:
      if (isprint(c))
        *s2++ = c;
      else {
        sprintf(s2, "\\%3o", c);
        s2 += 4;
      }
    }
  }

  strcpy(s2, "\"");
  ctx->heap.front = s2 + 1;
  return r;
}

uw_Basis_string uw_Basis_jsifyString_ws(uw_context ctx, uw_Basis_string s) {
  char *r, *s2;

  uw_check_script(ctx, strlen(s) * 4 + 2);

  r = s2 = ctx->script.front;
  *s2++ = '"';

  for (; *s; s++) {
    char c = *s;

    switch (c) {
    case '\'':
      strcpy(s2, "\\\"");
      s2 += 2;
      break;
    case '\\':
      strcpy(s2, "\\\\");
      s2 += 2;
      break;
    default:
      if (isprint(c))
        *s2++ = c;
      else {
        sprintf(s2, "\\%3o", c);
        s2 += 4;
      }
    }
  }

  strcpy(s2, "\"");
  ctx->script.front = s2 + 1;
  return r;
}

char *uw_Basis_jsifyChannel(uw_context ctx, uw_Basis_channel chn) {
  if (ctx->client == NULL || chn.cli != ctx->client->id)
    return "null";
  else {
    int len;
    char *r;

    uw_check_heap(ctx, INTS_MAX + 1);
    r = ctx->heap.front;
    sprintf(r, "%u%n", chn.chn, &len);
    ctx->heap.front += len+1;
    return r;
  }
}

uw_Basis_int uw_Basis_new_client_source(uw_context ctx, uw_Basis_string s) {
  int len;
  size_t s_len = strlen(s);

  uw_check_script(ctx, 12 + INTS_MAX + s_len);
  sprintf(ctx->script.front, "var s%d=sc(%n", ctx->source_count, &len);
  ctx->script.front += len;
  strcpy(ctx->script.front, s);
  ctx->script.front += s_len;
  strcpy(ctx->script.front, ");");
  ctx->script.front += 2;

  return ctx->source_count++;
}

uw_unit uw_Basis_set_client_source(uw_context ctx, uw_Basis_int n, uw_Basis_string s) {
  int len;
  size_t s_len = strlen(s);

  uw_check_script(ctx, 6 + INTS_MAX + s_len);
  sprintf(ctx->script.front, "s%d.v=%n", (int)n, &len);
  ctx->script.front += len;
  strcpy(ctx->script.front, s);
  ctx->script.front += s_len;
  strcpy(ctx->script.front, ";");
  ctx->script.front++;

  return uw_unit_v;
}

static void uw_check(uw_context ctx, size_t extra) {
  buf_check(&ctx->page, extra);
}

static void uw_writec_unsafe(uw_context ctx, char c) {
  *(ctx->page.front)++ = c;
}

void uw_writec(uw_context ctx, char c) {
  uw_check(ctx, 1);
  uw_writec_unsafe(ctx, c);
}

static void uw_write_unsafe(uw_context ctx, const char* s) {
  int len = strlen(s);
  memcpy(ctx->page.front, s, len);
  ctx->page.front += len;
}

void uw_write(uw_context ctx, const char* s) {
  uw_check(ctx, strlen(s) + 1);
  uw_write_unsafe(ctx, s);
  *ctx->page.front = 0;
}

char *uw_Basis_attrifyInt(uw_context ctx, uw_Basis_int n) {
  char *result;
  int len;
  uw_check_heap(ctx, INTS_MAX);
  result = ctx->heap.front;
  sprintf(result, "%lld%n", n, &len);
  ctx->heap.front += len+1;
  return result;
}

char *uw_Basis_attrifyFloat(uw_context ctx, uw_Basis_float n) {
  char *result;
  int len;
  uw_check_heap(ctx, FLOATS_MAX);
  result = ctx->heap.front;
  sprintf(result, "%g%n", n, &len);
  ctx->heap.front += len+1;
  return result;
}

char *uw_Basis_attrifyString(uw_context ctx, uw_Basis_string s) {
  int len = strlen(s);
  char *result, *p;
  uw_check_heap(ctx, len * 6 + 1);

  result = p = ctx->heap.front;

  for (; *s; s++) {
    char c = *s;

    if (c == '"') {
      strcpy(p, "&quot;");
      p += 6;
    } else if (c == '&') {
      strcpy(p, "&amp;");
      p += 5;
    }
    else if (isprint(c))
      *p++ = c;
    else {
      int len2;
      sprintf(p, "&#%d;%n", c, &len2);
      p += len2;
    }
  }

  *p++ = 0;
  ctx->heap.front = p;
  return result;
}

char *uw_Basis_attrifyCss_class(uw_context ctx, uw_Basis_css_class s) {
  return s;
}

static void uw_Basis_attrifyInt_w_unsafe(uw_context ctx, uw_Basis_int n) {
  int len;

  sprintf(ctx->page.front, "%lld%n", n, &len);
  ctx->page.front += len;
}

uw_unit uw_Basis_attrifyInt_w(uw_context ctx, uw_Basis_int n) {
  uw_check(ctx, INTS_MAX);
  uw_Basis_attrifyInt_w_unsafe(ctx, n);

  return uw_unit_v;
}

uw_unit uw_Basis_attrifyFloat_w(uw_context ctx, uw_Basis_float n) {
  int len;

  uw_check(ctx, FLOATS_MAX);
  sprintf(ctx->page.front, "%g%n", n, &len);
  ctx->page.front += len;

  return uw_unit_v;
}

uw_unit uw_Basis_attrifyString_w(uw_context ctx, uw_Basis_string s) {
  uw_check(ctx, strlen(s) * 6);

  for (; *s; s++) {
    char c = *s;

    if (c == '"')
      uw_write_unsafe(ctx, "&quot;");
    else if (c == '&')
      uw_write_unsafe(ctx, "&amp;");
    else if (isprint(c))
      uw_writec_unsafe(ctx, c);
    else {
      uw_write_unsafe(ctx, "&#");
      uw_Basis_attrifyInt_w_unsafe(ctx, c);
      uw_writec_unsafe(ctx, ';');
    }
  }

  return uw_unit_v;
}


char *uw_Basis_urlifyInt(uw_context ctx, uw_Basis_int n) {
  int len;
  char *r;

  uw_check_heap(ctx, INTS_MAX);
  r = ctx->heap.front;
  sprintf(r, "%lld%n", n, &len);
  ctx->heap.front += len+1;
  return r;
}

char *uw_Basis_urlifyChannel(uw_context ctx, uw_Basis_channel chn) {
  if (ctx->client == NULL || chn.cli != ctx->client->id)
    return "";
  else {
    int len;
    char *r;

    uw_check_heap(ctx, INTS_MAX + 1);
    r = ctx->heap.front;
    sprintf(r, "%u%n", chn.chn, &len);
    ctx->heap.front += len+1;
    return r;
  }
}

char *uw_Basis_urlifyFloat(uw_context ctx, uw_Basis_float n) {
  int len;
  char *r;

  uw_check_heap(ctx, FLOATS_MAX);
  r = ctx->heap.front;
  sprintf(r, "%g%n", n, &len);
  ctx->heap.front += len+1;
  return r;
}

char *uw_Basis_urlifyString(uw_context ctx, uw_Basis_string s) {
  char *r, *p;

  uw_check_heap(ctx, strlen(s) * 3 + 1);

  for (r = p = ctx->heap.front; *s; s++) {
    char c = *s;

    if (c == ' ')
      *p++ = '+';
    else if (isalnum(c))
      *p++ = c;
    else {
      sprintf(p, "%%%02X", c);
      p += 3;
    }
  }

  *p++ = 0;
  ctx->heap.front = p;
  return r;
}

char *uw_Basis_urlifyBool(uw_context ctx, uw_Basis_bool b) {
  if (b == uw_Basis_False)
    return "0";
  else
    return "1";
}

static void uw_Basis_urlifyInt_w_unsafe(uw_context ctx, uw_Basis_int n) {
  int len;

  sprintf(ctx->page.front, "%lld%n", n, &len);
  ctx->page.front += len;
}

uw_unit uw_Basis_urlifyInt_w(uw_context ctx, uw_Basis_int n) {
  uw_check(ctx, INTS_MAX);
  uw_Basis_urlifyInt_w_unsafe(ctx, n);

  return uw_unit_v;
}

uw_unit uw_Basis_urlifyChannel_w(uw_context ctx, uw_Basis_channel chn) {
  if (ctx->client != NULL && chn.cli == ctx->client->id) {
    int len;
    
    uw_check(ctx, INTS_MAX + 1);
    sprintf(ctx->page.front, "%u%n", chn.chn, &len);
    ctx->page.front += len;
  }
    
  return uw_unit_v;
}

uw_unit uw_Basis_urlifyFloat_w(uw_context ctx, uw_Basis_float n) {
  int len;

  uw_check(ctx, FLOATS_MAX);
  sprintf(ctx->page.front, "%g%n", n, &len);
  ctx->page.front += len;

  return uw_unit_v;
}

uw_Basis_string uw_Basis_urlifyTime(uw_context ctx, uw_Basis_time t) {
  return uw_Basis_urlifyInt(ctx, t);
}

uw_unit uw_Basis_urlifyString_w(uw_context ctx, uw_Basis_string s) {
  uw_check(ctx, strlen(s) * 3);

  for (; *s; s++) {
    char c = *s;

    if (c == ' ')
      uw_writec_unsafe(ctx, '+');
    else if (isalnum(c))
      uw_writec_unsafe(ctx, c);
    else {
      sprintf(ctx->page.front, "%%%02X", c);
      ctx->page.front += 3;
    }
  }

  return uw_unit_v;
}

uw_unit uw_Basis_urlifyBool_w(uw_context ctx, uw_Basis_bool b) {
  if (b == uw_Basis_False)
    uw_writec(ctx, '0');
  else
    uw_writec(ctx, '1');

  return uw_unit_v;
}


static char *uw_unurlify_advance(char *s) {
  char *new_s = strchr(s, '/');

  if (new_s)
    *new_s++ = 0;
  else
    new_s = strchr(s, 0);

  return new_s;
}

uw_Basis_int uw_Basis_unurlifyInt(uw_context ctx, char **s) {
  char *new_s = uw_unurlify_advance(*s);
  uw_Basis_int r;

  r = atoll(*s);
  *s = new_s;
  return r;
}

uw_Basis_float uw_Basis_unurlifyFloat(uw_context ctx, char **s) {
  char *new_s = uw_unurlify_advance(*s);
  uw_Basis_float r;

  r = atof(*s);
  *s = new_s;
  return r;
}

uw_Basis_time uw_Basis_unurlifyTime(uw_context ctx, char **s) {
  return uw_Basis_unurlifyInt(ctx, s);
}

static uw_Basis_string uw_unurlifyString_to(uw_context ctx, char *r, char *s) {
  char *s1, *s2;
  int n;

  for (s1 = r, s2 = s; *s2; ++s1, ++s2) {
    char c = *s2;

    switch (c) {
    case '+':
      *s1 = ' ';
      break;
    case '%':
      if (s2[1] == 0)
        uw_error(ctx, FATAL, "Missing first character of escaped URL byte");
      if (s2[2] == 0)
        uw_error(ctx, FATAL, "Missing second character of escaped URL byte");
      if (sscanf(s2+1, "%02X", &n) != 1)
        uw_error(ctx, FATAL, "Invalid escaped URL byte starting at: %s", s2);
      *s1 = n;
      s2 += 2;
      break;
    default:
      *s1 = c;
    }
  }
  *s1++ = 0;
  return s1;
}

uw_Basis_bool uw_Basis_unurlifyBool(uw_context ctx, char **s) {
  char *new_s = uw_unurlify_advance(*s);
  uw_Basis_bool r;
  
  if (*s[0] == 0 || !strcmp(*s, "0") || !strcmp(*s, "off"))
    r = uw_Basis_False;
  else
    r = uw_Basis_True;

  *s = new_s;
  return r;
}

uw_Basis_string uw_Basis_unurlifyString(uw_context ctx, char **s) {
  char *new_s = uw_unurlify_advance(*s);
  char *r, *s1, *s2;
  int len, n;

  len = strlen(*s);
  uw_check_heap(ctx, len + 1);

  r = ctx->heap.front;
  ctx->heap.front = uw_unurlifyString_to(ctx, ctx->heap.front, *s);
  *s = new_s;
  return r;
}


char *uw_Basis_htmlifyInt(uw_context ctx, uw_Basis_int n) {
  int len;
  char *r;

  uw_check_heap(ctx, INTS_MAX);
  r = ctx->heap.front;
  sprintf(r, "%lld%n", n, &len);
  ctx->heap.front += len+1;
  return r;
}

uw_unit uw_Basis_htmlifyInt_w(uw_context ctx, uw_Basis_int n) {
  int len;

  uw_check(ctx, INTS_MAX);
  sprintf(ctx->page.front, "%lld%n", n, &len);
  ctx->page.front += len;
  
  return uw_unit_v;
}

char *uw_Basis_htmlifyFloat(uw_context ctx, uw_Basis_float n) {
  int len;
  char *r;

  uw_check_heap(ctx, FLOATS_MAX);
  r = ctx->heap.front;
  sprintf(r, "%g%n", n, &len);
  ctx->heap.front += len+1;
  return r;
}

uw_unit uw_Basis_htmlifyFloat_w(uw_context ctx, uw_Basis_float n) {
  int len;

  uw_check(ctx, FLOATS_MAX);
  sprintf(ctx->page.front, "%g%n", n, &len);
  ctx->page.front += len;

  return uw_unit_v;
}

char *uw_Basis_htmlifyString(uw_context ctx, uw_Basis_string s) {
  char *r, *s2;

  uw_check_heap(ctx, strlen(s) * 5 + 1);

  for (r = s2 = ctx->heap.front; *s; s++) {
    char c = *s;

    switch (c) {
    case '<':
      strcpy(s2, "&lt;");
      s2 += 4;
      break;
    case '&':
      strcpy(s2, "&amp;");
      s2 += 5;
      break;
    default:
      if (isprint(c))
        *s2++ = c;
      else {
        int len2;
        sprintf(s2, "&#%d;%n", c, &len2);
        s2 += len2;
      }
    }
  }

  *s2++ = 0;
  ctx->heap.front = s2;
  return r;
}

uw_unit uw_Basis_htmlifyString_w(uw_context ctx, uw_Basis_string s) {
  uw_check(ctx, strlen(s) * 6);

  for (; *s; s++) {
    char c = *s;

    switch (c) {
    case '<':
      uw_write_unsafe(ctx, "&lt;");
      break;
    case '&':
      uw_write_unsafe(ctx, "&amp;");
      break;
    default:
      if (isprint(c))
        uw_writec_unsafe(ctx, c);
      else {
        uw_write_unsafe(ctx, "&#");
        uw_Basis_attrifyInt_w_unsafe(ctx, c);
        uw_writec_unsafe(ctx, ';');
      }
    }
  }

  return uw_unit_v;
}

uw_Basis_string uw_Basis_htmlifyBool(uw_context ctx, uw_Basis_bool b) {
  if (b == uw_Basis_False)
    return "False";
  else
    return "True";
}

uw_unit uw_Basis_htmlifyBool_w(uw_context ctx, uw_Basis_bool b) {
  if (b == uw_Basis_False) {
    uw_check(ctx, 6);
    strcpy(ctx->page.front, "False");
    ctx->page.front += 5;
  } else {
    uw_check(ctx, 5);
    strcpy(ctx->page.front, "True");
    ctx->page.front += 4;
  }

  return uw_unit_v;
}

#define TIME_FMT "%x %X"
#define TIME_FMT_PG "%Y-%m-%d %T"

uw_Basis_string uw_Basis_htmlifyTime(uw_context ctx, uw_Basis_time t) {
  size_t len;
  char *r;
  struct tm stm;

  if (localtime_r(&t, &stm)) {
    uw_check_heap(ctx, TIMES_MAX);
    r = ctx->heap.front;
    len = strftime(r, TIMES_MAX, TIME_FMT, &stm);
    ctx->heap.front += len+1;
    return r;
  } else
    return "<i>Invalid time</i>";
}

uw_unit uw_Basis_htmlifyTime_w(uw_context ctx, uw_Basis_time t) {
  size_t len;
  char *r;
  struct tm stm;

  if (localtime_r(&t, &stm)) {
    uw_check(ctx, TIMES_MAX);
    r = ctx->page.front;
    len = strftime(r, TIMES_MAX, TIME_FMT, &stm);
    ctx->page.front += len;
  } else {
    uw_check(ctx, 20);
    strcpy(ctx->page.front, "<i>Invalid time</i>");
    ctx->page.front += 19;
  }

  return uw_unit_v;
}

uw_Basis_char uw_Basis_strsub(uw_context ctx, uw_Basis_string s, uw_Basis_int n) {
  if (n >= 0 && n < strlen(s))
    return s[n];
  else
    uw_error(ctx, FATAL, "Out-of-bounds strsub");
}

uw_Basis_string uw_Basis_strsuffix(uw_context ctx, uw_Basis_string s, uw_Basis_int n) {
  if (n >= 0 && n < strlen(s))
    return &s[n];
  else
    uw_error(ctx, FATAL, "Out-of-bounds strsuffix");
}

uw_Basis_int uw_Basis_strlen(uw_context ctx, uw_Basis_string s) {
  return strlen(s);
}

uw_Basis_string uw_Basis_strchr(uw_context ctx, uw_Basis_string s, uw_Basis_char ch) {
  return strchr(s, ch);
}

uw_Basis_int uw_Basis_strcspn(uw_context ctx, uw_Basis_string s, uw_Basis_string chs) {
  return strcspn(s, chs);
}

uw_Basis_int *uw_Basis_strindex(uw_context ctx, uw_Basis_string s, uw_Basis_char ch) {
  uw_Basis_string r = strchr(s, ch);
  if (r == NULL)
    return NULL;
  else {
    uw_Basis_int *nr = uw_malloc(ctx, sizeof(uw_Basis_int));
    *nr = r - s;
    return nr;
  }
}

uw_Basis_string uw_Basis_strcat(uw_context ctx, uw_Basis_string s1, uw_Basis_string s2) {
  int len = uw_Basis_strlen(ctx, s1) + uw_Basis_strlen(ctx, s2) + 1;
  char *s;

  uw_check_heap(ctx, len);

  s = ctx->heap.front;

  strcpy(s, s1);
  strcat(s, s2);
  ctx->heap.front += len;

  return s;
}

uw_Basis_string uw_Basis_substring(uw_context ctx, uw_Basis_string s, uw_Basis_int start, uw_Basis_int len) {
  size_t full_len = uw_Basis_strlen(ctx, s);

  if (start < 0)
    uw_error(ctx, FATAL, "substring: Negative start index");
  if (len < 0)
    uw_error(ctx, FATAL, "substring: Negative length");
  if (start + len > full_len)
    uw_error(ctx, FATAL, "substring: Start index plus length is too large");

  if (start + len == full_len)
    return &s[start];
  else {
    uw_Basis_string r = uw_malloc(ctx, len+1);
    memcpy(r, s, len);
    r[len] = 0;
    return r;
  }
    
}

uw_Basis_string uw_strdup(uw_context ctx, uw_Basis_string s1) {
  int len = uw_Basis_strlen(ctx, s1) + 1;
  char *s;

  uw_check_heap(ctx, len);

  s = ctx->heap.front;

  strcpy(s, s1);
  ctx->heap.front += len;

  return s;
}

uw_Basis_string uw_maybe_strdup(uw_context ctx, uw_Basis_string s1) {
  if (s1)
    return uw_strdup(ctx, s1);
  else
    return NULL;
}

char *uw_memdup(uw_context ctx, const char *p, size_t len) {
  char *r = uw_malloc(ctx, len);
  memcpy(r, p, len);
  return r;
}

char *uw_Basis_sqlifyInt(uw_context ctx, uw_Basis_int n) {
  int len;
  char *r;

  uw_check_heap(ctx, INTS_MAX + 6);
  r = ctx->heap.front;
  sprintf(r, "%lld::int8%n", n, &len);
  ctx->heap.front += len+1;
  return r;
}

char *uw_Basis_sqlifyIntN(uw_context ctx, uw_Basis_int *n) {
  if (n == NULL)
    return "NULL";
  else
    return uw_Basis_sqlifyInt(ctx, *n);
}

char *uw_Basis_sqlifyFloat(uw_context ctx, uw_Basis_float n) {
  int len;
  char *r;

  uw_check_heap(ctx, FLOATS_MAX + 8);
  r = ctx->heap.front;
  sprintf(r, "%g::float8%n", n, &len);
  ctx->heap.front += len+1;
  return r;
}

char *uw_Basis_sqlifyFloatN(uw_context ctx, uw_Basis_float *n) {
  if (n == NULL)
    return "NULL";
  else
    return uw_Basis_sqlifyFloat(ctx, *n);
}


uw_Basis_string uw_Basis_sqlifyString(uw_context ctx, uw_Basis_string s) {
  char *r, *s2;

  uw_check_heap(ctx, strlen(s) * 2 + 10);

  r = s2 = ctx->heap.front;
  *s2++ = 'E';
  *s2++ = '\'';

  for (; *s; s++) {
    char c = *s;

    switch (c) {
    case '\'':
      strcpy(s2, "\\'");
      s2 += 2;
      break;
    case '\\':
      strcpy(s2, "\\\\");
      s2 += 2;
      break;
    default:
      if (isprint(c))
        *s2++ = c;
      else {
        sprintf(s2, "\\%03o", c);
        s2 += 4;
      }
    }
  }

  strcpy(s2, "'::text");
  ctx->heap.front = s2 + 8;
  return r;
}

uw_Basis_string uw_Basis_sqlifyBlob(uw_context ctx, uw_Basis_blob b) {
  char *r, *s2;
  size_t i;

  uw_check_heap(ctx, b.size * 5 + 11);

  r = s2 = ctx->heap.front;
  *s2++ = 'E';
  *s2++ = '\'';

  for (i = 0; i < b.size; ++i) {
    char c = b.data[i];

    switch (c) {
    case '\'':
      strcpy(s2, "\\'");
      s2 += 2;
      break;
    case '\\':
      strcpy(s2, "\\\\\\\\");
      s2 += 4;
      break;
    default:
      if (isprint(c))
        *s2++ = c;
      else {
        sprintf(s2, "\\\\%03o", c);
        s2 += 5;
      }
    }
  }

  strcpy(s2, "'::bytea");
  ctx->heap.front = s2 + 9;
  return r;
}

char *uw_Basis_sqlifyChannel(uw_context ctx, uw_Basis_channel chn) {
  int len;
  char *r;
  unsigned long long combo = ((unsigned long long)chn.cli << 32) | chn.chn;

  uw_check_heap(ctx, INTS_MAX + 7);
  r = ctx->heap.front;
  sprintf(r, "%lld::int8%n", combo, &len);
  ctx->heap.front += len+1;
  return r;
}

char *uw_Basis_attrifyChannel(uw_context ctx, uw_Basis_channel chn) {
  int len;
  char *r;
  unsigned long long combo = ((unsigned long long)chn.cli << 32) | chn.chn;

  uw_check_heap(ctx, INTS_MAX + 1);
  r = ctx->heap.front;
  sprintf(r, "%lld%n", combo, &len);
  ctx->heap.front += len+1;
  return r;
}

char *uw_Basis_sqlifyClient(uw_context ctx, uw_Basis_client cli) {
  int len;
  char *r;

  uw_check_heap(ctx, INTS_MAX + 7);
  r = ctx->heap.front;
  sprintf(r, "%u::int4%n", cli, &len);
  ctx->heap.front += len+1;
  return r;
}

char *uw_Basis_attrifyClient(uw_context ctx, uw_Basis_client cli) {
  int len;
  char *r;

  uw_check_heap(ctx, INTS_MAX + 1);
  r = ctx->heap.front;
  sprintf(r, "%u%n", cli, &len);
  ctx->heap.front += len+1;
  return r;
}

uw_Basis_string uw_Basis_sqlifyStringN(uw_context ctx, uw_Basis_string s) {
  if (s == NULL)
    return "NULL";
  else
    return uw_Basis_sqlifyString(ctx, s);
}

char *uw_Basis_sqlifyBool(uw_context ctx, uw_Basis_bool b) {
  if (b == uw_Basis_False)
    return "FALSE";
  else
    return "TRUE";
}

char *uw_Basis_sqlifyBoolN(uw_context ctx, uw_Basis_bool *b) {
  if (b == NULL)
    return "NULL";
  else
    return uw_Basis_sqlifyBool(ctx, *b);
}

char *uw_Basis_sqlifyTime(uw_context ctx, uw_Basis_time t) {
  size_t len;
  char *r, *s;
  struct tm stm;

  if (localtime_r(&t, &stm)) {
    s = uw_malloc(ctx, TIMES_MAX);
    len = strftime(s, TIMES_MAX, TIME_FMT, &stm);
    r = uw_malloc(ctx, len + 14);
    sprintf(r, "'%s'::timestamp", s);
    return r;
  } else
    return "<Invalid time>";
}

char *uw_Basis_attrifyTime(uw_context ctx, uw_Basis_time t) {
  size_t len;
  char *r;
  struct tm stm;

  if (localtime_r(&t, &stm)) {
    uw_check_heap(ctx, TIMES_MAX);
    r = ctx->heap.front;
    len = strftime(r, TIMES_MAX, TIME_FMT, &stm);
    ctx->heap.front += len+1;
    return r;
  } else
    return "<Invalid time>";
}

char *uw_Basis_sqlifyTimeN(uw_context ctx, uw_Basis_time *t) {
  if (t == NULL)
    return "NULL";
  else
    return uw_Basis_sqlifyTime(ctx, *t);
}

char *uw_Basis_ensqlBool(uw_Basis_bool b) {
  static uw_Basis_int true = 1;
  static uw_Basis_int false = 0;

  if (b == uw_Basis_False)
    return (char *)&false;
  else
    return (char *)&true;
}

uw_Basis_string uw_Basis_intToString(uw_context ctx, uw_Basis_int n) {
  int len;
  char *r;

  uw_check_heap(ctx, INTS_MAX);
  r = ctx->heap.front;
  sprintf(r, "%lld%n", n, &len);
  ctx->heap.front += len+1;
  return r;
}

uw_Basis_string uw_Basis_floatToString(uw_context ctx, uw_Basis_float n) {
  int len;
  char *r;

  uw_check_heap(ctx, FLOATS_MAX);
  r = ctx->heap.front;
  sprintf(r, "%g%n", n, &len);
  ctx->heap.front += len+1;
  return r;
}

uw_Basis_string uw_Basis_charToString(uw_context ctx, uw_Basis_char ch) {
  char *r = uw_malloc(ctx, 2);
  r[0] = ch;
  r[1] = 0;
  return r;
}

uw_Basis_string uw_Basis_boolToString(uw_context ctx, uw_Basis_bool b) {
  if (b == uw_Basis_False)
    return "False";
  else
    return "True";
}

uw_Basis_string uw_Basis_timeToString(uw_context ctx, uw_Basis_time t) {
  size_t len;
  char *r;
  struct tm stm;

  if (localtime_r(&t, &stm)) {
    uw_check_heap(ctx, TIMES_MAX);
    r = ctx->heap.front;
    len = strftime(r, TIMES_MAX, TIME_FMT, &stm);
    ctx->heap.front += len+1;
    return r;
  } else
    return "<Invalid time>";
}

uw_Basis_int *uw_Basis_stringToInt(uw_context ctx, uw_Basis_string s) {
  char *endptr;
  uw_Basis_int n = strtoll(s, &endptr, 10);

  if (*s != '\0' && *endptr == '\0') {
    uw_Basis_int *r = uw_malloc(ctx, sizeof(uw_Basis_int));
    *r = n;
    return r;
  } else
    return NULL;
}

uw_Basis_float *uw_Basis_stringToFloat(uw_context ctx, uw_Basis_string s) {
  char *endptr;
  uw_Basis_float n = strtod(s, &endptr);

  if (*s != '\0' && *endptr == '\0') {
    uw_Basis_float *r = uw_malloc(ctx, sizeof(uw_Basis_float));
    *r = n;
    return r;
  } else
    return NULL;
}

uw_Basis_char *uw_Basis_stringToChar(uw_context ctx, uw_Basis_string s) {
  if (s[0] == 0) {
    uw_Basis_char *r = uw_malloc(ctx, 1);
    r[0] = 0;
    return r;
  } else if (s[1] != 0)
    return NULL;
  else {
    uw_Basis_char *r = uw_malloc(ctx, 1);
    r[0] = s[0];
    return r;
  }
}

uw_Basis_bool *uw_Basis_stringToBool(uw_context ctx, uw_Basis_string s) {
  static uw_Basis_bool true = uw_Basis_True;
  static uw_Basis_bool false = uw_Basis_False;

  if (!strcasecmp (s, "True"))
    return &true;
  else if (!strcasecmp (s, "False"))
    return &false;
  else
    return NULL;
}

uw_Basis_time *uw_Basis_stringToTime(uw_context ctx, uw_Basis_string s) {
  char *dot = strchr(s, '.'), *end = strchr(s, 0);
  struct tm stm;

  if (dot) {
    *dot = 0;
    if (strptime(s, TIME_FMT_PG, &stm) == end) {
      *dot = '.';
      uw_Basis_time *r = uw_malloc(ctx, sizeof(uw_Basis_time));
      *r = mktime(&stm);
      return r;
    }
    else {
      *dot = '.';
      return NULL;
    }
  }
  else {
    if (strptime(s, TIME_FMT_PG, &stm) == end) {
      uw_Basis_time *r = uw_malloc(ctx, sizeof(uw_Basis_time));
      *r = mktime(&stm);
      return r;
    }
    else if (strptime(s, TIME_FMT, &stm) == end) {
      uw_Basis_time *r = uw_malloc(ctx, sizeof(uw_Basis_time));
      *r = mktime(&stm);
      return r;
    }
    else
      return NULL;
  }
}

uw_Basis_int uw_Basis_stringToInt_error(uw_context ctx, uw_Basis_string s) {
  char *endptr;
  uw_Basis_int n = strtoll(s, &endptr, 10);

  if (*s != '\0' && *endptr == '\0')
    return n;
  else
    uw_error(ctx, FATAL, "Can't parse int: %s", s);
}

#include <errno.h>

uw_Basis_channel uw_Basis_stringToChannel_error(uw_context ctx, uw_Basis_string s) {
  unsigned long long n;

  if (sscanf(s, "%llu", &n) < 1)
    uw_error(ctx, FATAL, "Can't parse channel: %s", s);
  else {
    uw_Basis_channel ch = {n >> 32, n & ((1ull << 32) - 1)};
    return ch;
  }
}

uw_Basis_client uw_Basis_stringToClient_error(uw_context ctx, uw_Basis_string s) {
  char *endptr;
  unsigned long n = strtoul(s, &endptr, 10);

  if (*s != '\0' && *endptr == '\0')
    return n;
  else
    uw_error(ctx, FATAL, "Can't parse client: %s", s);
}

uw_Basis_float uw_Basis_stringToFloat_error(uw_context ctx, uw_Basis_string s) {
  char *endptr;
  uw_Basis_float n = strtod(s, &endptr);

  if (*s != '\0' && *endptr == '\0')
    return n;
  else
    uw_error(ctx, FATAL, "Can't parse float: %s", s);
}

uw_Basis_char uw_Basis_stringToChar_error(uw_context ctx, uw_Basis_string s) {
  if (s[0] == 0)
    return 0;
  else if (s[1] != 0)
    uw_error(ctx, FATAL, "Can't parse char: %s", s);
  else
    return s[0];
}

uw_Basis_bool uw_Basis_stringToBool_error(uw_context ctx, uw_Basis_string s) {
  if (!strcasecmp(s, "T") || !strcasecmp (s, "True"))
    return uw_Basis_True;
  else if (!strcasecmp(s, "F") || !strcasecmp (s, "False"))
    return uw_Basis_False;
  else
    uw_error(ctx, FATAL, "Can't parse bool: %s", s);
}

uw_Basis_time uw_Basis_stringToTime_error(uw_context ctx, uw_Basis_string s) {
  char *dot = strchr(s, '.'), *end = strchr(s, 0);
  struct tm stm = {};

  if (dot) {
    *dot = 0;
    if (strptime(s, TIME_FMT_PG, &stm)) {
      *dot = '.';
      return mktime(&stm);
    }
    else {
      *dot = '.';
      uw_error(ctx, FATAL, "Can't parse time: %s", s);
    }
  }
  else {
    if (strptime(s, TIME_FMT_PG, &stm) == end)
      return mktime(&stm);
    else if (strptime(s, TIME_FMT, &stm) == end)
      return mktime(&stm);
    else
      uw_error(ctx, FATAL, "Can't parse time: %s", s);
  }
}

uw_Basis_blob uw_Basis_stringToBlob_error(uw_context ctx, uw_Basis_string s, size_t len) {
  char *r = ctx->heap.front;
  uw_Basis_blob b = {len, r};

  uw_check_heap(ctx, len);

  while (*s) {
    if (s[0] == '\\') {
      if (s[1] == '\\') {
        *r++ = '\\';
        s += 2;
      } else if (isdigit(s[1]) && isdigit(s[2]) && isdigit(s[3])) {
        *r++ = (s[1] - '0') * 8 * 8 + ((s[2] - '0') * 8) + (s[3] - '0');
        s += 4;
      }
      else {
        *r++ = '\\';
        ++s;
      }
    } else {
      *r++ = s[0];
      ++s;
    }
  }

  b.size = r - ctx->heap.front;
  ctx->heap.front = r;
  return b;
}

uw_Basis_string uw_Basis_get_cookie(uw_context ctx, uw_Basis_string c) {
  int len = strlen(c);
  char *s = ctx->headers, *p = ctx->outHeaders.start;

  while (p = strstr(p, "\nSet-Cookie: ")) {
    char *p2;
    p += 13;
    p2 = strchr(p, '=');

    if (p2) {
      size_t sz = strcspn(p2+1, ";\r\n");

      if (!strncasecmp(p, c, p2 - p)) {
        char *ret = uw_malloc(ctx, sz + 1);
        memcpy(ret, p2+1, sz);
        ret[sz] = 0;
        return ret;
      }
    }
  }

  while (p = strchr(s, ':')) {
    if (!strncasecmp(s, "Cookie: ", 8)) {
      p += 2;
      while (1) {
        if (!strncmp(p, c, len)
            && p + len < ctx->headers_end && p[len] == '=')
          return p + 1 + len;
        else if (p = strchr(p, ';'))
          p += 2;
        else if ((s = strchr(s, 0)) && s < ctx->headers_end) {
          s += 2;
          break;
        }
        else
          return NULL;
      }
    } else {
      if ((s = strchr(p, 0)) && s < ctx->headers_end)
        s += 2;
      else
        return NULL;
    }
  }

  return NULL;
}

uw_unit uw_Basis_set_cookie(uw_context ctx, uw_Basis_string prefix, uw_Basis_string c, uw_Basis_string v) {
  uw_write_header(ctx, "Set-Cookie: ");
  uw_write_header(ctx, c);
  uw_write_header(ctx, "=");
  uw_write_header(ctx, v);
  uw_write_header(ctx, "; path=");
  uw_write_header(ctx, prefix);
  uw_write_header(ctx, "\r\n");

  return uw_unit_v;
}

static delta *allocate_delta(uw_context ctx, unsigned client) {
  unsigned i;
  delta *d;

  for (i = 0; i < ctx->used_deltas; ++i)
    if (ctx->deltas[i].client == client)
      return &ctx->deltas[i];

  if (ctx->used_deltas >= ctx->n_deltas) {
    ctx->deltas = realloc(ctx->deltas, sizeof(delta) * ++ctx->n_deltas);
    buf_init(&ctx->deltas[ctx->n_deltas-1].msgs, 0);
  }

  d = &ctx->deltas[ctx->used_deltas++];
  d->client = client;
  buf_reset(&d->msgs);
  return d;
}

uw_Basis_channel uw_Basis_new_channel(uw_context ctx, uw_unit u) {
  if (ctx->client == NULL)
    uw_error(ctx, FATAL, "Attempt to create channel on request not associated with a persistent connection");

  return new_channel(ctx->client);
}

uw_unit uw_Basis_send(uw_context ctx, uw_Basis_channel chn, uw_Basis_string msg) {
  delta *d = allocate_delta(ctx, chn.cli);
  size_t len;
  int preLen;
  char pre[INTS_MAX + 2];

  len = strlen(msg);

  sprintf(pre, "%u\n%n", chn.chn, &preLen);

  buf_append(&d->msgs, pre, preLen);
  buf_append(&d->msgs, msg, len);
  buf_append(&d->msgs, "\n", 1);

  return uw_unit_v;
}

int uw_db_commit(uw_context);
int uw_db_rollback(uw_context);

void uw_commit(uw_context ctx) {
  unsigned i;

  for (i = 0; i < ctx->used_transactionals; ++i)
    if (ctx->transactionals[i].rollback != NULL)
      ctx->transactionals[i].commit(ctx->transactionals[i].data);

  for (i = 0; i < ctx->used_transactionals; ++i)
    if (ctx->transactionals[i].rollback == NULL)
      ctx->transactionals[i].commit(ctx->transactionals[i].data);

  if (uw_db_commit(ctx))
    uw_error(ctx, FATAL, "Error running SQL COMMIT");

  for (i = 0; i < ctx->used_deltas; ++i) {
    delta *d = &ctx->deltas[i];
    client *c = find_client(d->client);

    assert (c != NULL && c->mode == USED);

    client_send(c, &d->msgs);
  }

  if (ctx->client)
    release_client(ctx->client);

  for (i = 0; i < ctx->used_transactionals; ++i)
    ctx->transactionals[i].free(ctx->transactionals[i].data);
}

int uw_rollback(uw_context ctx) {
  size_t i;

  if (ctx->client)
    release_client(ctx->client);

  for (i = 0; i < ctx->used_transactionals; ++i)
    if (ctx->transactionals[i].rollback != NULL)
      ctx->transactionals[i].rollback(ctx->transactionals[i].data);

  for (i = 0; i < ctx->used_transactionals; ++i)
    ctx->transactionals[i].free(ctx->transactionals[i].data);

  return uw_db_rollback(ctx);
}

void uw_register_transactional(uw_context ctx, void *data, uw_callback commit, uw_callback rollback,
                               uw_callback free) {
  if (commit == NULL)
    uw_error(ctx, FATAL, "uw_register_transactional: NULL commit callback");

  if (ctx->used_transactionals >= ctx->n_transactionals) {
    ctx->transactionals = realloc(ctx->transactionals, ctx->used_transactionals+1);
    ++ctx->n_transactionals;
  }

  ctx->transactionals[ctx->used_transactionals].data = data;
  ctx->transactionals[ctx->used_transactionals].commit = commit;
  ctx->transactionals[ctx->used_transactionals].rollback = rollback;
  ctx->transactionals[ctx->used_transactionals++].free = free;
}


// "Garbage collection"

void uw_expunger(uw_context ctx, uw_Basis_client cli);

static failure_kind uw_expunge(uw_context ctx, uw_Basis_client cli) {
  int r = setjmp(ctx->jmp_buf);

  if (r == 0) {
    if (uw_db_begin(ctx))
      uw_error(ctx, FATAL, "Error running SQL BEGIN");
    uw_expunger(ctx, cli);
    if (uw_db_commit(ctx))
      uw_error(ctx, FATAL, "Error running SQL COMMIT");
  }

  return r;
}

void uw_prune_clients(uw_context ctx) {
  client *c, *next, *prev = NULL;
  time_t cutoff;

  cutoff = time(NULL) - uw_timeout;

  pthread_mutex_lock(&clients_mutex);

  for (c = clients_used; c; c = next) {
    next = c->next;
    pthread_mutex_lock(&c->lock);
    if (c->last_contact < cutoff && c->refcount == 0) {
      failure_kind fk = UNLIMITED_RETRY;
      if (prev)
        prev->next = next;
      else
        clients_used = next;
      uw_reset(ctx);
      while (fk == UNLIMITED_RETRY) {
        fk = uw_expunge(ctx, c->id);
        if (fk == UNLIMITED_RETRY) {
          uw_db_rollback(ctx);
          printf("Unlimited retry during expunge: %s\n", uw_error_message(ctx));
        }
      }
      if (fk == SUCCESS)
        free_client(c);
      else {
        uw_db_rollback(ctx);
        printf("Expunge blocked by error: %s\n", uw_error_message(ctx));
      }
    }
    else
      prev = c;
    pthread_mutex_unlock(&c->lock);
  }

  pthread_mutex_unlock(&clients_mutex);
}

void uw_initializer(uw_context ctx);

failure_kind uw_initialize(uw_context ctx) {
  int r = setjmp(ctx->jmp_buf);

  if (r == 0) {
    if (uw_db_begin(ctx))
      uw_error(ctx, FATAL, "Error running SQL BEGIN");
    uw_initializer(ctx);
    if (uw_db_commit(ctx))
      uw_error(ctx, FATAL, "Error running SQL COMMIT");
  }

  return r;
}

extern int uw_check_url(const char *);
extern int uw_check_mime(const char *);

uw_Basis_string uw_Basis_bless(uw_context ctx, uw_Basis_string s) {
  if (uw_check_url(s))
    return s;
  else
    uw_error(ctx, FATAL, "Disallowed URL %s", uw_Basis_htmlifyString(ctx, s));
}

uw_Basis_string uw_Basis_checkUrl(uw_context ctx, uw_Basis_string s) {
  if (uw_check_url(s))
    return s;
  else
    return NULL;
}

int mime_format(const char *s) {
  for (; *s; ++s)
    if (!isalnum(*s) && *s != '/' && *s != '-' && *s != '.')
      return 0;

  return 1;
}

uw_Basis_string uw_Basis_blessMime(uw_context ctx, uw_Basis_string s) {
  if (!mime_format(s))
    uw_error(ctx, FATAL, "MIME type \"%s\" contains invalid character", uw_Basis_htmlifyString(ctx, s));

  if (uw_check_mime(s))
    return s;
  else
    uw_error(ctx, FATAL, "Disallowed MIME type %s", uw_Basis_htmlifyString(ctx, s));
}

uw_Basis_string uw_Basis_checkMime(uw_context ctx, uw_Basis_string s) {
  if (!mime_format(s))
    return NULL;

  if (uw_check_mime(s))
    return s;
  else
    return NULL;
}

uw_Basis_string uw_unnull(uw_Basis_string s) {
  return s ? s : "";
}

extern int uw_hash_blocksize;

uw_Basis_string uw_Basis_makeSigString(uw_context ctx, uw_Basis_string sig) {
  uw_Basis_string r = uw_malloc(ctx, 2 * uw_hash_blocksize + 1);
  int i;
  
  for (i = 0; i < uw_hash_blocksize; ++i)
    sprintf(&r[2*i], "%.02X", ((unsigned char *)sig)[i]);

  return r;
}

uw_Basis_string uw_Basis_sigString(uw_context ctx, uw_unit u) {
  return uw_cookie_sig(ctx);
}

uw_Basis_string uw_Basis_fileName(uw_context ctx, uw_Basis_file f) {
  return f.name;
}

uw_Basis_string uw_Basis_fileMimeType(uw_context ctx, uw_Basis_file f) {
  return f.type;
}

uw_Basis_int uw_Basis_blobSize(uw_context ctx, uw_Basis_blob b) {
  return b.size;
}

uw_Basis_blob uw_Basis_fileData(uw_context ctx, uw_Basis_file f) {
  return f.data;
}

__attribute__((noreturn)) void uw_return_blob(uw_context ctx, uw_Basis_blob b, uw_Basis_string mimeType) {
  cleanup *cl;
  int len;

  buf_reset(&ctx->outHeaders);
  buf_reset(&ctx->page);

  uw_write_header(ctx, "HTTP/1.1 200 OK\r\nContent-Type: ");
  uw_write_header(ctx, mimeType);
  uw_write_header(ctx, "\r\nContent-Length: ");
  buf_check(&ctx->outHeaders, INTS_MAX);
  sprintf(ctx->outHeaders.front, "%d%n", b.size, &len);
  ctx->outHeaders.front += len;
  uw_write_header(ctx, "\r\n");  

  buf_append(&ctx->page, b.data, b.size);

  for (cl = ctx->cleanup; cl < ctx->cleanup_front; ++cl)
    cl->func(cl->arg);

  ctx->cleanup_front = ctx->cleanup;

  longjmp(ctx->jmp_buf, RETURN_BLOB);
}