File: http.c

package info (click to toggle)
kannel 1.4.5-22
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,284 kB
  • sloc: ansic: 105,659; sh: 32,211; xml: 20,360; php: 1,103; perl: 711; makefile: 583; yacc: 548; awk: 133; python: 122; javascript: 27; pascal: 3
file content (3655 lines) | stat: -rw-r--r-- 102,816 bytes parent folder | download | duplicates (5)
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
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
/* ==================================================================== 
 * The Kannel Software License, Version 1.0 
 * 
 * Copyright (c) 2001-2018 Kannel Group  
 * Copyright (c) 1998-2001 WapIT Ltd.   
 * All rights reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright 
 *    notice, this list of conditions and the following disclaimer. 
 * 
 * 2. Redistributions in binary form must reproduce the above copyright 
 *    notice, this list of conditions and the following disclaimer in 
 *    the documentation and/or other materials provided with the 
 *    distribution. 
 * 
 * 3. The end-user documentation included with the redistribution, 
 *    if any, must include the following acknowledgment: 
 *       "This product includes software developed by the 
 *        Kannel Group (http://www.kannel.org/)." 
 *    Alternately, this acknowledgment may appear in the software itself, 
 *    if and wherever such third-party acknowledgments normally appear. 
 * 
 * 4. The names "Kannel" and "Kannel Group" must not be used to 
 *    endorse or promote products derived from this software without 
 *    prior written permission. For written permission, please  
 *    contact org@kannel.org. 
 * 
 * 5. Products derived from this software may not be called "Kannel", 
 *    nor may "Kannel" appear in their name, without prior written 
 *    permission of the Kannel Group. 
 * 
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED.  IN NO EVENT SHALL THE KANNEL GROUP OR ITS CONTRIBUTORS 
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,  
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR  
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,  
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE  
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,  
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 * ==================================================================== 
 * 
 * This software consists of voluntary contributions made by many 
 * individuals on behalf of the Kannel Group.  For more information on  
 * the Kannel Group, please see <http://www.kannel.org/>. 
 * 
 * Portions of this software are based upon software originally written at  
 * WapIT Ltd., Helsinki, Finland for the Kannel project.  
 */ 

/*
 * http.c - HTTP protocol server and client implementation
 *
 * Implements major parts of the Hypertext Transfer Protocol HTTP/1.1 (RFC 2616)
 * See http://www.w3.org/Protocols/rfc2616/rfc2616.txt
 *
 * Lars Wirzenius
 */
 
/* XXX re-implement socket pools, with idle connection killing to 
    	save sockets */
/* XXX implement http_abort */
/* XXX give maximum input size */
/* XXX kill http_get_real */
/* XXX the proxy exceptions list should be a dict, I guess */
/* XXX set maximum number of concurrent connections to same host, total? */
/* XXX 100 status codes. */
/* XXX stop destroying persistent connections when a request is redirected */

#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "gwlib.h"
#include "gwlib/regex.h"

/* comment this out if you don't want HTTP responses to be dumped */
#define DUMP_RESPONSE 1

/* define http client connections timeout in seconds (set to -1 for disable) */
static int http_client_timeout = 240;

/* define http server connections timeout in seconds (set to -1 for disable) */
#define HTTP_SERVER_TIMEOUT 60
/* max accepted clients */
#define HTTP_SERVER_MAX_ACTIVE_CONNECTIONS 500

/***********************************************************************
 * Stuff used in several sub-modules.
 */


/*
 * Default port to connect to for HTTP connections.
 */
enum { HTTP_PORT = 80,
       HTTPS_PORT = 443 };


/*
 * Status of this module.
 */
static enum { 
    limbo, 
    running, 
    terminating 
} run_status = limbo;


/*
 * Which interface to use for outgoing HTTP requests.
 */
static Octstr *http_interface = NULL;


/*
 * Read some headers, i.e., until the first empty line (read and discard
 * the empty line as well). Return -1 for error, 0 for all headers read,
 * 1 for more headers to follow.
 */
static int read_some_headers(Connection *conn, List *headers)
{
    Octstr *line, *prev;

    if (gwlist_len(headers) == 0)
        prev = NULL;
    else
    	prev = gwlist_get(headers, gwlist_len(headers) - 1);

    for (;;) {
	line = conn_read_line(conn);
	if (line == NULL) {
            if (conn_eof(conn) || conn_error(conn))
	    	return -1;
	    return 1;
	}
        if (octstr_len(line) == 0) {
            octstr_destroy(line);
            break;
        }
        if (isspace(octstr_get_char(line, 0)) && prev != NULL) {
            octstr_append(prev, line);
            octstr_destroy(line);
        } else {
            gwlist_append(headers, line);
            prev = line;
        }
    }

    return 0;
}


/*
 * Check that the HTTP version string is valid. Return -1 for invalid,
 * 0 for version 1.0, 1 for 1.x.
 */
static int parse_http_version(Octstr *version)
{
    Octstr *prefix;
    long prefix_len;
    int digit;
    
    prefix = octstr_imm("HTTP/1.");
    prefix_len = octstr_len(prefix);

    if (octstr_ncompare(version, prefix, prefix_len) != 0)
    	return -1;
    if (octstr_len(version) != prefix_len + 1)
    	return -1;
    digit = octstr_get_char(version, prefix_len);
    if (!isdigit(digit))
    	return -1;
    if (digit == '0')
    	return 0;
    return 1;
}


/***********************************************************************
 * Proxy support.
 */


/*
 * Data and functions needed to support proxy operations. If proxy_hostname 
 * is NULL, no proxy is used.
 */
static Mutex *proxy_mutex = NULL;
static Octstr *proxy_hostname = NULL;
static int proxy_port = 0;
static int proxy_ssl = 0;
static Octstr *proxy_username = NULL;
static Octstr *proxy_password = NULL;
static List *proxy_exceptions = NULL;
static regex_t *proxy_exceptions_regex = NULL;


static void proxy_add_authentication(List *headers)
{
    Octstr *os;
    
    if (proxy_username == NULL || proxy_password == NULL)
    	return;

    os = octstr_format("%S:%S", proxy_username, proxy_password);
    octstr_binary_to_base64(os);
    octstr_strip_blanks(os);
    octstr_insert(os, octstr_imm("Basic "), 0);
    http_header_add(headers, "Proxy-Authorization", octstr_get_cstr(os));
    octstr_destroy(os);
}


static void proxy_init(void)
{
    proxy_mutex = mutex_create();
    proxy_exceptions = gwlist_create();
}


static void proxy_shutdown(void)
{
    http_close_proxy();
    mutex_destroy(proxy_mutex);
    proxy_mutex = NULL;
}


static int proxy_used_for_host(Octstr *host, Octstr *url)
{
    int i;

    mutex_lock(proxy_mutex);

    if (proxy_hostname == NULL) {
        mutex_unlock(proxy_mutex);
        return 0;
    }

    for (i = 0; i < gwlist_len(proxy_exceptions); ++i) {
        if (octstr_compare(host, gwlist_get(proxy_exceptions, i)) == 0) {
            mutex_unlock(proxy_mutex);
            return 0;
        }
    }

    if (proxy_exceptions_regex != NULL && gw_regex_match_pre(proxy_exceptions_regex, url)) {
            mutex_unlock(proxy_mutex);
            return 0;
    }

    mutex_unlock(proxy_mutex);
    return 1;
}


void http_use_proxy(Octstr *hostname, int port, int ssl, List *exceptions,
    	    	    Octstr *username, Octstr *password, Octstr *exceptions_regex)
{
    Octstr *e;
    int i;

    gw_assert(run_status == running);
    gw_assert(hostname != NULL);
    gw_assert(octstr_len(hostname) > 0);
    gw_assert(port > 0);

    http_close_proxy();
    mutex_lock(proxy_mutex);

    proxy_hostname = octstr_duplicate(hostname);
    proxy_port = port;
    proxy_ssl = ssl;
    proxy_exceptions = gwlist_create();
    for (i = 0; i < gwlist_len(exceptions); ++i) {
        e = gwlist_get(exceptions, i);
        debug("gwlib.http", 0, "HTTP: Proxy exception `%s'.", octstr_get_cstr(e));
        gwlist_append(proxy_exceptions, octstr_duplicate(e));
    }
    if (exceptions_regex != NULL &&
        (proxy_exceptions_regex = gw_regex_comp(exceptions_regex, REG_EXTENDED)) == NULL)
            panic(0, "Could not compile pattern '%s'", octstr_get_cstr(exceptions_regex));
    proxy_username = octstr_duplicate(username);
    proxy_password = octstr_duplicate(password);
    debug("gwlib.http", 0, "Using proxy <%s:%d> with %s scheme", 
    	  octstr_get_cstr(proxy_hostname), proxy_port,
    	  (proxy_ssl ? "HTTPS" : "HTTP"));

    mutex_unlock(proxy_mutex);
}


void http_close_proxy(void)
{
    gw_assert(run_status == running || run_status == terminating);

    mutex_lock(proxy_mutex);
    proxy_port = 0;
    octstr_destroy(proxy_hostname);
    octstr_destroy(proxy_username);
    octstr_destroy(proxy_password);
    proxy_hostname = NULL;
    proxy_username = NULL;
    proxy_password = NULL;
    gwlist_destroy(proxy_exceptions, octstr_destroy_item);
    gw_regex_destroy(proxy_exceptions_regex);
    proxy_exceptions = NULL;
    proxy_exceptions_regex = NULL;
    mutex_unlock(proxy_mutex);
}


/***********************************************************************
 * Common functions for reading request or result entities.
 */

/*
 * Value to pass to entity_create.
 */
enum body_expectation {
   /*
    * Message must not have a body, even if the headers indicate one.
    * (i.e. response to HEAD method).
    */
   expect_no_body,
   /*
    * Message will have a body if Content-Length or Transfer-Encoding
    * headers are present (i.e. most request methods).
    */
   expect_body_if_indicated,
   /*
    * Message will have a body, possibly zero-length.
    * (i.e. 200 OK responses to a GET method.)
    */
   expect_body
};

enum entity_state {
    reading_headers,
    reading_chunked_body_len,
    reading_chunked_body_data,
    reading_chunked_body_crlf,
    reading_chunked_body_trailer,
    reading_body_until_eof,
    reading_body_with_length,
    body_error,
    entity_done
};

typedef struct {
    List *headers;
    Octstr *body;
    enum body_expectation expect_state;
    enum entity_state state;
    long chunked_body_chunk_len;
    long expected_body_len;
} HTTPEntity;


/*
 * The rules for message bodies (length and presence) are defined
 * in RFC2616 paragraph 4.3 and 4.4.
 */
static void deduce_body_state(HTTPEntity *ent)
{
    Octstr *h = NULL;

    if (ent->expect_state == expect_no_body) {
        ent->state = entity_done;
        return;
    }

    ent->state = body_error;  /* safety net */

    h = http_header_find_first(ent->headers, "Transfer-Encoding");
    if (h != NULL) {
        octstr_strip_blanks(h);
        if (octstr_str_compare(h, "chunked") != 0) {
            error(0, "HTTP: Unknown Transfer-Encoding <%s>",
                  octstr_get_cstr(h));
            ent->state = body_error;
        } else {
            ent->state = reading_chunked_body_len;
        }
        octstr_destroy(h);
        return;
    }

    h = http_header_find_first(ent->headers, "Content-Length");
    if (h != NULL) {
        if (octstr_parse_long(&ent->expected_body_len, h, 0, 10) == -1 ||
            ent->expected_body_len < 0) {
            error(0, "HTTP: Content-Length header wrong: <%s>",
                  octstr_get_cstr(h));
            ent->state = body_error;
        } else if (ent->expected_body_len == 0) {
            ent->state = entity_done;
        } else {
            ent->state = reading_body_with_length;
        }
        octstr_destroy(h);
        return;
    }

    if (ent->expect_state == expect_body)
        ent->state = reading_body_until_eof;
    else
        ent->state = entity_done;
}


/*
 * Create a HTTPEntity structure suitable for reading the expected
 * result or request message and decoding the transferred entity (if any).
 * See the definition of enum body_expectation for the possible values
 * of exp.
 */
static HTTPEntity *entity_create(enum body_expectation exp)
{
    HTTPEntity *ent;

    ent = gw_malloc(sizeof(*ent));
    ent->headers = http_create_empty_headers();
    ent->body = octstr_create("");
    ent->chunked_body_chunk_len = -1;
    ent->expected_body_len = -1;
    ent->state = reading_headers;
    ent->expect_state = exp;

    return ent;
}


static void entity_destroy(HTTPEntity *ent)
{
    if (ent == NULL)
        return;

    http_destroy_headers(ent->headers);
    octstr_destroy(ent->body);
    gw_free(ent);
}


static void read_chunked_body_len(HTTPEntity *ent, Connection *conn)
{
    Octstr *os;
    long len;
    
    os = conn_read_line(conn);
    if (os == NULL) {
        if (conn_error(conn) || conn_eof(conn))
	    ent->state = body_error;
        return;
    }
    if (octstr_parse_long(&len, os, 0, 16) == -1) {
        octstr_destroy(os);
	ent->state = body_error;
        return;
    }
    octstr_destroy(os);
    if (len == 0)
        ent->state = reading_chunked_body_trailer;
    else {
        ent->state = reading_chunked_body_data;
        ent->chunked_body_chunk_len = len;
    }
}


static void read_chunked_body_data(HTTPEntity *ent, Connection *conn)
{
    Octstr *os;

    os = conn_read_fixed(conn, ent->chunked_body_chunk_len);
    if (os == NULL) {
        if (conn_error(conn) || conn_eof(conn))
	    ent->state = body_error;
    } else {
        octstr_append(ent->body, os);
        octstr_destroy(os);
        ent->state = reading_chunked_body_crlf;
    }
}


static void read_chunked_body_crlf(HTTPEntity *ent, Connection *conn)
{
    Octstr *os;

    os = conn_read_line(conn);
    if (os == NULL) {
        if (conn_error(conn) || conn_eof(conn))
	    ent->state = body_error;
    } else {
        octstr_destroy(os);
        ent->state = reading_chunked_body_len;
    }
}


static void read_chunked_body_trailer(HTTPEntity *ent, Connection *conn)
{
    int ret;

    ret = read_some_headers(conn, ent->headers);
    if (ret == -1)
	ent->state = body_error;
    if (ret == 0)
        ent->state = entity_done;
}


static void read_body_until_eof(HTTPEntity *ent, Connection *conn)
{
    Octstr *os;

    while ((os = conn_read_everything(conn)) != NULL) {
        octstr_append(ent->body, os);
        octstr_destroy(os);
    }
    if (conn_error(conn))
	ent->state = body_error;
    if (conn_eof(conn))
	ent->state = entity_done;
}


static void read_body_with_length(HTTPEntity *ent, Connection *conn)
{
    Octstr *os;

    os = conn_read_fixed(conn, ent->expected_body_len);
    if (os == NULL) {
        if (conn_error(conn) || conn_eof(conn))
            ent->state = body_error;
        return;
    }
    octstr_destroy(ent->body);
    ent->body = os;
    ent->state = entity_done;
}


/*
 * Read headers and body (if any) from this connection.  Return 0 if it's
 * complete, 1 if we expect more input, and -1 if there is something wrong.
 */
static int entity_read(HTTPEntity *ent, Connection *conn)
{
    int ret;
    enum entity_state old_state;

    /*
     * In this loop, each state will process as much input as it needs
     * and then switch to the next state, unless it's a final state in
     * which case it returns directly, or unless it needs more input.
     * So keep looping as long as the state changes.
     */
    do {
        old_state = ent->state;
        switch (ent->state) {
        case reading_headers:
            ret = read_some_headers(conn, ent->headers);
                if (ret == 0)
                deduce_body_state(ent);
            if (ret < 0)
            return -1;
            break;

        case reading_chunked_body_len:
            read_chunked_body_len(ent, conn);
            break;

        case reading_chunked_body_data:
            read_chunked_body_data(ent, conn);
            break;

        case reading_chunked_body_crlf:
            read_chunked_body_crlf(ent, conn);
            break;

        case reading_chunked_body_trailer:
            read_chunked_body_trailer(ent, conn);
            break;

        case reading_body_until_eof:
            read_body_until_eof(ent, conn);
            break;

        case reading_body_with_length:
            read_body_with_length(ent, conn);
            break;

        case body_error:
            return -1;

        case entity_done:
            return 0;

        default:
            panic(0, "Internal error: Invalid HTTPEntity state.");
        }
    } while (ent->state != old_state);

    /*
     * If we got here, then the loop ended because a non-final state
     * needed more input.
     */
    return 1;
}


/***********************************************************************
 * HTTP client interface.
 */

/*
 * Internal lists of completely unhandled requests and requests for which
 * a request has been sent but response has not yet been read.
 */
static List *pending_requests = NULL;


/*
 * Have background threads been started?
 */
static Mutex *client_thread_lock = NULL;
static volatile sig_atomic_t client_threads_are_running = 0;


/*
 * Set of all connections to all servers. Used with conn_register to
 * do I/O on several connections with a single thread.
 */
static FDSet *client_fdset = NULL;

/*
 * Maximum number of HTTP redirections to follow. Making this infinite
 * could cause infinite looping if the redirections loop.
 */
#define HTTP_MAX_FOLLOW 5


/*
 * The implemented HTTP method strings
 * Order is sequenced by the enum in the header
 */
static char *http_methods[] = {
    "GET", "POST", "HEAD"
};

/*
 * Information about a server we've connected to.
 */
typedef struct {
    HTTPCaller *caller;
    void *request_id;
    int method;             /* uses enums from http.h for the HTTP methods */
    Octstr *url;            /* the full URL, including scheme, host, etc. */
    Octstr *uri;            /* the HTTP URI path only */
    List *request_headers;
    Octstr *request_body;   /* NULL for GET or HEAD, non-NULL for POST */
    enum {
	connecting,
	request_not_sent,
	reading_status,
	reading_entity,
	transaction_done
    } state;
    long status;
    int persistent;
    HTTPEntity *response; /* Can only be NULL if status < 0 */
    Connection *conn;
    Octstr *host;
    long port;
    int follow_remaining;
    Octstr *certkeyfile;
    int ssl;
    Octstr *username;	/* For basic authentication */
    Octstr *password;
} HTTPServer;


static int send_request(HTTPServer *trans);
static Octstr *build_response(List *headers, Octstr *body);
static int header_is_called(Octstr *header, char *name);

static HTTPServer *server_create(HTTPCaller *caller, int method, Octstr *url,
                                 List *headers, Octstr *body, int follow_remaining,
                                 Octstr *certkeyfile)
{
    HTTPServer *trans;
    
    trans = gw_malloc(sizeof(*trans));
    trans->caller = caller;
    trans->request_id = NULL;
    trans->method = method;
    trans->url = octstr_duplicate(url);
    trans->uri = NULL;
    trans->request_headers = http_header_duplicate(headers);
    trans->request_body = octstr_duplicate(body);
    trans->state = request_not_sent;
    trans->status = -1;
    trans->persistent = 0;
    trans->response = NULL;
    trans->conn = NULL;
    trans->host = NULL;
    trans->port = 0;
    trans->username = NULL;
    trans->password = NULL;
    trans->follow_remaining = follow_remaining;
    trans->certkeyfile = octstr_duplicate(certkeyfile);
    trans->ssl = 0;
    return trans;
}


static void server_destroy(void *p)
{
    HTTPServer *trans;
    
    trans = p;
    octstr_destroy(trans->url);
    octstr_destroy(trans->uri);
    http_destroy_headers(trans->request_headers);
    trans->request_headers = NULL;
    octstr_destroy(trans->request_body);
    entity_destroy(trans->response);
    octstr_destroy(trans->host);
    octstr_destroy(trans->certkeyfile);
    octstr_destroy(trans->username);
    octstr_destroy(trans->password);
    gw_free(trans);
}


/*
 * Pool of open, but unused connections to servers or proxies. Key is
 * "servername:port", value is List with Connection objects.
 */
static Dict *conn_pool;
static Mutex *conn_pool_lock;


static void conn_pool_item_destroy(void *item)
{
    gwlist_destroy(item, (void(*)(void*))conn_destroy);
}

static void conn_pool_init(void)
{
    conn_pool = dict_create(1024, conn_pool_item_destroy);
    conn_pool_lock = mutex_create();
}


static void conn_pool_shutdown(void)
{
    dict_destroy(conn_pool);
    mutex_destroy(conn_pool_lock);
}


static inline Octstr *conn_pool_key(Octstr *host, int port, int ssl, Octstr *certfile, Octstr *our_host)
{
    return octstr_format("%S:%d:%d:%S:%S", host, port, ssl?1:0, certfile?certfile:octstr_imm(""),
                         our_host?our_host:octstr_imm(""));
}


static Connection *conn_pool_get(Octstr *host, int port, int ssl, Octstr *certkeyfile,
		Octstr *our_host)
{
    Octstr *key;
    List *list = NULL;
    Connection *conn = NULL;
    int retry;

    do {
        retry = 0;
        key = conn_pool_key(host, port, ssl, certkeyfile, our_host);
        mutex_lock(conn_pool_lock);
        list = dict_get(conn_pool, key);
        if (list != NULL)
            conn = gwlist_extract_first(list);
        mutex_unlock(conn_pool_lock);
        /*
         * Note: we don't hold conn_pool_lock when we check/destroy/unregister
         *       connection because otherwise we can deadlock! And it's even better
         *       not to delay other threads while we check connection.
         */
        if (conn != NULL) {
#ifdef USE_KEEPALIVE
            /* unregister our server disconnect callback */
            conn_unregister(conn);
#endif 
            /*
             * Check whether the server has closed the connection while
             * it has been in the pool.
             */
            conn_wait(conn, 0);
            if (conn_eof(conn) || conn_error(conn)) {
                debug("gwlib.http", 0, "HTTP:conn_pool_get: Server closed connection, destroying it <%s><%p><fd:%d>.",
                      octstr_get_cstr(key), conn, conn_get_id(conn));
                conn_destroy(conn);
                retry = 1;
                conn = NULL;
            }
        }
        octstr_destroy(key);
    } while(retry == 1);
    
    if (conn == NULL) {
#ifdef HAVE_LIBSSL
        if (ssl) 
            conn = conn_open_ssl_nb(host, port, certkeyfile, our_host);
        else
#endif /* HAVE_LIBSSL */
            conn = conn_open_tcp_nb(host, port, our_host);
        debug("gwlib.http", 0, "HTTP: Opening connection to `%s:%d' (fd=%d).",
              octstr_get_cstr(host), port, conn_get_id(conn));
    } else {
        debug("gwlib.http", 0, "HTTP: Reusing connection to `%s:%d' (fd=%d).",
              octstr_get_cstr(host), port, conn_get_id(conn)); 
    }
    
    return conn;
}

#ifdef USE_KEEPALIVE
static void check_pool_conn(Connection *conn, void *data)
{
    Octstr *key = data;
    
    if (run_status != running) {
        conn_unregister(conn);
        return;
    }
    /* check if connection still ok */
    if (conn_error(conn) || conn_eof(conn)) {
        List *list;
        mutex_lock(conn_pool_lock);
        list = dict_get(conn_pool, key);
        if (gwlist_delete_equal(list, conn) > 0) {
            /*
             * ok, connection was still within pool. So it's
             * safe to destroy this connection.
             */
            debug("gwlib.http", 0, "HTTP: Server closed connection, destroying it <%s><%p><fd:%d>.",
                  octstr_get_cstr(key), conn, conn_get_id(conn));
            conn_unregister(conn);
            conn_destroy(conn);
        }
        /*
         * it's perfectly valid if connection was not found in connection pool because
         * in 'conn_pool_get' we first removed connection from pool with conn_pool_lock locked
         * and then check connection for errors with conn_pool_lock unlocked. In the meantime
         * fdset's poller may call us. So just ignore such "dummy" call.
        */
        mutex_unlock(conn_pool_lock);
    }
}


static void conn_pool_put(Connection *conn, Octstr *host, int port, int ssl, Octstr *certfile, Octstr *our_host)
{
    Octstr *key;
    List *list;

    key = conn_pool_key(host, port, ssl, certfile, our_host);
    mutex_lock(conn_pool_lock);
    list = dict_get(conn_pool, key);
    if (list == NULL) {
    	list = gwlist_create();
        dict_put(conn_pool, key, list);
    }
    gwlist_append(list, conn);
    /* register connection to get server disconnect */
    conn_register_real(conn, client_fdset, check_pool_conn, key, octstr_destroy_item);
    mutex_unlock(conn_pool_lock);
}
#endif


HTTPCaller *http_caller_create(void)
{
    HTTPCaller *caller;
    
    caller = gwlist_create();
    gwlist_add_producer(caller);
    return caller;
}


void http_caller_destroy(HTTPCaller *caller)
{
    gwlist_destroy(caller, server_destroy);
}


void http_caller_signal_shutdown(HTTPCaller *caller)
{
    gwlist_remove_producer(caller);
}


static Octstr *get_redirection_location(HTTPServer *trans)
{
    if (trans->status < 0 || trans->follow_remaining <= 0)
    	return NULL;
    /* check for the redirection response codes */
    if (trans->status != HTTP_MOVED_PERMANENTLY &&
    	trans->status != HTTP_FOUND && trans->status != HTTP_SEE_OTHER &&
        trans->status != HTTP_TEMPORARY_REDIRECT)
	return NULL;
    if (trans->response == NULL)
        return NULL;
    return http_header_find_first(trans->response->headers, "Location");
}


/* 
 * Recovers a Location header value of format URI /xyz to an 
 * absoluteURI format according to the protocol rules. 
 * This simply implies that we re-create the prefixed scheme,
 * user/passwd (if any), host and port string and prepend it
 * to the location URI.
 */
static void recover_absolute_uri(HTTPServer *trans, Octstr *loc)
{
    Octstr *os;
    
    gw_assert(loc != NULL && trans != NULL);
    
    /* we'll only accept locations with a leading / */
    if (octstr_get_char(loc, 0) == '/') {
        
        /* scheme */
        os = trans->ssl ? octstr_create("https://") : 
            octstr_create("http://");
        
        /* credentials, if any */
        if (trans->username && trans->password) {
            octstr_append(os, trans->username);
            octstr_append_char(os, ':');
            octstr_append(os, trans->password);
            octstr_append_char(os, '@');
        }
        
        /* host */
        octstr_append(os, trans->host);
        
        /* port, only added if literally not default. */
        if (trans->port != 80 || trans->ssl) {
            octstr_format_append(os, ":%ld", trans->port);
        }
        
        /* prepend the created octstr to the loc, and destroy then. */
        octstr_insert(loc, os, 0);
        octstr_destroy(os);
    }
}


/*
 * Read and parse the status response line from an HTTP server.
 * Fill in trans->persistent and trans->status with the findings.
 * Return -1 for error, 1 for status line not yet available, 0 for OK.
 */
static int client_read_status(HTTPServer *trans)
{
    Octstr *line, *version;
    long space;
    int ret;

    line = conn_read_line(trans->conn);
    if (line == NULL) {
	if (conn_eof(trans->conn) || conn_error(trans->conn))
	    return -1;
    	return 1;
    }

    debug("gwlib.http", 0, "HTTP: Status line: <%s>", octstr_get_cstr(line));

    space = octstr_search_char(line, ' ', 0);
    if (space == -1)
    	goto error;
	
    version = octstr_copy(line, 0, space);
    ret = parse_http_version(version);
    octstr_destroy(version);
    if (ret == -1)
    	goto error;
    trans->persistent = ret;

    octstr_delete(line, 0, space + 1);
    space = octstr_search_char(line, ' ', 0);
    if (space == -1)
    	goto error;
    octstr_truncate(line, space);
	
    if (octstr_parse_long(&trans->status, line, 0, 10) == -1)
        goto error;

    octstr_destroy(line);
    return 0;

error:
    error(0, "HTTP: Malformed status line from HTTP server: <%s>",
	  octstr_get_cstr(line));
    octstr_destroy(line);
    return -1;
}

static int response_expectation(int method, int status)
{
    if (status == HTTP_NO_CONTENT ||
        status == HTTP_NOT_MODIFIED ||
        http_status_class(status) == HTTP_STATUS_PROVISIONAL ||
        method == HTTP_METHOD_HEAD)
	return expect_no_body;
    else
        return expect_body;
}

static void handle_transaction(Connection *conn, void *data)
{
    HTTPServer *trans;
    int ret;
    Octstr *h;
    int rc;
    
    trans = data;

    if (run_status != running) {
        conn_unregister(conn);
        return;
    }

    while (trans->state != transaction_done) {
        switch (trans->state) {
        case connecting:
            debug("gwlib.http", 0, "Get info about connecting socket");
            if (conn_get_connect_result(trans->conn) != 0) {
                debug("gwlib.http", 0, "Socket not connected");
                goto error;
            }

            if ((rc = send_request(trans)) == 0) {
                trans->state = reading_status;
            } else {
                debug("gwlib.http", 0, "Failed while sending request");
                goto error;
            }
            break;

        case reading_status:
            ret = client_read_status(trans);
            if (ret < 0) {
                /*
                 * Couldn't read the status from the socket. This may mean
                 * that the socket had been closed by the server after an
                 * idle timeout.
                 */
                debug("gwlib.http",0,"Failed while reading status");
                goto error;
            } else if (ret == 0) {
                /* Got the status, go read headers and body next. */
                trans->state = reading_entity;
                trans->response = entity_create(response_expectation(trans->method, trans->status));
            } else {
                return;
            }
            break;

        case reading_entity:
            ret = entity_read(trans->response, conn);
            if (ret < 0) {
                debug("gwlib.http",0,"Failed reading entity");
                goto error;
            } else if (ret == 0 &&
                       http_status_class(trans->status) == HTTP_STATUS_PROVISIONAL) {
                /* This was a provisional reply; get the real one now. */
                trans->state = reading_status;
                entity_destroy(trans->response);
                trans->response = NULL;
            } else if (ret == 0) {
                trans->state = transaction_done;
#ifdef DUMP_RESPONSE
                /* Dump the response */
                debug("gwlib.http", 0, "HTTP: Received response:");
                h = build_response(trans->response->headers, trans->response->body);
                octstr_dump(h, 0);
                octstr_destroy(h);
#endif
            } else {
                return;
            }
            break;

        default:
            panic(0, "Internal error: Invalid HTTPServer state.");
        }
    }

    conn_unregister(trans->conn);

    /* 
     * Take care of persistent connection handling. 
     * At this point we have only obeyed if server responds in HTTP/1.0 or 1.1
     * and have assigned trans->persistent accordingly. This can be keept
     * for default usage, but if we have [Proxy-]Connection: keep-alive, then
     * we're still forcing persistancy of the connection.
     */
    h = http_header_find_first(trans->response->headers, "Connection");
    if (h != NULL && octstr_case_compare(h, octstr_imm("close")) == 0)
        trans->persistent = 0;
    if (h != NULL && octstr_case_compare(h, octstr_imm("keep-alive")) == 0)
        trans->persistent = 1;
    octstr_destroy(h);
    if (proxy_used_for_host(trans->host, trans->url)) {
        h = http_header_find_first(trans->response->headers, "Proxy-Connection");
        if (h != NULL && octstr_case_compare(h, octstr_imm("close")) == 0)
            trans->persistent = 0;
        if (h != NULL && octstr_case_compare(h, octstr_imm("keep-alive")) == 0)
            trans->persistent = 1;
        octstr_destroy(h);
    }

#ifdef USE_KEEPALIVE 
    if (trans->persistent) {
        if (proxy_used_for_host(trans->host, trans->url))
            conn_pool_put(trans->conn, proxy_hostname, proxy_port, trans->ssl, trans->certkeyfile, http_interface);
        else 
            conn_pool_put(trans->conn, trans->host, trans->port, trans->ssl, trans->certkeyfile, http_interface);
    } else
#endif
        conn_destroy(trans->conn);

    trans->conn = NULL;

    /* 
     * Check if the HTTP server told us to look somewhere else,
     * hence if we got one of the following response codes:
     *   HTTP_MOVED_PERMANENTLY (301)
     *   HTTP_FOUND (302)
     *   HTTP_SEE_OTHER (303)
     *   HTTP_TEMPORARY_REDIRECT (307)
     */
    if ((h = get_redirection_location(trans)) != NULL) {

        /* 
         * This is a redirected response, we have to follow.
         * 
         * According to HTTP/1.1 (RFC 2616), section 14.30 any Location
         * header value should be 'absoluteURI', which is defined in
         * RFC 2616, section 3.2.1 General Syntax, and specifically in
         * RFC 2396, section 3 URI Syntactic Components as
         * 
         *   absoluteURI   = scheme ":" ( hier_part | opaque_part )
         * 
         * Some HTTP servers 'interpret' a leading UDI / as that kind
         * of absoluteURI, which is not correct, following the protocol in
         * detail. But we'll try to recover from that misleaded 
         * interpreation and try to convert the partly absoluteURI to a
         * fully qualified absoluteURI.
         * 
         *   http_URL = "http:" "//" [ userid : password "@"] host 
         *      [ ":" port ] [ abs_path [ "?" query ]] 
         * 
         */
        octstr_strip_blanks(h);
        recover_absolute_uri(trans, h);
        
        /*
         * Clean up all trans stuff for the next request we do.
         */
        octstr_destroy(trans->url);
        octstr_destroy(trans->host);
        trans->port = 0;
        octstr_destroy(trans->uri);
        octstr_destroy(trans->username);
        octstr_destroy(trans->password);
        trans->host = NULL;
        trans->port = 0;
        trans->uri = NULL;
        trans->username = NULL;
        trans->password = NULL;
        trans->ssl = 0;
        trans->url = h; /* apply new absolute URL to next request */
        trans->state = request_not_sent;
        trans->status = -1;
        entity_destroy(trans->response);
        trans->response = NULL;
        --trans->follow_remaining;
        conn_destroy(trans->conn);
        trans->conn = NULL;

        /* re-inject request to the front of the queue */
        gwlist_insert(pending_requests, 0, trans);

    } else {
        /* handle this response as usual */
        gwlist_produce(trans->caller, trans);
    }
    return;

error:
    conn_unregister(trans->conn);
    conn_destroy(trans->conn);
    trans->conn = NULL;
    error(0, "Couldn't fetch <%s>", octstr_get_cstr(trans->url));
    trans->status = -1;
    gwlist_produce(trans->caller, trans);
}


/*
 * Build a complete HTTP request given the host, port, path and headers. 
 * Add Host: and Content-Length: headers (and others that may be necessary).
 * Return the request as an Octstr.
 */
static Octstr *build_request(char *method_name, Octstr *path_or_url, 
                             Octstr *host, long port, int ssl, List *headers,
                             Octstr *request_body)
{
    /* XXX headers missing */
    Octstr *request;
    int i, host_found = 0;

    request = octstr_format("%s %S HTTP/1.1\r\n",
                            method_name, path_or_url);

#ifdef USE_KEEPALIVE 
    octstr_append(request, octstr_imm("Connection: keep-alive\r\n"));
#endif

    for (i = 0; headers != NULL && i < gwlist_len(headers); ++i) {
        /* check if Host already set in the headers */
        if (header_is_called(gwlist_get(headers, i), "Host"))
            host_found = 1;
        octstr_append(request, gwlist_get(headers, i));
        octstr_append(request, octstr_imm("\r\n"));
    }

    if (!host_found) {
        octstr_format_append(request, "Host: %S", host);
        /*
         * In accordance with HTT/1.1 [RFC 2616], section 14.23 "Host"
         * we shall ONLY add the port number if it is not one of the
         * officially assigned port numbers. This means we need to obey
         * port 80 for non-SSL connections and port 443 for SSL-enabled.
         */
        if ((port != HTTP_PORT && !ssl) || (port != HTTPS_PORT && ssl))
            octstr_format_append(request, ":%ld", port);
        octstr_append(request, octstr_imm("\r\n"));
    }

    octstr_append(request, octstr_imm("\r\n"));

    if (request_body != NULL)
        octstr_append(request, request_body);

    return request;
}


/*
 * Re-build the HTTP response given the headers and the body.
 * Return the response as an Octstr.
 */
static Octstr *build_response(List *headers, Octstr *body)
{
    Octstr *response;
    int i;

    response = octstr_create("");

    for (i = 0; headers != NULL && i < gwlist_len(headers); ++i) {
        octstr_append(response, gwlist_get(headers, i));
        octstr_append(response, octstr_imm("\r\n"));
    }
    octstr_append(response, octstr_imm("\r\n"));

    if (body != NULL)
        octstr_append(response, body);

    return response;
}


HTTPURLParse *http_urlparse_create(void)
{
    HTTPURLParse *p;

    p = gw_malloc(sizeof(HTTPURLParse));
    p->url = NULL;
    p->scheme = NULL;
    p->host = NULL;
    p->port = 0;
    p->user = NULL;
    p->pass = NULL;
    p->path = NULL;
    p->query = NULL;
    p->fragment = NULL;
    
    return p;
}


void http_urlparse_destroy(HTTPURLParse *p)
{
    gw_assert(p != NULL);

    octstr_destroy(p->url);
    octstr_destroy(p->scheme);
    octstr_destroy(p->host);
    octstr_destroy(p->user);
    octstr_destroy(p->pass);
    octstr_destroy(p->path);
    octstr_destroy(p->query);
    octstr_destroy(p->fragment);
    gw_free(p);
}


void parse_dump(HTTPURLParse *p) 
{
    if (p == NULL)
        return;
    debug("http.parse_url",0,"Parsing URL `%s':", octstr_get_cstr(p->url));
    debug("http.parse_url",0,"  Scheme: %s", octstr_get_cstr(p->scheme));  
    debug("http.parse_url",0,"  Host: %s", octstr_get_cstr(p->host));  
    debug("http.parse_url",0,"  Port: %ld", p->port);  
    debug("http.parse_url",0,"  Username: %s", octstr_get_cstr(p->user));  
    debug("http.parse_url",0,"  Password: %s", octstr_get_cstr(p->pass));  
    debug("http.parse_url",0,"  Path: %s", octstr_get_cstr(p->path));  
    debug("http.parse_url",0,"  Query: %s", octstr_get_cstr(p->query));  
    debug("http.parse_url",0,"  Fragment: %s", octstr_get_cstr(p->fragment));  
}


/*
 * Parse the URL to get all components, which are: scheme, hostname, 
 * port, username, password, path (URI), query (the CGI parameter list), 
 * fragment (#).
 *
 * On success return the HTTPURLParse structure, otherwise NULL if the URL 
 * seems malformed.
 *
 * We assume HTTP URLs of the form specified in "3.2.2 http URL" in
 * RFC 2616:
 * 
 *  http_URL = "http:" "//" [ userid : password "@"] host [ ":" port ] [ abs_path [ "?" query ]] 
 */
HTTPURLParse *parse_url(Octstr *url)
{
    HTTPURLParse *p;
    Octstr *prefix, *prefix_https;
    long prefix_len;
    int host_len, colon, slash, at, auth_sep, query;
    host_len = colon = slash = at = auth_sep = query = 0;

    prefix = octstr_imm("http://");
    prefix_https = octstr_imm("https://");
    prefix_len = octstr_len(prefix);

    if (octstr_case_search(url, prefix, 0) != 0) {
        if (octstr_case_search(url, prefix_https, 0) == 0) {
#ifdef HAVE_LIBSSL
            debug("gwlib.http", 0, "HTTPS URL; Using SSL for the connection");
            prefix = prefix_https;
            prefix_len = octstr_len(prefix_https);	
#else
            error(0, "Attempt to use HTTPS <%s> but SSL not compiled in", 
                  octstr_get_cstr(url));
            return NULL;
#endif
        } else {
            error(0, "URL <%s> doesn't start with `%s' nor `%s'",
            octstr_get_cstr(url), octstr_get_cstr(prefix),
            octstr_get_cstr(prefix_https));
            return NULL;
        }
    }

    /* an URL should be more (at least one charset) then the scheme itself */
    if (octstr_len(url) == prefix_len) {
        error(0, "URL <%s> is malformed.", octstr_get_cstr(url));
        return NULL;
    }

    /* check if colon and slashes are within scheme */
    colon = octstr_search_char(url, ':', prefix_len);
    slash = octstr_search_char(url, '/', prefix_len);
    if (colon == prefix_len || slash == prefix_len) {
        error(0, "URL <%s> is malformed.", octstr_get_cstr(url));
        return NULL;
    }

    /* create struct and add values succesively while parsing */
    p = http_urlparse_create();
    p->url = octstr_duplicate(url);
    p->scheme = octstr_duplicate(prefix);

    /* try to parse authentication separator */
    at = octstr_search_char(url, '@', prefix_len);
    if (at != -1) {
        if ((slash == -1 || ( slash != -1 && at < slash))) {
            auth_sep = octstr_search_char(url, ':', prefix_len);
            if (auth_sep != -1 && (auth_sep < at)) {
                octstr_set_char(url, auth_sep, '@');
                colon = octstr_search_char(url, ':', prefix_len);
            }
        } else {
            at = -1;
        }
    }

    /*
     * We have to watch out here for 4 cases:
     *  a) hostname, no port or path
     *  b) hostname, port, no path
     *  c) hostname, path, no port
     *  d) hostname, port and path
     */
    
    /* we only have the hostname, no port or path. */
    if (slash == -1 && colon == -1) {
        host_len = octstr_len(url) - prefix_len;
#ifdef HAVE_LIBSSL
        p->port = (octstr_compare(p->scheme, octstr_imm("https://")) == 0) ? 
            HTTPS_PORT : HTTP_PORT;
#else
        p->port = HTTP_PORT;
#endif /* HAVE_LIBSSL */
    } 
    /* we have a port, but no path. */
    else if (slash == -1) {
        host_len = colon - prefix_len;
        if (octstr_parse_long((long*) &(p->port), url, colon + 1, 10) == -1) {
            error(0, "URL <%s> has malformed port number.",
                  octstr_get_cstr(url));
            http_urlparse_destroy(p);
            return NULL;
        }
    } 
    /* we have a path, but no port. */
    else if (colon == -1 || colon > slash) {
        host_len = slash - prefix_len;
#ifdef HAVE_LIBSSL
        p->port = (octstr_compare(p->scheme, octstr_imm("https://")) == 0) ? 
            HTTPS_PORT : HTTP_PORT;
#else
        p->port = HTTP_PORT;
#endif /* HAVE_LIBSSL */
    } 
    /* we have both, path and port. */
    else if (colon < slash) {
        host_len = colon - prefix_len;
        if (octstr_parse_long((long*) &(p->port), url, colon + 1, 10) == -1) {
            error(0, "URL <%s> has malformed port number.",
                  octstr_get_cstr(url));
            http_urlparse_destroy(p);
            return NULL;
        }
    /* none of the above, so there is something wrong here */
    } else {
        error(0, "Internal error in URL parsing logic.");
        http_urlparse_destroy(p);
        return NULL;
    }

    /* there was an authenticator separator, so try to parse 
     * the username and password credentials */
    if (at != -1) {
        int at2;

        at2 = octstr_search_char(url, '@', prefix_len);
        p->user = octstr_copy(url, prefix_len, at2 - prefix_len);
        p->pass = (at2 != at) ? octstr_copy(url, at2 + 1, at - at2 - 1) : NULL;

        if (auth_sep != -1)
            octstr_set_char(url, auth_sep, ':');
  
        host_len = host_len - at + prefix_len - 1;
        prefix_len = at + 1;
    }

    /* query (CGI vars) */
    query = octstr_search_char(url, '?', (slash == -1) ? prefix_len : slash);
    if (query != -1) {
        p->query = octstr_copy(url, query + 1, octstr_len(url));
        if (colon == -1)
            host_len = slash != -1 ? slash - prefix_len : query - prefix_len;
    }

    /* path */
    p->path = (slash == -1) ? 
        octstr_create("/") : ((query != -1) && (query > slash) ? 
            octstr_copy(url, slash, query - slash) :
            octstr_copy(url, slash, octstr_len(url) - slash)); 

    /* hostname */
    p->host = octstr_copy(url, prefix_len, host_len); 

    /* XXX add fragment too */
   
    /* dump components */
    parse_dump(p);

    return p;
}

/* copy all relevant parsed data to the server info struct */
static void parse2trans(HTTPURLParse *p, HTTPServer *t)
{
    if (p == NULL || t == NULL)
        return;

    if (p->user && !t->username)
        t->username = octstr_duplicate(p->user);
    if (p->pass && !t->password)
        t->password = octstr_duplicate(p->pass);
    if (p->host && !t->host) 
        t->host = octstr_duplicate(p->host);
    if (p->port && !t->port)
        t->port = p->port;
    if (p->path && !t->uri) {
        t->uri = octstr_duplicate(p->path);
        if (p->query) { /* add the query too */
            octstr_append_char(t->uri, '?');
            octstr_append(t->uri, p->query);
        }
    }
    t->ssl = (p->scheme && (octstr_compare(p->scheme, octstr_imm("https://")) == 0) 
              && !t->ssl) ? 1 : 0;
}

static Connection *get_connection(HTTPServer *trans) 
{
    Connection *conn = NULL;
    Octstr *host;
    HTTPURLParse *p;
    int port, ssl;
    
    /* if the parsing has not yet been done, then do it now */
    if (!trans->host && trans->port == 0 && trans->url != NULL) {
        if ((p = parse_url(trans->url)) != NULL) {
            parse2trans(p, trans);
            http_urlparse_destroy(p);
        } else {
            goto error;
        }
    }

    if (proxy_used_for_host(trans->host, trans->url)) {
        host = proxy_hostname;
        port = proxy_port;
        ssl = proxy_ssl;
    } else {
        host = trans->host;
        port = trans->port;
        ssl = trans->ssl;
    }

    conn = conn_pool_get(host, port, ssl, trans->certkeyfile,
                         http_interface);
    if (conn == NULL)
        goto error;

    return conn;

error:
    conn_destroy(conn);
    error(0, "Couldn't send request to <%s>", octstr_get_cstr(trans->url));
    return NULL;
}


/*
 * Build and send the HTTP request. Return 0 for success or -1 for error.
 */
static int send_request(HTTPServer *trans)
{
    char buf[128];    
    Octstr *request = NULL;

    if (trans->method == HTTP_METHOD_POST) {
        /* 
         * Add a Content-Length header.  Override an existing one, if
         * necessary.  We must have an accurate one in order to use the
         * connection for more than a single request.
         */
        http_header_remove_all(trans->request_headers, "Content-Length");
        snprintf(buf, sizeof(buf), "%ld", octstr_len(trans->request_body));
        http_header_add(trans->request_headers, "Content-Length", buf);
    } 
    /* 
     * ok, this has to be an GET or HEAD request method then,
     * if it contains a body, then this is not HTTP conform, so at
     * least warn the user 
     */
    else if (trans->request_body != NULL) {
        warning(0, "HTTP: GET or HEAD method request contains body:");
        octstr_dump(trans->request_body, 0);
    }

    /* 
     * we have to assume all values in trans are already set
     * by parse_url() before calling this.
     */

    if (trans->username != NULL)
        http_add_basic_auth(trans->request_headers, trans->username,
                            trans->password);

    if (proxy_used_for_host(trans->host, trans->url)) {
        proxy_add_authentication(trans->request_headers);
        request = build_request(http_method2name(trans->method), trans->url,
                                trans->host, trans->port, trans->ssl,
                                trans->request_headers, 
                                trans->request_body);
    } else {
        request = build_request(http_method2name(trans->method), trans->uri, 
                                trans->host, trans->port, trans->ssl,
                                trans->request_headers,
                                trans->request_body);
    }
  
    debug("gwlib.http", 0, "HTTP: Sending request:");
    octstr_dump(request, 0);
    if (conn_write(trans->conn, request) == -1)
        goto error;

    octstr_destroy(request);

    return 0;

error:
    conn_destroy(trans->conn);
    trans->conn = NULL;
    octstr_destroy(request);
    error(0, "Couldn't send request to <%s>", octstr_get_cstr(trans->url));
    return -1;
}


/*
 * This thread starts the transaction: it connects to the server and sends
 * the request. It then sends the transaction to the read_response_thread
 * via started_requests_queue.
 */
static void write_request_thread(void *arg)
{
    HTTPServer *trans;
    int rc;

    while (run_status == running) {
        trans = gwlist_consume(pending_requests);
        if (trans == NULL)
            break;

        gw_assert(trans->state == request_not_sent);

        debug("gwlib.http", 0, "Queue contains %ld pending requests.", gwlist_len(pending_requests));

        /* 
         * get the connection to use
         * also calls parse_url() to populate the trans values
         */
        trans->conn = get_connection(trans);

        if (trans->conn == NULL)
            gwlist_produce(trans->caller, trans);
        else if (conn_is_connected(trans->conn) == 0) {
            debug("gwlib.http", 0, "Socket connected at once");

            if ((rc = send_request(trans)) == 0) {
                trans->state = reading_status;
                conn_register(trans->conn, client_fdset, handle_transaction, 
                                trans);
            } else {
                gwlist_produce(trans->caller, trans);
            }

        } else { /* Socket not connected, wait for connection */
            debug("gwlib.http", 0, "Socket connecting");
            trans->state = connecting;
            conn_register(trans->conn, client_fdset, handle_transaction, trans);
        }
    }
}


static void start_client_threads(void)
{
    if (!client_threads_are_running) {
	/* 
	 * To be really certain, we must repeat the test, but use the
	 * lock first. If the test failed, however, we _know_ we've
	 * already initialized. This strategy of double testing avoids
	 * using the lock more than a few times at startup.
	 */
	mutex_lock(client_thread_lock);
	if (!client_threads_are_running) {
	    client_fdset = fdset_create_real(http_client_timeout);
	    if (gwthread_create(write_request_thread, NULL) == -1) {
                error(0, "HTTP: Could not start client write_request thread.");
                fdset_destroy(client_fdset);
                client_threads_are_running = 0;
            } else
                client_threads_are_running = 1;
	}
	mutex_unlock(client_thread_lock);
    }
}

void http_set_interface(const Octstr *our_host)
{
    http_interface = octstr_duplicate(our_host);
}

void http_set_client_timeout(long timeout)
{
    http_client_timeout = timeout;
    if (client_fdset != NULL) {
        /* we are already initialized set timeout in fdset */
        fdset_set_timeout(client_fdset, http_client_timeout);
    }
}

void http_start_request(HTTPCaller *caller, int method, Octstr *url, List *headers,
    	    	    	Octstr *body, int follow, void *id, Octstr *certkeyfile)
{
    HTTPServer *trans;
    int follow_remaining;
    
    if (follow)
    	follow_remaining = HTTP_MAX_FOLLOW;
    else
    	follow_remaining = 0;

    trans = server_create(caller, method, url, headers, body, follow_remaining, 
			  certkeyfile);

    if (id == NULL)
        /* We don't leave this NULL so http_receive_result can use NULL
         * to signal no more requests */
        trans->request_id = http_start_request;
    else
        trans->request_id = id;
        
    gwlist_produce(pending_requests, trans);
    start_client_threads();
}


void *http_receive_result_real(HTTPCaller *caller, int *status, Octstr **final_url,
    	    	    	 List **headers, Octstr **body, int blocking)
{
    HTTPServer *trans;
    void *request_id;

    if (blocking == 0)
        trans = gwlist_extract_first(caller);
    else
        trans = gwlist_consume(caller);
    if (trans == NULL)
    	return NULL;

    request_id = trans->request_id;
    *status = trans->status;
    
    if (trans->status >= 0) {
        *final_url = trans->url;
        *headers = trans->response->headers;
        *body = trans->response->body;

        trans->url = NULL;
        trans->response->headers = NULL;
        trans->response->body = NULL;
    } else {
       *final_url = NULL;
       *headers = NULL;
       *body = NULL;
    }

    server_destroy(trans);
    return request_id;
}


int http_get_real(int method, Octstr *url, List *request_headers, Octstr **final_url,
                  List **reply_headers, Octstr **reply_body)
{
    HTTPCaller *caller;
    int status;
    void *ret;
    
    caller = http_caller_create();
    http_start_request(caller, method, url, request_headers, 
                       NULL, 1, http_get_real, NULL);
    ret = http_receive_result(caller, &status, final_url, 
    	    	    	      reply_headers, reply_body);
    http_caller_destroy(caller);
    if (ret == NULL)
    	return -1;
    return status;
}


static void client_init(void)
{
    pending_requests = gwlist_create();
    gwlist_add_producer(pending_requests);
    client_thread_lock = mutex_create();
}


static void client_shutdown(void)
{
    gwlist_remove_producer(pending_requests);
    gwthread_join_every(write_request_thread);
    client_threads_are_running = 0;
    gwlist_destroy(pending_requests, server_destroy);
    mutex_destroy(client_thread_lock);
    fdset_destroy(client_fdset);
    client_fdset = NULL;
    octstr_destroy(http_interface);
    http_interface = NULL;
}


/***********************************************************************
 * HTTP server interface.
 */


/*
 * Information about a client that has connected to the server we implement.
 */
struct HTTPClient {
    int port;
    Connection *conn;
    Octstr *ip;
    enum {
        reading_request_line,
        reading_request,
        request_is_being_handled,
        sending_reply
    } state;
    int method;  /* HTTP_METHOD_ value */
    Octstr *url;
    int use_version_1_0;
    int persistent_conn;
    unsigned long conn_time; /* store time for timeouting */
    HTTPEntity *request;
};


/*
 * Variables related to server side implementation.
 */
static Mutex *server_thread_lock = NULL;
static volatile sig_atomic_t server_thread_is_running = 0;
static long server_thread_id = -1;
static List *new_server_sockets = NULL;
static List *closed_server_sockets = NULL;
static int keep_servers_open = 0;
/* List with all active HTTPClient's */
static List *active_connections;


static HTTPClient *client_create(int port, Connection *conn, Octstr *ip)
{
    HTTPClient *p;
    
#ifdef HAVE_LIBSSL
    if (conn_get_ssl(conn)) 
        debug("gwlib.http", 0, "HTTP: Creating SSL-enabled HTTPClient for `%s', using cipher '%s'.",
    	      octstr_get_cstr(ip), SSL_get_cipher_version(conn_get_ssl(conn)));
    else
#endif    
        debug("gwlib.http", 0, "HTTP: Creating HTTPClient for `%s'.", octstr_get_cstr(ip));
    p = gw_malloc(sizeof(*p));
    p->port = port;
    p->conn = conn;
    p->ip = ip;
    p->state = reading_request_line;
    p->url = NULL;
    p->use_version_1_0 = 0;
    p->persistent_conn = 1;
    p->conn_time = time(NULL);
    p->request = NULL;
    debug("gwlib.http", 0, "HTTP: Created HTTPClient area %p.", p);
    
    /* add this client to active_connections */
    gwlist_produce(active_connections, p);
    
    return p;
}


static void client_destroy(void *client)
{
    HTTPClient *p;
    long a_len;
    
    if (client == NULL)
        return;

    p = client;
    
    /* drop this client from active_connections list */
    gwlist_lock(active_connections);
    if (gwlist_delete_equal(active_connections, p) != 1)
        panic(0, "HTTP: Race condition in client_destroy(%p) detected!", client);

    /* signal server thread that client slot is free */
    a_len = gwlist_len(active_connections);
    gwlist_unlock(active_connections);

    if (a_len >= HTTP_SERVER_MAX_ACTIVE_CONNECTIONS - 1)
        gwthread_wakeup(server_thread_id);
    
    debug("gwlib.http", 0, "HTTP: Destroying HTTPClient area %p.", p);
    gw_assert_allocated(p, __FILE__, __LINE__, __func__);
    debug("gwlib.http", 0, "HTTP: Destroying HTTPClient for `%s'.",
          octstr_get_cstr(p->ip));
    
    conn_destroy(p->conn);
    octstr_destroy(p->ip);
    octstr_destroy(p->url);
    entity_destroy(p->request);
    gw_free(p);
}


static void client_reset(HTTPClient *p)
{
    debug("gwlib.http", 0, "HTTP: Resetting HTTPClient for `%s'.",
    	  octstr_get_cstr(p->ip));
    p->state = reading_request_line;
    p->conn_time = time(NULL);
    gw_assert(p->request == NULL);
}


/*
 * Checks whether the client connection is meant to be persistent or not.
 * Returns 1 for true, 0 for false.
 * Reference: RFC2616, section 8.1.2.1 Negotiation
 */
static int client_is_persistent(List *headers, int use_version_1_0)
{
    Octstr *h = http_header_find_first(headers, "Connection");

    if (h == NULL) {
        /* assumes persistent for HTTP/1.1, not for HTTP/1.0 */
        return !use_version_1_0;
    } else {
        List *values = octstr_split(h, octstr_imm(","));
        int ret;
        octstr_destroy(h);
        if (gwlist_search(values, octstr_imm("keep-alive"), octstr_item_case_match) != NULL) {
            /* Keep-Alive was requested */
            ret = 1;
        } else if (gwlist_search(values, octstr_imm("close"), octstr_item_case_match) != NULL) {
            /* Close was requested */
            ret = 0;
        } else {
            /* Nothing was requested, so based on HTTP version */
            ret = (!use_version_1_0);
        }
        gwlist_destroy(values, octstr_destroy_item);
        return ret;
    }

    return 1;
}


/*
 * Port specific lists of clients with requests.
 */
struct port {
    int fd;
    int port;
    int ssl;
    List *clients_with_requests;
    Counter *active_consumers;
    FDSet *server_fdset;
};


static Mutex *port_mutex = NULL;
static Dict *port_collection = NULL;


static int port_match(void *client, void *port)
{
    return ((HTTPClient*)client)->port == *((int*)port);
}


static void port_init(void)
{
    port_mutex = mutex_create();
    port_collection = dict_create(1024, NULL);
    /* create list with all active_connections */
    active_connections = gwlist_create();
}

static void port_shutdown(void)
{
    mutex_destroy(port_mutex);
    dict_destroy(port_collection);
    /* destroy active_connections list */
    gwlist_destroy(active_connections, client_destroy);
}


static Octstr *port_key(int port)
{
    return octstr_format("%d", port);
}


static struct port *port_add(int port)
{
    Octstr *key;
    struct port *p;

    key = port_key(port);
    mutex_lock(port_mutex);
    if ((p = dict_get(port_collection, key)) == NULL) {
        p = gw_malloc(sizeof(*p));
        p->clients_with_requests = gwlist_create();
        gwlist_add_producer(p->clients_with_requests);
        p->active_consumers = counter_create();
        p->server_fdset = fdset_create_real(HTTP_SERVER_TIMEOUT);
        dict_put(port_collection, key, p);
    } else {
        warning(0, "HTTP: port_add called for existing port (%d)", port);
    }
    mutex_unlock(port_mutex);
    octstr_destroy(key);

    return p;
}


static void port_remove(int port)
{
    Octstr *key;
    struct port *p;
    List *l;
    HTTPClient *client;

    key = port_key(port);
    mutex_lock(port_mutex);
    p = dict_remove(port_collection, key);
    mutex_unlock(port_mutex);
    octstr_destroy(key);
    
    if (p == NULL) {
        error(0, "HTTP: Could not find port (%d) in port_collection.", port);
        return;
    }

    gwlist_remove_producer(p->clients_with_requests);
    while (counter_value(p->active_consumers) > 0)
       gwthread_sleep(0.1);    /* Reasonable use of busy waiting. */

    gwlist_destroy(p->clients_with_requests, client_destroy);
    counter_destroy(p->active_consumers);

    /*
     * In order to avoid race conditions with FDSet thread, we
     * destroy Clients for this port in two steps:
     * 1) unregister from fdset with gwlist_lock held, so client_destroy
     *    cannot destroy our client that we currently use
     * 2) without gwlist_lock held destroy every client, we can do this
     *    because we only one thread that can use this client struct
     */
    gwlist_lock(active_connections);
    l = gwlist_search_all(active_connections, &port, port_match);
    while(l != NULL && (client = gwlist_extract_first(l)) != NULL)
        conn_unregister(client->conn);
    gwlist_unlock(active_connections);
    gwlist_destroy(l, NULL);
    while((client = gwlist_search(active_connections, &port, port_match)) != NULL)
        client_destroy(client);

    /* now destroy fdset */
    fdset_destroy(p->server_fdset);
    gw_free(p);
}


static void port_put_request(HTTPClient *client)
{
    Octstr *key;
    struct port *p;

    mutex_lock(port_mutex);
    key = port_key(client->port);
    p = dict_get(port_collection, key);
    octstr_destroy(key);
    if (p == NULL) {
        /* client was too slow and we closed port already */
        mutex_unlock(port_mutex);
        client_destroy(client);
        return;
    }
    gwlist_produce(p->clients_with_requests, client);
    mutex_unlock(port_mutex);
}


static HTTPClient *port_get_request(int port)
{
    Octstr *key;
    struct port *p;
    HTTPClient *client;
    
    mutex_lock(port_mutex);
    key = port_key(port);
    p = dict_get(port_collection, key);
    octstr_destroy(key);

    if (p == NULL) {
       client = NULL;
       mutex_unlock(port_mutex);
    } else {
       counter_increase(p->active_consumers);
       mutex_unlock(port_mutex);   /* Placement of this unlock is tricky. */
       client = gwlist_consume(p->clients_with_requests);
       counter_decrease(p->active_consumers);
    }
    return client;
}


static void port_set_timeout(int port, long timeout)
{
    Octstr *key;
    struct port *p;

    mutex_lock(port_mutex);
    key = port_key(port);
    p = dict_get(port_collection, key);
    octstr_destroy(key);

    if (p != NULL)
        fdset_set_timeout(p->server_fdset, timeout);

    mutex_unlock(port_mutex);
}


static FDSet *port_get_fdset(int port)
{
    Octstr *key;
    struct port *p;
    FDSet *ret = NULL;

    mutex_lock(port_mutex);
    key = port_key(port);
    p = dict_get(port_collection, key);
    octstr_destroy(key);

    if (p != NULL)
        ret = p->server_fdset;

    mutex_unlock(port_mutex);

    return ret;
}


static int parse_request_line(int *method, Octstr **url,
                              int *use_version_1_0, Octstr *line)
{
    List *words;
    Octstr *version;
    Octstr *method_str;
    int ret;

    words = octstr_split_words(line);
    if (gwlist_len(words) != 3) {
        gwlist_destroy(words, octstr_destroy_item);
        return -1;
    }

    method_str = gwlist_get(words, 0);
    *url = gwlist_get(words, 1);
    version = gwlist_get(words, 2);
    gwlist_destroy(words, NULL);

    if (octstr_compare(method_str, octstr_imm("GET")) == 0)
        *method = HTTP_METHOD_GET;
    else if (octstr_compare(method_str, octstr_imm("POST")) == 0)
        *method = HTTP_METHOD_POST;
    else if (octstr_compare(method_str, octstr_imm("HEAD")) == 0)
        *method = HTTP_METHOD_HEAD;
    else
        goto error;

    ret = parse_http_version(version);
    if (ret < 0)
        goto error;
    *use_version_1_0 = !ret;

    octstr_destroy(method_str);
    octstr_destroy(version);
    return 0;

error:
    octstr_destroy(method_str);
    octstr_destroy(*url);
    octstr_destroy(version);
    *url = NULL;
    return -1;
}


static void receive_request(Connection *conn, void *data)
{
    HTTPClient *client;
    Octstr *line;
    int ret;

    if (run_status != running) {
        conn_unregister(conn);
        return;
    }

    client = data;
    
    for (;;) {
        switch (client->state) {
            case reading_request_line:
                line = conn_read_line(conn);
                if (line == NULL) {
                    if (conn_eof(conn) || conn_error(conn))
                        goto error;
                    return;
                }
                ret = parse_request_line(&client->method, &client->url,
                                         &client->use_version_1_0, line);
                octstr_destroy(line);
                /* client sent bad request? */
                if (ret == -1) {
                    /*
                     * mark client as not persistent in order to destroy connection
                     * afterwards
                     */
                    client->persistent_conn = 0;
                    /* unregister connection, http_send_reply handle this */
                    conn_unregister(conn);
                    http_send_reply(client, HTTP_BAD_REQUEST, NULL, NULL);
                    return;
                }
                /*
                 * RFC2616 (4.3) says we should read a message body if there
                 * is one, even on GET requests.
                 */
                client->request = entity_create(expect_body_if_indicated);
                client->state = reading_request;
                break;
                
            case reading_request:
                ret = entity_read(client->request, conn);
                if (ret < 0)
                    goto error;
                if (ret == 0) {
                    client->state = request_is_being_handled;
                    conn_unregister(conn);
                    port_put_request(client);
                }
                return;
                
            case sending_reply:
                /* Implicit conn_unregister() and _destroy */
                if (conn_error(conn))
                    goto error;
                if (conn_outbuf_len(conn) > 0)
                    return;
                /* Reply has been sent completely */
                if (!client->persistent_conn) {
                    /*
                     * in order to avoid race conditions while conn will be destroyed but
                     * conn is still in use, we call conn_unregister explicit here because
                     * conn_unregister call uses locks
                     */
                    conn_unregister(conn);
                    client_destroy(client);
                    return;
                }
                /* Start reading another request */
                client_reset(client);
                break;
                
            default:
                panic(0, "Internal error: HTTPClient state is wrong.");
        }
    }
    
error:
    /*
     * in order to avoid race conditions while conn will be destroyed but
     * conn is still in use, we call conn_unregister explicit here because
     * conn_unregister call uses locks
     */
    conn_unregister(conn);
    client_destroy(client);
}


static void server_thread(void *dummy)
{
    struct pollfd *tab = NULL;
    struct port **ports = NULL;
    int tab_size = 0, n, i, fd, ret, max_clients_reached;
    struct sockaddr_in addr;
    socklen_t addrlen;
    HTTPClient *client;
    Connection *conn;
    int *portno;

    n = max_clients_reached = 0;
    while (run_status == running && keep_servers_open) {
        while (n == 0 || gwlist_len(new_server_sockets) > 0) {
            struct port *p = gwlist_consume(new_server_sockets);
            if (p == NULL) {
                debug("gwlib.http", 0, "HTTP: No new servers. Quitting.");
                break;
            } else {
                debug ("gwlib.http", 0, "HTTP: Including port %d, fd %d for polling in server thread", p->port, p->fd);
            }
            if (tab_size <= n) {
                tab_size++;
                tab = gw_realloc(tab, tab_size * sizeof(*tab));
                ports = gw_realloc(ports, tab_size * sizeof(*ports));
                if (tab == NULL || ports == NULL) {
                    tab_size--;
                    port_remove(p->port);
                    continue;
                }
            }
            tab[n].fd = p->fd;
            tab[n].events = POLLIN;
            ports[n] = p;
            n++;
        }

        if (max_clients_reached && gwlist_len(active_connections) >= HTTP_SERVER_MAX_ACTIVE_CONNECTIONS) {
            /* TODO start cleanup of stale connections */
            /* wait for slots to become free */
            gwthread_sleep(1.0);
        } else if (!max_clients_reached && (ret = gwthread_poll(tab, n, -1.0)) == -1) {
            if (errno != EINTR) /* a signal was caught during poll() function */
                warning(errno, "HTTP: gwthread_poll failed.");
            continue;
        }

        for (i = 0; i < n; ++i) {
            if (tab[i].revents & POLLIN) {
                /* check our limit */
                if (gwlist_len(active_connections) >= HTTP_SERVER_MAX_ACTIVE_CONNECTIONS) {
                    max_clients_reached = 1;
                    break;
                } else {
                    max_clients_reached = 0;
                }

                addrlen = sizeof(addr);
                fd = accept(tab[i].fd, (struct sockaddr *) &addr, &addrlen);
                if (fd == -1) {
                    error(errno, "HTTP: Error accepting a client.");
                } else {
                    Octstr *client_ip = host_ip(addr);
                    /*
                     * Be aware that conn_wrap_fd() will return NULL if SSL 
                     * handshake has failed, so we only client_create() if
                     * there is an conn.
                     */             
                    if ((conn = conn_wrap_fd(fd, ports[i]->ssl))) {
                        client = client_create(ports[i]->port, conn, client_ip);
                        conn_register(conn, ports[i]->server_fdset, receive_request, client);
                    } else {
                        error(0, "HTTP: unsuccessful SSL handshake for client `%s'",
                        octstr_get_cstr(client_ip));
                        octstr_destroy(client_ip);
                    }
                }
            }
        }

        while ((portno = gwlist_extract_first(closed_server_sockets)) != NULL) {
            for (i = 0; i < n; ++i) {
                if (ports[i]->port == *portno) {
                    (void) close(tab[i].fd);
                    tab[i].fd = -1;
                    tab[i].events = 0;
                    port_remove(ports[i]->port);
                    ports[i] = NULL;
                    n--;
                    
                    /* now put the last entry on this place */
                    tab[i].fd = tab[n].fd;
                    tab[i].events = tab[n].events;
                    tab[n].fd = -1;
                    tab[n].events = 0;
                    ports[i] = ports[n];
                }
            }
            gw_free(portno);
        }
    }
    
    /* make sure we close all ports */
    for (i = 0; i < n; ++i) {
        (void) close(tab[i].fd);
        port_remove(ports[i]->port);
    }
    gw_free(tab);
    gw_free(ports);

    server_thread_id = -1;
}


static void start_server_thread(void)
{
    if (!server_thread_is_running) {
        /* 
         * To be really certain, we must repeat the test, but use the
         * lock first. If the test failed, however, we _know_ we've
         * already initialized. This strategy of double testing avoids
         * using the lock more than a few times at startup.
         */
        mutex_lock(server_thread_lock);
        if (!server_thread_is_running) {
            server_thread_id = gwthread_create(server_thread, NULL);
            server_thread_is_running = 1;
        }
        mutex_unlock(server_thread_lock);
    }
}


void http_set_server_timeout(int port, long timeout)
{
    port_set_timeout(port, timeout);
}


int http_open_port_if(int port, int ssl, Octstr *interface)
{
    struct port *p;

    if (ssl) 
        info(0, "HTTP: Opening SSL server at port %d.", port);
    else 
        info(0, "HTTP: Opening server at port %d.", port);
    p = port_add(port);
    p->port = port;
    p->ssl = ssl;
    p->fd = make_server_socket(port, (interface ? octstr_get_cstr(interface) : NULL));
    if (p->fd == -1) {
        port_remove(port);
    	return -1;
    }
    
    gwlist_produce(new_server_sockets, p);
    keep_servers_open = 1;
    start_server_thread();
    gwthread_wakeup(server_thread_id);
    
    return 0;
}


int http_open_port(int port, int ssl)
{
    return http_open_port_if(port, ssl, NULL);
}


void http_close_port(int port)
{
    int *p;
    
    p = gw_malloc(sizeof(*p));
    *p = port;
    gwlist_produce(closed_server_sockets, p);
    gwthread_wakeup(server_thread_id);
}


void http_close_all_ports(void)
{
    if (server_thread_id != -1) {
        keep_servers_open = 0;
        gwthread_wakeup(server_thread_id);
        gwthread_join_every(server_thread);
        server_thread_is_running = 0;
    }
}


/*
 * Parse CGI variables from the path given in a GET. Return a list
 * of HTTPCGIvar pointers. Modify the url so that the variables are
 * removed.
 */
static List *parse_cgivars(Octstr *url)
{
    HTTPCGIVar *v;
    List *list;
    int query, et, equals;
    Octstr *arg, *args;

    query = octstr_search_char(url, '?', 0);
    if (query == -1)
        return gwlist_create();

    args = octstr_copy(url, query + 1, octstr_len(url));
    octstr_truncate(url, query);

    list = gwlist_create();

    while (octstr_len(args) > 0) {
        et = octstr_search_char(args, '&', 0);
        if (et == -1)
            et = octstr_len(args);
        arg = octstr_copy(args, 0, et);
        octstr_delete(args, 0, et + 1);

        equals = octstr_search_char(arg, '=', 0);
        if (equals == -1)
            equals = octstr_len(arg);

        v = gw_malloc(sizeof(HTTPCGIVar));
        v->name = octstr_copy(arg, 0, equals);
        v->value = octstr_copy(arg, equals + 1, octstr_len(arg));
        octstr_url_decode(v->name);
        octstr_url_decode(v->value);

        octstr_destroy(arg);

        gwlist_append(list, v);
    }
    octstr_destroy(args);

    return list;
}


HTTPClient *http_accept_request(int port, Octstr **client_ip, Octstr **url, 
    	    	    	    	List **headers, Octstr **body, 
                                List **cgivars)
{
    HTTPClient *client;
    
    do {
        client = port_get_request(port);
        if (client == NULL) {
            debug("gwlib.http", 0, "HTTP: No clients with requests, quitting.");
            return NULL;
        }
        /* check whether client connection still ok */
        conn_wait(client->conn, 0);
        if (conn_error(client->conn) || conn_eof(client->conn)) {
            client_destroy(client);
            client = NULL;
        }
    } while(client == NULL);
    
    *client_ip = octstr_duplicate(client->ip);
    *url = client->url;
    *headers = client->request->headers;
    *body = client->request->body;
    *cgivars = parse_cgivars(client->url);
    
    if (client->method != HTTP_METHOD_POST) {
        octstr_destroy(*body);
        *body = NULL;
    }
    
    client->persistent_conn = client_is_persistent(client->request->headers,
                                                   client->use_version_1_0);
    
    client->url = NULL;
    client->request->headers = NULL;
    client->request->body = NULL;
    entity_destroy(client->request);
    client->request = NULL;
    
    return client;
}

/*
 * The http_send_reply(...) uses this function to determinate the
 * reason pahrase for a status code.
 */
static const char *http_reason_phrase(int status)
{
	switch (status) {
	case HTTP_OK:
		return "OK";						/* 200 */
	case HTTP_CREATED:                   
		return "Created";					/* 201 */
	case HTTP_ACCEPTED:
		return "Accepted";					/* 202 */
	case HTTP_NO_CONTENT:
		return "No Content";				/* 204 */
	case HTTP_RESET_CONTENT: 
		return "Reset Content";				/* 205 */
	case HTTP_MOVED_PERMANENTLY:
		return "Moved Permanently"; 		/* 301 */
	case HTTP_FOUND:
		return "Found";						/* 302 */
	case HTTP_SEE_OTHER:
		return "See Other";					/* 303 */
	case HTTP_NOT_MODIFIED:
		return "Not Modified";				/* 304 */
	case HTTP_TEMPORARY_REDIRECT:
		return "Temporary Redirect";		/* 307 */
	case HTTP_BAD_REQUEST:
		return "Bad Request";				/* 400 */
	case HTTP_UNAUTHORIZED:
		return "Unauthorized";				/* 401 */
	case HTTP_FORBIDDEN:
		return "Forbidden";					/* 403 */
	case HTTP_NOT_FOUND:           	
		return "Not Found";					/* 404 */
	case HTTP_BAD_METHOD:
		return "Method Not Allowed";		/* 405 */
	case HTTP_NOT_ACCEPTABLE:
		return "Not Acceptable";			/* 406 */
	case HTTP_REQUEST_ENTITY_TOO_LARGE:
		return "Request Entity Too Large";	/* 413 */
	case HTTP_UNSUPPORTED_MEDIA_TYPE:
		return "Unsupported Media Type";	/* 415 */
	case HTTP_INTERNAL_SERVER_ERROR:
		return "Internal Server Error";		/* 500 */
	case HTTP_NOT_IMPLEMENTED:
		return "Not Implemented";			/* 501 */
	case HTTP_BAD_GATEWAY:
		return "Bad Gateway";				/* 502 */
	}
	return "Foo";
}


void http_send_reply(HTTPClient *client, int status, List *headers, 
    	    	     Octstr *body)
{
    Octstr *response;
    Octstr *date;
    long i;
    int ret;

    if (client->use_version_1_0)
    	response = octstr_format("HTTP/1.0 %d %s\r\n", status, http_reason_phrase(status));
    else
    	response = octstr_format("HTTP/1.1 %d %s\r\n", status, http_reason_phrase(status));

    /* identify ourselfs */
    octstr_format_append(response, "Server: " GW_NAME "/%s\r\n", GW_VERSION);
    
    /* let's inform the client of our time */
    date = date_format_http(time(NULL));
    octstr_format_append(response, "Date: %s\r\n", octstr_get_cstr(date));
    octstr_destroy(date);
    
    octstr_format_append(response, "Content-Length: %ld\r\n", octstr_len(body));

    /* Indicate if we're keeping the connection or closing. */
    if (client->persistent_conn)
        octstr_format_append(response, "Connection: Keep-Alive\r\n");
    else
        octstr_format_append(response, "Connection: Close\r\n");

    for (i = 0; i < gwlist_len(headers); ++i)
    	octstr_format_append(response, "%S\r\n", gwlist_get(headers, i));
    octstr_format_append(response, "\r\n");
    
    if (body != NULL && client->method != HTTP_METHOD_HEAD)
    	octstr_append(response, body);
	
    ret = conn_write(client->conn, response);
    octstr_destroy(response);

    /* obey return code of conn_write() */
    /* sending response was successful */
    if (ret == 0) { 
        /* HTTP/1.0 or 1.1, hence keep-alive or keep-alive */
        if (!client->persistent_conn) {
            client_destroy(client);     
        } else {
            /* XXX mark this HTTPClient in the keep-alive cleaner thread */
            client_reset(client);
            conn_register(client->conn, port_get_fdset(client->port), receive_request, client);
        }
    }
    /* queued for sending, we don't want to block */
    else if (ret == 1) {    
        client->state = sending_reply;
        conn_register(client->conn, port_get_fdset(client->port), receive_request, client);
    }
    /* error while sending response */
    else {     
        client_destroy(client);
    }
}


void http_close_client(HTTPClient *client)
{
    client_destroy(client);
}

int http_method(HTTPClient *client)
{
    return client->method;
}

Octstr *http_request_url(HTTPClient *client)
{
    return client->url;
}

static void server_init(void)
{
    new_server_sockets = gwlist_create();
    gwlist_add_producer(new_server_sockets);
    closed_server_sockets = gwlist_create();
    server_thread_lock = mutex_create();
}


static void destroy_struct_server(void *p)
{
    struct port *pp;
    
    pp = p;
    (void) close(pp->fd);
    port_remove(pp->port);
}


static void destroy_int_pointer(void *p)
{
    (void) close(*(int *) p);
    gw_free(p);
}


static void server_shutdown(void)
{
    gwlist_remove_producer(new_server_sockets);
    if (server_thread_id != -1) {
        gwthread_wakeup(server_thread_id);
        gwthread_join_every(server_thread);
        server_thread_is_running = 0;
    }
    mutex_destroy(server_thread_lock);
    gwlist_destroy(new_server_sockets, destroy_struct_server);
    gwlist_destroy(closed_server_sockets, destroy_int_pointer);
}


/***********************************************************************
 * CGI variable manipulation.
 */


void http_destroy_cgiargs(List *args)
{
    HTTPCGIVar *v;

    gwlib_assert_init();

    if (args == NULL)
        return ;

    while ((v = gwlist_extract_first(args)) != NULL) {
        octstr_destroy(v->name);
        octstr_destroy(v->value);
        gw_free(v);
    }
    gwlist_destroy(args, NULL);
}


Octstr *http_cgi_variable(List *list, char *name)
{
    int i;
    HTTPCGIVar *v;

    gwlib_assert_init();
    gw_assert(list != NULL);
    gw_assert(name != NULL);

    for (i = 0; i < gwlist_len(list); ++i) {
        v = gwlist_get(list, i);
        if (octstr_str_compare(v->name, name) == 0)
            return v->value;
    }
    return NULL;
}


/***********************************************************************
 * Header manipulation.
 */


static int header_is_called(Octstr *header, char *name)
{
    long colon;

    colon = octstr_search_char(header, ':', 0);
    if (colon == -1)
        return 0;
    if ((long) strlen(name) != colon)
        return 0;
    return strncasecmp(octstr_get_cstr(header), name, colon) == 0;
}


List *http_create_empty_headers(void)
{
    gwlib_assert_init();
    return gwlist_create();
}


void http_destroy_headers(List *headers)
{
    gwlib_assert_init();
    gwlist_destroy(headers, octstr_destroy_item);
}


void http_header_add(List *headers, char *name, char *contents)
{
    gwlib_assert_init();
    gw_assert(headers != NULL);
    gw_assert(name != NULL);
    gw_assert(contents != NULL);

    gwlist_append(headers, octstr_format("%s: %s", name, contents));
}


/*
 * Given an headers list and a position, returns its header name and value,
 * or (X-Unknown, header) if it doesn't exist or if it's malformed - missing 
 * ":" for example
 */
void http_header_get(List *headers, long i, Octstr **name, Octstr **value)
{
    Octstr *os;
    long colon;

    gwlib_assert_init();
    gw_assert(i >= 0);
    gw_assert(name != NULL);
    gw_assert(value != NULL);

    os = gwlist_get(headers, i);
    if (os == NULL)
        colon = -1;
    else
        colon = octstr_search_char(os, ':', 0);
    if (colon == -1) {
        error(0, "HTTP: Header does not contain a colon. BAD.");
        *name = octstr_create("X-Unknown");
        *value = octstr_duplicate(os);
    } else {
        *name = octstr_copy(os, 0, colon);
        *value = octstr_copy(os, colon + 1, octstr_len(os) - colon - 1);
        octstr_strip_blanks(*value);
    }
}

/*
 * Given an headers list and a name, returns its value or NULL if it 
 * doesn't exist
 */
Octstr *http_header_value(List *headers, Octstr *name)
{
    Octstr *value;
    long i;
    Octstr *os;
    long colon;
    Octstr *current_name;
    
    gwlib_assert_init();
    gw_assert(name);
    
    value = NULL;
    i = 0;
    while (i < gwlist_len(headers)) {
        os = gwlist_get(headers, i);
        if (os == NULL)
            colon = -1;
        else
            colon = octstr_search_char(os, ':', 0);
        if (colon == -1) {
            return NULL;      
        } else {
            current_name = octstr_copy(os, 0, colon);
        }
        if (octstr_case_compare(current_name, name) == 0) {
            value = octstr_copy(os, colon + 1, octstr_len(os) - colon - 1);
            octstr_strip_blanks(value);
            octstr_destroy(current_name);
            return value;
        }
        octstr_destroy(current_name);
        ++i;
    }
    
    return NULL;
}

List *http_header_duplicate(List *headers)
{
    List *new;
    long i, len;

    gwlib_assert_init();

    if (headers == NULL)
        return NULL;

    new = http_create_empty_headers();
    len = gwlist_len(headers);
    for (i = 0; i < len; ++i)
        gwlist_append(new, octstr_duplicate(gwlist_get(headers, i)));
    return new;
}


#define MAX_HEADER_LENGTH 256
/*
 * Aggregate header in one (or more) lines with several parameters separated
 * by commas, instead of one header per parameter
 */
void http_header_pack(List *headers)
{
    Octstr *name, *value;
    Octstr *name2, *value2;
    long i, j;

    gwlib_assert_init();
    gw_assert(headers != NULL);

    /*
     * For each header, search forward headers for similar ones and if possible, 
     * add it to current header and delete it
     */
    for(i = 0; i < gwlist_len(headers); i++) {
        http_header_get(headers, i, &name, &value);
	/* debug("http_header_pack", 0, "HTTP_HEADER_PACK: Processing header %d. [%s: %s]", 
	       i, octstr_get_cstr(name), octstr_get_cstr(value)); */

        for(j=i+1; j < gwlist_len(headers); j++) {
            http_header_get(headers, j, &name2, &value2);

            if(octstr_case_compare(name, name2) == 0) {
                if(octstr_len(value) + 2 + octstr_len(value2) > MAX_HEADER_LENGTH) {
		    octstr_destroy(name2);
		    octstr_destroy(value2);
                    break;
                } else {
		    Octstr *header;

		    /* Delete old header */
		    header = gwlist_get(headers, i);
		    octstr_destroy(header);
                    gwlist_delete(headers, i, 1);

		    /* Adds comma and new value to old header value */
                    octstr_append(value, octstr_imm(", "));
                    octstr_append(value, value2);
		    /* Creates a new header */
		    header = octstr_create("");
                    octstr_append(header, name);
                    octstr_append(header, octstr_imm(": "));
                    octstr_append(header, value);
                    gwlist_insert(headers, i, header);

		    /* Delete this header */
		    header = gwlist_get(headers, j);
		    octstr_destroy(header);
                    gwlist_delete(headers, j, 1);
                    j--;
                }
            }
	    octstr_destroy(name2);
	    octstr_destroy(value2);
        }
	octstr_destroy(name);
	octstr_destroy(value);
    }
}


void http_append_headers(List *to, List *from)
{
    Octstr *header;
    long i;

    gwlib_assert_init();
    gw_assert(to != NULL);
    gw_assert(from != NULL);

    for (i = 0; i < gwlist_len(from); ++i) {
        header = gwlist_get(from, i);
        gwlist_append(to, octstr_duplicate(header));
    }
}


void http_header_combine(List *old_headers, List *new_headers)
{
    long i;
    Octstr *name;
    Octstr *value;

    /*
     * Avoid doing this scan if old_headers is empty anyway.
     */
    if (gwlist_len(old_headers) > 0) {
        for (i = 0; i < gwlist_len(new_headers); i++) {
  	    http_header_get(new_headers, i, &name, &value);
	    http_header_remove_all(old_headers, octstr_get_cstr(name));
            octstr_destroy(name);
            octstr_destroy(value);
        }
    }

    http_append_headers(old_headers, new_headers);
}


Octstr *http_header_find_first_real(List *headers, char *name, const char *file, long line,
                                    const char *func)
{
    long i, name_len;
    Octstr *h, *value;

    gwlib_assert_init();
    gw_assert(headers != NULL);
    gw_assert(name != NULL);

    name_len = strlen(name);

    for (i = 0; i < gwlist_len(headers); ++i) {
        h = gwlist_get(headers, i);
        if (header_is_called(h, name)) {
            value = octstr_copy_real(h, name_len + 1, octstr_len(h),
                                     file, line, func);
	    octstr_strip_blanks(value);
	    return value;
	}
    }
    return NULL;
}


List *http_header_find_all(List *headers, char *name)
{
    List *list;
    long i;
    Octstr *h;

    gwlib_assert_init();
    gw_assert(headers != NULL);
    gw_assert(name != NULL);

    list = gwlist_create();
    for (i = 0; i < gwlist_len(headers); ++i) {
        h = gwlist_get(headers, i);
        if (header_is_called(h, name))
            gwlist_append(list, octstr_duplicate(h));
    }
    return list;
}


long http_header_remove_all(List *headers, char *name)
{
    long i;
    Octstr *h;
    long count;

    gwlib_assert_init();
    gw_assert(headers != NULL);
    gw_assert(name != NULL);

    i = 0;
    count = 0;
    while (i < gwlist_len(headers)) {
	h = gwlist_get(headers, i);
	if (header_is_called(h, name)) {
	    gwlist_delete(headers, i, 1);
	    octstr_destroy(h);
	    count++;
	} else
	    i++;
    }

    return count;
}


void http_remove_hop_headers(List *headers)
{
    Octstr *h;
    List *connection_headers;

    gwlib_assert_init();
    gw_assert(headers != NULL);

    /*
     * The hop-by-hop headers are a standard list, plus those named
     * in the Connection header(s).
     */

    connection_headers = http_header_find_all(headers, "Connection");
    while ((h = gwlist_consume(connection_headers))) {
	List *hop_headers;
	Octstr *e;

	octstr_delete(h, 0, strlen("Connection:"));
	hop_headers = http_header_split_value(h);
	octstr_destroy(h);

	while ((e = gwlist_consume(hop_headers))) {
	    http_header_remove_all(headers, octstr_get_cstr(e));
	    octstr_destroy(e);
	}

	gwlist_destroy(hop_headers, NULL);
    }
    gwlist_destroy(connection_headers, NULL);
   
    http_header_remove_all(headers, "Connection");
    http_header_remove_all(headers, "Keep-Alive");
    http_header_remove_all(headers, "Proxy-Authenticate");
    http_header_remove_all(headers, "Proxy-Authorization");
    http_header_remove_all(headers, "TE");
    http_header_remove_all(headers, "Trailers");
    http_header_remove_all(headers, "Transfer-Encoding");
    http_header_remove_all(headers, "Upgrade");
}


void http_header_mark_transformation(List *headers,
    	    	    	    	     Octstr *new_body, Octstr *new_type)
{
    Octstr *new_length = NULL;

    /* Remove all headers that no longer apply to the new body. */
    http_header_remove_all(headers, "Content-Length");
    http_header_remove_all(headers, "Content-MD5");
    http_header_remove_all(headers, "Content-Type");

    /* Add headers that we need to describe the new body. */
    new_length = octstr_format("%ld", octstr_len(new_body));
    http_header_add(headers, "Content-Length", octstr_get_cstr(new_length));
    if(octstr_len(new_type))
	http_header_add(headers, "Content-Type", octstr_get_cstr(new_type));

    /* Perhaps we should add Warning: 214 "Transformation applied" too? */

    octstr_destroy(new_length);
}


void http_header_get_content_type(List *headers, Octstr **type,
                                  Octstr **charset)
{
    Octstr *h;
    long semicolon, equals, len;

    gwlib_assert_init();
    gw_assert(headers != NULL);
    gw_assert(type != NULL);
    gw_assert(charset != NULL);

    h = http_header_find_first(headers, "Content-Type");
    if (h == NULL) {
        *type = octstr_create("application/octet-stream");
        *charset = octstr_create("");
    } else {
        octstr_strip_blanks(h);
        semicolon = octstr_search_char(h, ';', 0);
        if (semicolon == -1) {
            *type = h;
            *charset = octstr_create("");
        } else {
            *charset = octstr_duplicate(h);
            octstr_delete(*charset, 0, semicolon + 1);
            octstr_strip_blanks(*charset);
            equals = octstr_search_char(*charset, '=', 0);
            if (equals == -1)
                octstr_truncate(*charset, 0);
            else {
                octstr_delete(*charset, 0, equals + 1);
                if (octstr_get_char(*charset, 0) == '"')
                    octstr_delete(*charset, 0, 1);
                len = octstr_len(*charset);
                if (octstr_get_char(*charset, len - 1) == '"')
                    octstr_truncate(*charset, len - 1);
            }

            octstr_truncate(h, semicolon);
            octstr_strip_blanks(h);
            *type = h;
        }

        /* 
         * According to HTTP/1.1 (RFC 2616, section 3.7.1) we have to ensure
         * to return charset 'iso-8859-1' in case of no given encoding and
         * content-type is a 'text' subtype. 
         */
        if (octstr_len(*charset) == 0 && 
            octstr_ncompare(*type, octstr_imm("text"), 4) == 0)
            octstr_append_cstr(*charset, "ISO-8859-1");
    }
}


static void http_header_add_element(List *list, Octstr *value,
				    long start, long end)
{
    Octstr *element;

    element = octstr_copy(value, start, end - start);
    octstr_strip_blanks(element);
    if (octstr_len(element) == 0)
	octstr_destroy(element);
    else
    	gwlist_append(list, element);
}


long http_header_quoted_string_len(Octstr *header, long start)
{
    long len;
    long pos;
    int c;

    if (octstr_get_char(header, start) != '"')
	return -1;

    len = octstr_len(header);
    for (pos = start + 1; pos < len; pos++) {
	c = octstr_get_char(header, pos);
	if (c == '\\')    /* quoted-pair */
	    pos++;
	else if (c == '"')
	    return pos - start + 1;
    }

    warning(0, "Header contains unterminated quoted-string:");
    warning(0, "%s", octstr_get_cstr(header));
    return len - start;
}


List *http_header_split_value(Octstr *value)
{
    long start;  /* start of current element */
    long pos;
    long len;
    List *result;
    int c;

    /*
     * According to RFC2616 section 4.2, a field-value is either *TEXT
     * (the caller is responsible for not feeding us one of those) or
     * combinations of token, separators, and quoted-string.  We're
     * looking for commas which are separators, and have to skip
     * commas in quoted-strings.
     */
 
    result = gwlist_create();
    len = octstr_len(value);
    start = 0;
    for (pos = 0; pos < len; pos++) {
	c = octstr_get_char(value, pos);
	if (c == ',') {
	    http_header_add_element(result, value, start, pos);
	    start = pos + 1;
	} else if (c == '"') {
            pos += http_header_quoted_string_len(value, pos);
	    pos--; /* compensate for the loop's pos++ */
        }
    }
    http_header_add_element(result, value, start, len);
    return result;
}


List *http_header_split_auth_value(Octstr *value)
{
    List *result;
    Octstr *auth_scheme;
    Octstr *element;
    long i;

    /*
     * According to RFC2617, both "challenge" and "credentials"
     * consist of an auth-scheme followed by a list of auth-param.
     * Since we have to parse a list of challenges or credentials,
     * we have to look for auth-scheme to signal the start of
     * a new element.  (We can't just split on commas because
     * they are also used to separate the auth-params.)
     *
     * An auth-scheme is a single token, while an auth-param is
     * always a key=value pair.  So we can recognize an auth-scheme
     * as a token that is not followed by a '=' sign.
     *
     * Simple approach: First split at all commas, then recombine
     * the elements that belong to the same challenge or credential.
     * This is somewhat expensive but saves programmer thinking time.
     *
     * Richard Braakman
     */
 
    result = http_header_split_value(value);
    if (gwlist_len(result) == 0)
        return result;

    auth_scheme = gwlist_get(result, 0);
    i = 1;
    while (i < gwlist_len(result)) {
        int c;
        long pos;

        element = gwlist_get(result, i);

        /*
         * If the element starts with: token '='
         * then it's just an auth_param; append it to the current
         * auth_scheme.  If it starts with: token token '='
         * then it's the start of a new auth scheme.
         *
         * To make the scan easier, we consider anything other
         * than whitespace or '=' to be part of a token.
         */

        /* Skip first token */
        for (pos = 0; pos < octstr_len(element); pos++) {
            c = octstr_get_char(element, pos);
            if (isspace(c) || c == '=')
                break;
        }

        /* Skip whitespace, if any */
        while (isspace(octstr_get_char(element, pos)))
            pos++;

        if (octstr_get_char(element, pos) == '=') {
            octstr_append_char(auth_scheme, ';');
            octstr_append(auth_scheme, element);
            gwlist_delete(result, i, 1);
            octstr_destroy(element);
        } else {
            char semicolon = ';';
            octstr_insert_data(element, pos, &semicolon, 1);
            auth_scheme = element;
            i++;
        }
    }

    return result;
}


void http_header_dump(List *headers)
{
    long i;

    gwlib_assert_init();

    debug("gwlib.http", 0, "Dumping HTTP headers:");
    for (i = 0; headers != NULL && i < gwlist_len(headers); ++i)
        octstr_dump(gwlist_get(headers, i), 1);
    debug("gwlib.http", 0, "End of dump.");
}


void http_cgivar_dump(List *cgiargs)
{
    HTTPCGIVar *v;
    long i, len;

    gwlib_assert_init();

    len = gwlist_len(cgiargs);

    debug("gwlib.http", 0, "Dumping %ld cgi variables:", len);
    for (i = 0; i < len; i++) {
        v = gwlist_get(cgiargs, i);
        octstr_dump(v->name, 0);
        octstr_dump(v->value, 0);
    }
    debug("gwlib.http", 0, "End of dump.");
}


void http_cgivar_dump_into(List *cgiargs, Octstr *os)
{
    HTTPCGIVar *v;
    long i;

    if (os == NULL)
        return;

    gwlib_assert_init();

    for (i = 0; i < gwlist_len(cgiargs); i++) {
        v = gwlist_get(cgiargs, i);
        octstr_format_append(os, "&%E=%E", v->name, v->value);
    }
}


static int http_something_accepted(List *headers, char *header_name,
                                   char *what)
{
    int found;
    long i;
    List *accepts;
    Octstr *needle = octstr_create(what);

    gwlib_assert_init();
    gw_assert(headers != NULL);
    gw_assert(what != NULL);

    /* return all headers with this name */
    accepts = http_header_find_all(headers, header_name);

    found = 0;
    for (i = 0; !found && i < gwlist_len(accepts); ++i) {
        Octstr *header_value = gwlist_get(accepts, i);
        if (octstr_case_search(header_value, needle, 0) != -1)
            found = 1;
    }
	octstr_destroy(needle);
    http_destroy_headers(accepts);
    return found;
}


int http_type_accepted(List *headers, char *type)
{
    return http_something_accepted(headers, "Accept", type);
}


int http_charset_accepted(List *headers, char *charset)
{
    return http_something_accepted(headers, "Accept-Charset", charset);
}


void http_add_basic_auth(List *headers, Octstr *username, Octstr *password)
{
    Octstr *os;
    
    if (password != NULL)
      os = octstr_format("%S:%S", username, password);
    else
      os = octstr_format("%S", username);
    octstr_binary_to_base64(os);
    octstr_strip_blanks(os);
    octstr_insert(os, octstr_imm("Basic "), 0);
    http_header_add(headers, "Authorization", octstr_get_cstr(os));
    octstr_destroy(os);
}


Octstr *http_get_header_parameter(Octstr *value, Octstr *parameter)
{
    long pos, len, end;
    int c, found = 0;
    Octstr *result = NULL;

    len = octstr_len(value);
    /* Find the start of the first parameter. */
    for (pos = 0; pos < len; pos++) {
        c = octstr_get_char(value, pos);
        if (c == ';')
            break;
        else if (c == '"')
            pos += http_header_quoted_string_len(value, pos) - 1;
    }

    if (pos >= len)
        return NULL;   /* no parameters */

    for (pos++; pos > 0 && pos < len && found == 0; pos++) {
        Octstr *key = NULL;
        Octstr *val = NULL;

        end = octstr_search_char(value, '=', pos);
        if (end < 0)
            end = octstr_search_char(value, ';', pos);
        if (end < 0)
            end = octstr_len(value);
        key = octstr_copy(value, pos, end - pos);
        octstr_strip_blanks(key);
        pos = end;

        if (octstr_get_char(value, pos) == '=') {
            pos++;
            while (isspace(octstr_get_char(value, pos)))
                pos++;
            if (octstr_get_char(value, pos) == '"')
                end = pos + http_header_quoted_string_len(value, pos);
            else
                end = octstr_search_char(value, ';', pos);
            if (end < 0)
                end = octstr_len(value);
            val = octstr_copy(value, pos, end - pos);
            octstr_strip_blanks(val);
            pos = end;
            pos = octstr_search_char(value, ';', pos);
        }

        /* is this the pair we look for? bail out then*/
        if (octstr_case_compare(key, parameter) == 0) {
            found++;        
            result = octstr_duplicate(val);
        }

        octstr_destroy(key);
        octstr_destroy(val);
    }

    return result;
}


/***********************************************************************
 * Module initialization and shutdown.
 */


void http_init(void)
{
    gw_assert(run_status == limbo);

#ifdef HAVE_LIBSSL
    conn_init_ssl();
#endif /* HAVE_LIBSSL */
    proxy_init();
    client_init();
    conn_pool_init();
    port_init();
    server_init();
#ifdef HAVE_LIBSSL
    server_ssl_init();
#endif /* HAVE_LIBSSL */
    
    run_status = running;
}


void http_shutdown(void)
{
    gwlib_assert_init();
    gw_assert(run_status == running);

    run_status = terminating;

    conn_pool_shutdown();
    client_shutdown();
    server_shutdown();
    port_shutdown();
    proxy_shutdown();
#ifdef HAVE_LIBSSL
    conn_shutdown_ssl();
    server_shutdown_ssl();
#endif /* HAVE_LIBSSL */
    run_status = limbo;
}


/*
 * This function relies on the HTTP_STATUS_* enum values being
 * chosen to fit this.
 */
int http_status_class(int code)
{
    int sclass;

    if (code < 100 || code >= 600)
        sclass = HTTP_STATUS_UNKNOWN;
    else
        sclass = code - (code % 100);
    return sclass;
}


int http_name2method(Octstr *method)
{
    gw_assert(method != NULL);

    if (octstr_str_compare(method, "GET") == 0) {
        return HTTP_METHOD_GET;
    } 
    else if (octstr_str_compare(method, "POST") == 0) {
        return HTTP_METHOD_POST;
    } 
    else if (octstr_str_compare(method, "HEAD") == 0) {
        return HTTP_METHOD_HEAD;
    } 

    return -1;
}


char *http_method2name(int method)
{
    gw_assert(method > 0 && method <= 3);

    return http_methods[method-1];
}