gnoga_2.1.2_5f127c56/src/gnoga-server-connection.adb

   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
------------------------------------------------------------------------------
--                                                                          --
--                   GNOGA - The GNU Omnificent GUI for Ada                 --
--                                                                          --
--                 G N O G A . S E R V E R . C O N N E C I O N              --
--                                                                          --
--                                 B o d y                                  --
--                                                                          --
--                                                                          --
--                     Copyright (C) 2014 David Botton                      --
--                                                                          --
--  This library is free software;  you can redistribute it and/or modify   --
--  it under terms of the  GNU General Public License  as published by the  --
--  Free Software  Foundation;  either version 3,  or (at your  option) any --
--  later version. This library is distributed in the hope that it will be  --
--  useful, but WITHOUT ANY WARRANTY;  without even the implied warranty of --
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                    --
--                                                                          --
--  As a special exception under Section 7 of GPL version 3, you are        --
--  granted additional permissions described in the GCC Runtime Library     --
--  Exception, version 3.1, as published by the Free Software Foundation.   --
--                                                                          --
--  You should have received a copy of the GNU General Public License and   --
--  a copy of the GCC Runtime Library Exception along with this program;    --
--  see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see   --
--  <http://www.gnu.org/licenses/>.                                         --
--                                                                          --
--  As a special exception, if other files instantiate generics from this   --
--  unit, or you link this unit with other files to produce an executable,  --
--  this  unit  does not  by itself cause  the resulting executable to be   --
--  covered by the GNU General Public License. This exception does not      --
--  however invalidate any other reasons why the executable file might be   --
--  covered by the  GNU Public License.                                     --
--                                                                          --
--  For more information please go to http://www.gnoga.com                  --
------------------------------------------------------------------------------

with Ada.Streams;
with Ada.Directories;
with Ada.Strings;
with Ada.Unchecked_Deallocation;
with Ada.Exceptions;
with Ada.Containers.Ordered_Maps;
with Ada.Text_IO;
with Ada.Streams.Stream_IO;

with GNAT.Sockets.Server;                               use GNAT.Sockets.Server;
with GNAT.Sockets.Connection_State_Machine.HTTP_Server; use GNAT.Sockets.Connection_State_Machine.HTTP_Server;

with Gnoga.Server.Mime;
with Gnoga.Application;
with Gnoga.Server.Connection.Common; use Gnoga.Server.Connection.Common;
with Gnoga.Server.Template_Parser.Simple;

with Strings_Edit.Quoted;
with Strings_Edit.Streams;

package body Gnoga.Server.Connection is
   use type Gnoga.Types.Pointer_to_Connection_Data_Class;

   On_Connect_Event      : Connect_Event      := null;
   On_Post_Event         : Post_Event         := null;
   On_Post_Request_Event : Post_Request_Event := null;
   On_Post_File_Event    : Post_File_Event    := null;

   Exit_Application_Requested : Boolean := False;

   function Global_Gnoga_Client_Factory
     (Listener       : access Connections_Server'Class;
      Request_Length : Positive;
      Input_Size     : Buffer_Length;
      Output_Size    : Buffer_Length)
      return Connection_Ptr;
   --  Passed to Gnoga.Server.Connection.Common.Gnoga_Client_Factory
   --  This allows a common HTTP client for secure and insecure connections
   --  and when desired the secure libraries connection need not be linked in.

   -------------------------------------------------------------------------
   --  Private Types
   -------------------------------------------------------------------------

   protected type String_Buffer is
      procedure Buffering (Value : Boolean);
      function Buffering return Boolean;

      procedure Add (S : in String);
      --  Add to end of buffer

      procedure Preface (S : in String);
      --  Preface to buffer

      function Get return String;
      --  Retrieve buffer

      procedure Get_And_Clear (S : out String);
      --  Retrieve and clear buffer

      function Length return Natural;
      --  Size of buffer

      procedure Clear;
      --  Clear buffer
   private
      Is_Buffering : Boolean := False;
      Buffer       : String;
   end String_Buffer;

   task type Watchdog_Type is
      entry Start;
      entry Stop;
   end Watchdog_Type;

   type Watchdog_Access is access Watchdog_Type;

   Watchdog : Watchdog_Access := null;

   --  Keep alive and check connection status

   -------------------------------------------------------------------------
   --  HTTP Server Setup for Gnoga_HTTP_Server
   -------------------------------------------------------------------------

   --  Gnoga_HTTP_Content  --
   --  Per http connection data

   type Gnoga_HTTP_Client;
   type Socket_Type is access all Gnoga_HTTP_Client;

   type Gnoga_HTTP_Content is new Content_Source with record
      Socket          : Socket_Type           := null;
      Connection_Type : Gnoga_Connection_Type := HTTP;
      Connection_Path : String;
      FS              : Ada.Streams.Stream_IO.File_Type;
      Input_Overflow  : String_Buffer;
      Buffer          : String_Buffer;
      Finalized       : Boolean               := False;
      Text            : aliased Strings_Edit.Streams.String_Stream (500);
   end record;

   overriding function Get
     (Source : access Gnoga_HTTP_Content)
      return Standard.String;
   --  Handle long polling method

   pragma Warnings (Off);
   procedure Write
     (Stream :    access Ada.Streams.Root_Stream_Type'Class;
      Item   : in Gnoga_HTTP_Content);
   for Gnoga_HTTP_Content'Write use Write;
   pragma Warnings (On);

   --  Gnoga_HTTP_Factory  --
   --  Creates Gnoga_HTTP_Client objects on incoming connections
   --  from Gnoga_HTTP_Connection

   type Gnoga_HTTP_Factory
     (Request_Length : Positive; Input_Size : Buffer_Length; Output_Size : Buffer_Length; Max_Connections : Positive)
   is new Connections_Factory with null record;

   overriding function Create
     (Factory  : access Gnoga_HTTP_Factory;
      Listener : access Connections_Server'Class;
      From     : GNAT.Sockets.Sock_Addr_Type)
      return Connection_Ptr;

   --  Gnoga_HTTP_Connection  --

   type Gnoga_HTTP_Connection is new GNAT.Sockets.Server.Connections_Server with null record;

   overriding function Get_Server_Address
     (Listener : Gnoga_HTTP_Connection)
      return GNAT.Sockets.Sock_Addr_Type;
   --  Set the listening host if was set in Initialize

   overriding procedure Create_Socket
     (Listener : in out Gnoga_HTTP_Connection;
      Socket   : in out GNAT.Sockets.Socket_Type;
      Address  :        GNAT.Sockets.Sock_Addr_Type);
   --  Create socket with exception handler

   --  Gnoga_HTTP_Client  --

   type Gnoga_HTTP_Client is new HTTP_Client with record
      Content : aliased Gnoga_HTTP_Content;
   end record;

   --  type Socket_Type is access all Gnoga_HTTP_Client;

   overriding procedure Finalize (Client : in out Gnoga_HTTP_Client);
   --  Handle browser crashes or webkit abrupt closes

   overriding function Get_Name
     (Client : Gnoga_HTTP_Client)
      return Standard.String;

   overriding procedure Do_Get (Client : in out Gnoga_HTTP_Client);

   overriding procedure Do_Post (Client : in out Gnoga_HTTP_Client);

   overriding procedure Body_Received
     (Client  : in out Gnoga_HTTP_Client;
      Content : in out CGI_Keys.Table'Class);

   overriding procedure Body_Received
     (Client  : in out Gnoga_HTTP_Client;
      Content : in out Ada.Streams.Root_Stream_Type'Class);

   overriding procedure Do_Body (Client : in out Gnoga_HTTP_Client);

   overriding procedure Do_Head (Client : in out Gnoga_HTTP_Client);

   overriding function WebSocket_Open
     (Client : access Gnoga_HTTP_Client)
      return WebSocket_Accept;

   overriding procedure WebSocket_Initialize (Client : in out Gnoga_HTTP_Client);

   overriding procedure WebSocket_Received_Part
     (Client  : in out Gnoga_HTTP_Client;
      Message : in     Standard.String);

   overriding procedure WebSocket_Received
     (Client  : in out Gnoga_HTTP_Client;
      Message : in     Standard.String);

   overriding procedure WebSocket_Closed
     (Client  : in out Gnoga_HTTP_Client;
      Status  : in     WebSocket_Status;
      Message : in     Standard.String);

   overriding procedure WebSocket_Error
     (Client : in out Gnoga_HTTP_Client;
      Error  : in     Ada.Exceptions.Exception_Occurrence);

   -------------------------------------------------------------------------
   --  Connection Helpers
   -------------------------------------------------------------------------

   pragma Warnings (Off);
   procedure Start_Long_Polling_Connect
     (Client : in out Gnoga_HTTP_Client;
      ID     :    out Gnoga.Types.Connection_ID);
   --  Start a long polling connection alternative to websocket
   pragma Warnings (On);

   function Buffer_Add
     (ID     : Gnoga.Types.Connection_ID;
      Script : String)
      return Boolean;
   --  If buffering add Script to the buffer for ID and return true, if not
   --  buffering return false;

   procedure Dispatch_Message (Message : in String);
   --  Dispatch an incoming message from browser to event system

   -----------------------
   -- Gnoga_HTTP_Server --
   -----------------------

   Server_Wait : Connection_Holder_Type;

   task type Gnoga_HTTP_Server_Type is
      entry Start;
      entry Stop;
   end Gnoga_HTTP_Server_Type;

   type Gnoga_HTTP_Server_Access is access Gnoga_HTTP_Server_Type;

   Gnoga_HTTP_Server : Gnoga_HTTP_Server_Access := null;

   task body Gnoga_HTTP_Server_Type is
   begin
      accept Start;

      declare
         Factory : aliased Gnoga_HTTP_Factory
           (Request_Length => Max_HTTP_Request_Length, Input_Size => Max_HTTP_Input_Chunk,
            Output_Size    => Max_HTTP_Output_Chunk, Max_Connections => Max_HTTP_Connections);
      begin
         if Verbose_Output then
            Gnoga.Log ("HTTP Server Started");
            --  Trace_On (Factory  => Factory,
            --            Received => Trace_Any,
            --            Sent     => Trace_Any);
         end if;

         if not Secure_Server then
            declare
               Server : Gnoga_HTTP_Connection (Factory'Access, Server_Port);
               pragma Unreferenced (Server);
            begin
               accept Stop;
            end;
         else
            if not Secure_Only then
               declare
                  Server1 : Gnoga_HTTP_Connection (Factory'Access, Server_Port);
                  pragma Unreferenced (Server1);
                  Server2 : Gnoga_HTTP_Connection
                    (Gnoga.Server.Connection.Common.Gnoga_Secure_Factory.all, Secure_Port);
                  pragma Unreferenced (Server2);
               begin
                  accept Stop;
               end;
            else
               declare
                  Server : Gnoga_HTTP_Connection (Gnoga.Server.Connection.Common.Gnoga_Secure_Factory.all, Secure_Port);
                  pragma Unreferenced (Server);
               begin
                  accept Stop;
               end;
            end if;
         end if;

         Server_Wait.Release;

         if Verbose_Output then
            Gnoga.Log ("HTTP Server Stopping");
         end if;
      end;
   end Gnoga_HTTP_Server_Type;

   ------------
   -- Create --
   ------------

   function Global_Gnoga_Client_Factory
     (Listener       : access Connections_Server'Class;
      Request_Length : Positive;
      Input_Size     : Buffer_Length;
      Output_Size    : Buffer_Length)
      return Connection_Ptr
   is
      Socket : constant Socket_Type :=
        new Gnoga_HTTP_Client
          (Listener    => Listener.all'Unchecked_Access, Request_Length => Request_Length, Input_Size => Input_Size,
           Output_Size => Output_Size);
   begin
      Socket.Content.Socket := Socket;

      return Connection_Ptr (Socket);
   end Global_Gnoga_Client_Factory;

   overriding function Create
     (Factory  : access Gnoga_HTTP_Factory;
      Listener : access Connections_Server'Class;
      From     : GNAT.Sockets.Sock_Addr_Type)
      return Connection_Ptr
   is
      pragma Unreferenced (From);
   begin
      return
        Gnoga.Server.Connection.Common.Gnoga_Client_Factory
          (Listener   => Listener.all'Unchecked_Access, Request_Length => Factory.Request_Length,
           Input_Size => Factory.Input_Size, Output_Size => Factory.Output_Size);
   end Create;

   -------------------------
   --  Get_Server_Address --
   -------------------------

   overriding function Get_Server_Address
     (Listener : Gnoga_HTTP_Connection)
      return GNAT.Sockets.Sock_Addr_Type
   is
      use GNAT.Sockets;
      use type String;

      Address : Sock_Addr_Type;
      Host    : constant String := (if Server_Host = "localhost" then UXString'("127.0.0.1") else Server_Host);
   begin
      if Host = "" then
         Address.Addr := Any_Inet_Addr;
      else
         Address.Addr := Inet_Addr (To_UTF_8 (Host));
      end if;

      Address.Port := Listener.Port;

      return Address;
   end Get_Server_Address;

   --------------------
   --  Create_Socket --
   --------------------

   overriding procedure Create_Socket
     (Listener : in out Gnoga_HTTP_Connection;
      Socket   : in out GNAT.Sockets.Socket_Type;
      Address  :        GNAT.Sockets.Sock_Addr_Type)
   is
      use type GNAT.Sockets.Socket_Type;
   begin
      Create_Socket (Connections_Server (Listener), Socket, Address);
   exception
      when Error : others =>
         Gnoga.Log (Error);
         if Socket /= GNAT.Sockets.No_Socket then
            begin
               GNAT.Sockets.Shutdown_Socket (Socket);
            exception
               when others =>
                  null;
            end;
            begin
               GNAT.Sockets.Close_Socket (Socket);
            exception
               when others =>
                  null;
            end;
            Socket := GNAT.Sockets.No_Socket;
         end if;
         Stop;
   end Create_Socket;

   --------------
   -- Get_Name --
   --------------

   overriding function Get_Name
     (Client : Gnoga_HTTP_Client)
      return Standard.String
   is
      pragma Unreferenced (Client);
   begin
      return To_UTF_8 (Gnoga.HTTP_Server_Name);
   end Get_Name;

   -----------------
   -- Do_Get_Head --
   -----------------

   procedure Do_Get_Head
     (Client : in out Gnoga_HTTP_Client;
      Get    : in     Boolean);

   procedure Do_Get_Head
     (Client : in out Gnoga_HTTP_Client;
      Get    : in     Boolean)
   is
      use Strings_Edit.Quoted;

      Status : Status_Line renames Get_Status_Line (Client);

      function Adjust_Name return String;

      function Adjust_Name return String is
         function Start_Path return String;
         function After_Start_Path return String;

         File_Name : constant String := From_UTF_8 (UTF_8_Character_Array (Status.File));

         function Start_Path return String is
            Q : constant Integer := Index (File_Name, "/");
         begin
            if Q = 0 then
               return "";
            else
               return File_Name.Slice (File_Name.First, Q - 1);
            end if;
         end Start_Path;

         function After_Start_Path return String is
            Q : constant Integer := Index (File_Name, "/");
         begin
            if Q = 0 then
               return File_Name;
            else
               return File_Name.Slice (Q + 1, File_Name.Last);
            end if;
         end After_Start_Path;

         Start              : constant String := Start_Path;
         Path_Adjusted_Name : constant String := After_Start_Path;
      begin
         if File_Name = "gnoga_ajax" then
            return File_Name;
         elsif Start = "" and File_Name = "" then
            return Gnoga.Server.HTML_Directory & Boot_HTML;
         elsif Start = "js" then
            return Gnoga.Server.JS_Directory & Path_Adjusted_Name;
         elsif Start = "css" then
            return Gnoga.Server.CSS_Directory & Path_Adjusted_Name;
         elsif Start = "img" then
            return Gnoga.Server.IMG_Directory & Path_Adjusted_Name;
         else
            if Ada.Directories.Exists (Standard.String (To_UTF_8 (Gnoga.Server.HTML_Directory & File_Name))) then
               return Gnoga.Server.HTML_Directory & File_Name;
            else
               return Gnoga.Server.HTML_Directory & Boot_HTML;
            end if;
         end if;
      end Adjust_Name;

      function Image is new UXStrings.Conversions.Scalar_Image (Status_Line_Type);

   begin
      case Status.Kind is
         when None =>
            if Verbose_Output then
               Gnoga.Log
                 ("Requested: Kind: " & Image (Status.Kind) & ", Query: " &
                  From_UTF_8 (UTF_8_Character_Array (Status.Query)));
               Gnoga.Log ("Reply: Not found");
            end if;

            Reply_Text (Client, 404, "Not found", "Not found");
         when File =>
            if Verbose_Output then
               Gnoga.Log
                 ("Requested: Kind: " & Image (Status.Kind) & ", File: " &
                  From_UTF_8 (UTF_8_Character_Array (Status.File)) & ", Query: " &
                  From_UTF_8 (UTF_8_Character_Array (Status.Query)));
            end if;
            Client.Content.Connection_Path := From_UTF_8 (UTF_8_Character_Array (Status.File));

            Send_Status_Line (Client, 200, "OK");
            Send_Date (Client);
            Send
              (Client,
               Standard.String
                 (To_UTF_8
                    ("Cache-Control: no-cache, no-store, must-revalidate" & Gnoga.Server.Connection.Common.CRLF)));
            Send (Client, Standard.String (To_UTF_8 ("Pragma: no-cache" & Gnoga.Server.Connection.Common.CRLF)));
            Send (Client, Standard.String (To_UTF_8 ("Expires: 0" & Gnoga.Server.Connection.Common.CRLF)));
            Send_Connection (Client, Persistent => True);
            Send_Server (Client);

            declare
               F : constant String := Adjust_Name;
               M : constant String := Gnoga.Server.Mime.Mime_Type (F);
            begin
               if F = "gnoga_ajax" then
                  Send_Body (Client, "", Get);

                  declare
                     MH : constant String  := "?m=";
                     Q  : constant Integer :=
                       Index (From_UTF_8 (UTF_8_Character_Array (Status.Query)), MH, Going => Ada.Strings.Forward);
                     Message : constant String :=
                       From_UTF_8 (UTF_8_Character_Array (Status.Query (Q + MH.Length .. Status.Query'Last)));
                  begin
                     Dispatch_Message (Message);
                  end;
               else
                  if M = "text/html" then
                     Client.Content.Finalized := False;

                     declare
                        ID : Gnoga.Types.Connection_ID;
                        F  : String := Gnoga.Server.Template_Parser.Simple.Load_View (Adjust_Name);
                     begin
                        if Gnoga.Application.Favicon /= Null_UXString and
                          Index (F, "<meta name=""generator"" content=""Gnoga"" />") > 0 and
                          Index (F, "favicon.ico") > 0
                        then
                           String_Replace
                             (Source => F, Pattern => "favicon.ico", Replacement => Gnoga.Application.Favicon);
                        end if;
                        if Index (F, "/js/ajax.js") > 0 then
                           Client.Content.Connection_Type := Long_Polling;
                           Client.Content.Buffer.Add (F);

                           Send_Body (Client, Client.Content'Access, Get);

                           Start_Long_Polling_Connect (Client, ID);
                        elsif Index (F, "/js/auto.js") > 0 then
                           Client.Content.Connection_Type := Long_Polling;
                           Start_Long_Polling_Connect (Client, ID);

                           String_Replace (Source => F, Pattern => "@@Connection_ID@@", Replacement => Image (ID));
                           Client.Content.Buffer.Add (F);

                           Send_Body (Client, Client.Content'Access, Get);
                        else
                           Client.Content.Connection_Type := HTTP;
                           Client.Content.Buffer.Add (F);

                           Send_Body (Client, Client.Content'Access, Get);
                        end if;
                     end;
                  else
                     Send_Content_Type (Client, Standard.String (To_UTF_8 (M)));
                     declare
                        use Ada.Streams.Stream_IO;
                     begin
                        if Is_Open (Client.Content.FS) then
                           Close (Client.Content.FS);
                        end if;

                        Open (Client.Content.FS, In_File, Standard.String (To_UTF_8 (F)), Form => "shared=no");
                        Send_Body (Client, Stream (Client.Content.FS), Get);
                     end;
                  end if;
               end if;
               if Verbose_Output then
                  Gnoga.Log ("Reply: " & F & " (" & M & ')');
               end if;
            exception
               when Ada.Text_IO.Name_Error =>
                  if Verbose_Output then
                     Gnoga.Log ("Reply: Not found");
                  end if;
                  Reply_Text (Client, 404, "Not found", "No file " & Quote (Status.File) & " found");
            end;

         when URI =>
            if Verbose_Output then
               Gnoga.Log
                 ("Requested: Kind: " & Image (Status.Kind) & ", Path: " &
                  From_UTF_8 (UTF_8_Character_Array (Status.Path)) & ", Query: " &
                  From_UTF_8 (UTF_8_Character_Array (Status.Query)));
               Gnoga.Log ("Reply: Not found");
            end if;

            Reply_Text (Client, 404, "Not found", "No URI " & Quote (Status.Path) & " found");
      end case;
   exception
      when E : others =>
         Log ("Do_Get_Head Error");
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end Do_Get_Head;

   ------------
   -- Do_Get --
   ------------

   overriding procedure Do_Get (Client : in out Gnoga_HTTP_Client) is
   begin
      Do_Get_Head (Client, True);
   end Do_Get;

   -------------
   -- Do_Post --
   -------------

   overriding procedure Do_Post (Client : in out Gnoga_HTTP_Client) is
   begin
      Do_Get_Head (Client, True);
   end Do_Post;

   -------------------
   -- Body_Received --
   -------------------

   overriding procedure Body_Received
     (Client  : in out Gnoga_HTTP_Client;
      Content : in out CGI_Keys.Table'Class)
   is
      pragma Unreferenced (Content);
      Status : Status_Line renames Get_Status_Line (Client);

      Parameters : Gnoga.Types.Data_Map_Type;
   begin
      if On_Post_Event /= null and Status.Kind = File then
         for i in 1 .. Client.Get_CGI_Size loop
            Parameters.Insert
              (From_UTF_8 (UTF_8_Character_Array (Client.Get_CGI_Key (i))),
               From_UTF_8 (UTF_8_Character_Array (Client.Get_CGI_Value (i))));
         end loop;

         On_Post_Event (From_UTF_8 (UTF_8_Character_Array (Status.File & Status.Query)), Parameters);
      end if;
   end Body_Received;

   -------------------
   -- Body_Received --
   -------------------

   overriding procedure Body_Received
     (Client  : in out Gnoga_HTTP_Client;
      Content : in out Ada.Streams.Root_Stream_Type'Class)
   is
      pragma Unreferenced (Content);
      Status      : Status_Line renames Get_Status_Line (Client);
      Disposition : constant String :=
        From_UTF_8 (UTF_8_Character_Array (Client.Get_Multipart_Header (Content_Disposition_Header)));
      Field_ID     : constant String  := "name=""";
      n            : constant Natural := Index (Disposition, Field_ID);
      Eq           : constant Natural := Index (Disposition, """", n + Field_ID.Length);
      Field_Name   : constant String  := Disposition.Slice (n + Field_ID.Length, Eq - 1);
      Content_Type : constant String  :=
        From_UTF_8 (UTF_8_Character_Array (Client.Get_Multipart_Header (Content_Type_Header)));

      Parameters : Gnoga.Types.Data_Map_Type;
   begin
      if On_Post_Event /= null and Status.Kind = File and Content_Type = "" then
         Parameters.Insert (Field_Name, From_UTF_8 (UTF_8_Character_Array (Client.Content.Text.Get)));
         On_Post_Event (From_UTF_8 (UTF_8_Character_Array (Status.File & Status.Query)), Parameters);
      end if;
   end Body_Received;

   -------------
   -- Do_Post --
   -------------

   overriding procedure Do_Body (Client : in out Gnoga_HTTP_Client) is
      use Ada.Streams.Stream_IO;

      Status : Status_Line renames Get_Status_Line (Client);

      Param_List : String;

      Content_Type : constant String := From_UTF_8 (UTF_8_Character_Array (Client.Get_Header (Content_Type_Header)));
      Disposition  : constant String :=
        From_UTF_8 (UTF_8_Character_Array (Client.Get_Multipart_Header (Content_Disposition_Header)));
   begin
      --  Gnoga.Log ("Content_Type: " & Content_Type & ", Disposition: " & Disposition);
      if On_Post_Request_Event /= null then
         On_Post_Request_Event (From_UTF_8 (UTF_8_Character_Array (Status.File & Status.Query)), Param_List);
      end if;

      if Content_Type = "application/x-www-form-urlencoded" then
         Client.Receive_Body (Standard.String (To_UTF_8 (Param_List)));
      end if;

      if Index (Content_Type, "multipart/form-data") = Content_Type.First then
         if Index (Disposition, "form-data") = Disposition.First then
            declare
               Field_ID : constant String := "name=""";
               File_ID  : constant String := "filename=""";

               n : constant Natural := Index (Disposition, Field_ID);
               f : constant Natural := Index (Disposition, File_ID);
            begin
               if n /= 0 then
                  declare
                     Eq         : constant Natural := Index (Disposition, """", n + Field_ID.Length);
                     Field_Name : constant String  := Disposition.Slice (n + Field_ID.Length, Eq - 1);
                  begin
                     if Index (Param_List, Field_Name) > 0 then
                        if f /= 0 then
                           declare
                              Eq        : constant Natural := Index (Disposition, """", f + File_ID.Length);
                              File_Name : constant String  := Disposition.Slice (f + File_ID.Length, Eq - 1);
                           begin
                              if On_Post_File_Event = null then
                                 Gnoga.Log ("Attempt to upload file without an On_Post_File_Event set");
                              else
                                 if Is_Open (Client.Content.FS) then
                                    Close (Client.Content.FS);
                                 end if;

                                 Create
                                   (Client.Content.FS, Out_File,
                                    Standard.String (To_UTF_8 (Gnoga.Server.Upload_Directory & File_Name & ".tmp")),
                                    "Text_Translation=No");

                                 Receive_Body (Client, Stream (Client.Content.FS));

                                 On_Post_File_Event
                                   (From_UTF_8 (UTF_8_Character_Array (Status.File & Status.Query)), File_Name,
                                    File_Name & ".tmp");
                              end if;
                           end;
                        else
                           Client.Content.Text.Rewind;
                           Client.Receive_Body (Client.Content.Text'Access);
                        end if;
                     end if;
                  end;
               end if;
            end;
         end if;
      end if;
   exception
      when E : others =>
         Log ("Do_Body Error");
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end Do_Body;

   -------------
   -- Do_Head --
   -------------

   overriding procedure Do_Head (Client : in out Gnoga_HTTP_Client) is
   begin
      Do_Get_Head (Client, False);
   end Do_Head;

   -------------------------------------------------------------------------
   --  Gnoga Server Connection Methods
   -------------------------------------------------------------------------

   ----------------
   -- Initialize --
   ----------------

   procedure Initialize
     (Host    : in String  := "";
      Port    : in Integer := 8_080;
      Boot    : in String  := "boot.html";
      Verbose : in Boolean := True)
   is
      function Image is new UXStrings.Conversions.Integer_Image (GNAT.Sockets.Port_Type);
   begin
      Verbose_Output := Verbose;

      Boot_HTML   := Boot;
      Server_Port := GNAT.Sockets.Port_Type (Port);
      Server_Host := Host;

      if Verbose then
         Write_To_Console ("Gnoga            :" & Gnoga.Version);
         Write_To_Console ("Application root :" & Application_Directory);
         Write_To_Console ("Executable at    :" & Executable_Directory);
         Write_To_Console ("HTML root        :" & HTML_Directory);
         Write_To_Console ("Upload directory :" & Upload_Directory);
         Write_To_Console ("Templates root   :" & Templates_Directory);
         Write_To_Console ("/js  at          :" & JS_Directory);
         Write_To_Console ("/css at          :" & CSS_Directory);
         Write_To_Console ("/img at          :" & IMG_Directory);

         if not Secure_Only then
            Write_To_Console ("Boot file        :" & Boot);
            Write_To_Console ("HTTP listen on   :" & Host & ":" & Image (Server_Port));
         end if;

         if Secure_Server then
            Write_To_Console ("HTTPS listen on  :" & Host & ":" & Image (Secure_Port));
         end if;
      end if;

      Watchdog := new Watchdog_Type;
      Watchdog.Start;
   end Initialize;

   ---------
   -- Run --
   ---------

   procedure Run is
   begin
      Gnoga_HTTP_Server := new Gnoga_HTTP_Server_Type;
      Gnoga_HTTP_Server.Start;

      Server_Wait.Hold;

      Exit_Application_Requested := True;
   end Run;

   -------------------
   -- Shutting_Down --
   -------------------

   function Shutting_Down return Boolean is
   begin
      return Exit_Application_Requested;
   end Shutting_Down;

   ----------------------------
   -- Connection_Holder_Type --
   ----------------------------

   protected body Connection_Holder_Type is
      entry Hold when not Connected is
      begin
         null;
         --  Semaphore does not reset itself to a blocking state.
         --  This ensures that if Released before Hold that Hold
         --  will not block and connection will be released.
         --  It also allows for On_Connect Handler to not have to use
         --  Connection.Hold unless there is a desire code such as to
         --  clean up after a connection is ended.
      end Hold;

      procedure Release is
      begin
         Connected := False;
      end Release;
   end Connection_Holder_Type;

   type Connection_Holder_Access is access all Connection_Holder_Type;

   package Connection_Holder_Maps is new Ada.Containers.Ordered_Maps (Gnoga.Types.Unique_ID, Connection_Holder_Access);

   package Connection_Data_Maps is new Ada.Containers.Ordered_Maps
     (Gnoga.Types.Unique_ID, Gnoga.Types.Pointer_to_Connection_Data_Class);

   ---------------------
   -- Event_Task_Type --
   ---------------------

   task type Event_Task_Type (TID : Gnoga.Types.Connection_ID);

   type Event_Task_Access is access all Event_Task_Type;

   procedure Free_Event_Task is new Ada.Unchecked_Deallocation (Event_Task_Type, Event_Task_Access);

   package Event_Task_Maps is new Ada.Containers.Ordered_Maps (Gnoga.Types.Unique_ID, Event_Task_Access);

   ------------------------
   -- Connection Manager --
   ------------------------

   package Socket_Maps is new Ada.Containers.Ordered_Maps (Gnoga.Types.Connection_ID, Socket_Type);
   --  Socket Maps are used for the Connection Manager to map connection IDs
   --  to web sockets.

   protected Connection_Manager is
      procedure Add_Connection
        (Socket : in     Socket_Type;
         New_ID :    out Gnoga.Types.Connection_ID);
      --  Adds Socket to managed Connections and generates a New_ID.

      procedure Start_Connection (New_ID : in Gnoga.Types.Connection_ID);
      --  Start event task on connection

      procedure Swap_Connection
        (New_ID : in Gnoga.Types.Connection_ID;
         Old_ID : in Gnoga.Types.Connection_ID);
      --  Reconnect old connection

      procedure Add_Connection_Holder
        (ID     : in Gnoga.Types.Connection_ID;
         Holder : in Connection_Holder_Access);
      --  Adds a connection holder to the connection
      --  Can only be one at any given time.

      procedure Add_Connection_Data
        (ID   : in Gnoga.Types.Connection_ID;
         Data : in Gnoga.Types.Pointer_to_Connection_Data_Class);
      --  Adds data to be associated with connection

      function Connection_Data
        (ID : in Gnoga.Types.Connection_ID)
         return Gnoga.Types.Pointer_to_Connection_Data_Class;
      --  Returns the Connection_Data associated with ID

      procedure Delete_Connection_Holder (ID : in Gnoga.Types.Connection_ID);
      --  Delete connection holder

      procedure Delete_Connection (ID : in Gnoga.Types.Connection_ID);
      --  Delete Connection with ID.
      --  Releases connection holder if present.

      procedure Finalize_Connection (ID : in Gnoga.Types.Connection_ID);
      --  Mark Connection with ID for deletion.

      function Valid
        (ID : in Gnoga.Types.Connection_ID)
         return Boolean;
      --  Return True if ID is in connection map.

      procedure First (ID : out Gnoga.Types.Connection_ID);
      --  Return first ID if ID is in connection map else 0.

      procedure Next (ID : out Gnoga.Types.Connection_ID);
      --  Return next ID if ID is in connection map else 0.

      function Connection_Socket
        (ID : in Gnoga.Types.Connection_ID)
         return Socket_Type;
      --  Return the Socket_Type associated with ID
      --  Raises Connection_Error if ID is not Valid

      function Find_Connection_ID
        (Socket : Socket_Type)
         return Gnoga.Types.Connection_ID;
      --  Find the Connection_ID related to Socket.

      procedure Delete_All_Connections;
      --  Called by Stop to close down server

      function Active_Connections return Ada.Containers.Count_Type;
      --  Returns the number of active connections
   private
      Socket_Count          : Gnoga.Types.Connection_ID := 0;
      Connection_Holder_Map : Connection_Holder_Maps.Map;
      Connection_Data_Map   : Connection_Data_Maps.Map;
      Event_Task_Map        : Event_Task_Maps.Map;
      Socket_Map            : Socket_Maps.Map;
      Shadow_Socket_Map     : Socket_Maps.Map;
      Current_Socket        : Socket_Maps.Cursor        := Socket_Maps.No_Element;
   end Connection_Manager;

   protected body Connection_Manager is
      procedure Add_Connection
        (Socket : in     Socket_Type;
         New_ID :    out Gnoga.Types.Connection_ID)
      is
      begin
         Socket_Count := Socket_Count + 1;
         New_ID       := Socket_Count;
         Socket_Map.Insert (New_ID, Socket);
      end Add_Connection;

      procedure Start_Connection (New_ID : in Gnoga.Types.Connection_ID) is
      begin
         Event_Task_Map.Insert (New_ID, new Event_Task_Type (New_ID));
      end Start_Connection;

      procedure Swap_Connection
        (New_ID : in Gnoga.Types.Connection_ID;
         Old_ID : in Gnoga.Types.Connection_ID)
      is
      begin
         if Socket_Map.Contains (Old_ID) then
            declare
               Old_Socket : constant Socket_Type := Socket_Map.Element (Old_ID);
               New_Socket : constant Socket_Type := Socket_Map.Element (New_ID);
            begin
               New_Socket.Content.Connection_Path := Old_Socket.Content.Connection_Path;
               Socket_Map.Replace (Old_ID, New_Socket);
               Socket_Map.Replace (New_ID, Old_Socket);
               Old_Socket.Content.Finalized := True;
            end;
         else
            raise Connection_Error with "Old connection ID " & To_ASCII (Image (Old_ID)) & " already gone";
         end if;
      end Swap_Connection;

      procedure Add_Connection_Holder
        (ID     : in Gnoga.Types.Connection_ID;
         Holder : in Connection_Holder_Access)
      is
      begin
         Connection_Holder_Map.Insert (ID, Holder);
      end Add_Connection_Holder;

      procedure Delete_Connection_Holder (ID : in Gnoga.Types.Connection_ID) is
      begin
         if Connection_Holder_Map.Contains (ID) then
            Connection_Holder_Map.Delete (ID);
         end if;
      end Delete_Connection_Holder;

      procedure Add_Connection_Data
        (ID   : in Gnoga.Types.Connection_ID;
         Data : in Gnoga.Types.Pointer_to_Connection_Data_Class)
      is
      begin
         Connection_Data_Map.Include (ID, Data);
      end Add_Connection_Data;

      function Connection_Data
        (ID : in Gnoga.Types.Connection_ID)
         return Gnoga.Types.Pointer_to_Connection_Data_Class
      is
      begin
         if Connection_Data_Map.Contains (ID) then
            return Connection_Data_Map.Element (ID);
         else
            return null;
         end if;
      end Connection_Data;

      procedure Delete_Connection (ID : in Gnoga.Types.Connection_ID) is
      begin
         if (ID > 0) then
            Gnoga.Log ("Deleting connection ID " & Image (ID));

            if Connection_Holder_Map.Contains (ID) then
               Connection_Holder_Map.Element (ID).Release;
               Connection_Holder_Map.Delete (ID);
            end if;

            if Connection_Data_Map.Contains (ID) then
               Connection_Data_Map.Delete (ID);
            end if;

            if Socket_Map.Contains (ID) then
               Socket_Map.Delete (ID);
            end if;

            if Event_Task_Map.Contains (ID) then
               declare
                  E : Event_Task_Access := Event_Task_Map.Element (ID);
               begin
                  Free_Event_Task (E);
                  Event_Task_Map.Delete (ID);
               end;
            end if;
         end if;
      exception
         when E : others =>
            Log ("Delete_Connection error on ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
      end Delete_Connection;

      procedure Finalize_Connection (ID : in Gnoga.Types.Connection_ID) is
      begin
         if (ID > 0) and Socket_Map.Contains (ID) then
            if Verbose_Output then
               Gnoga.Log ("Finalizing connection ID " & Image (ID));
            end if;

            Socket_Map.Element (ID).Content.Finalized := True;
         end if;
      end Finalize_Connection;

      function Valid
        (ID : in Gnoga.Types.Connection_ID)
         return Boolean
      is
      begin
         return Socket_Map.Contains (ID);
      end Valid;

      procedure First (ID : out Gnoga.Types.Connection_ID) is
         use type Socket_Maps.Cursor;
      begin
         Shadow_Socket_Map := Socket_Map;
         Current_Socket    := Shadow_Socket_Map.First;
         if Current_Socket /= Socket_Maps.No_Element then
            ID := Socket_Maps.Key (Current_Socket);
         else
            ID := 0;
         end if;
      end First;

      procedure Next (ID : out Gnoga.Types.Connection_ID) is
         use type Socket_Maps.Cursor;
      begin
         Current_Socket := Socket_Maps.Next (Current_Socket);
         if Current_Socket /= Socket_Maps.No_Element then
            ID := Socket_Maps.Key (Current_Socket);
         else
            ID := 0;
         end if;
      end Next;

      function Connection_Socket
        (ID : in Gnoga.Types.Connection_ID)
         return Socket_Type
      is
         use type Socket_Maps.Cursor;
         Connection_Cursor : constant Socket_Maps.Cursor := Socket_Map.Find (ID);
      begin
         if Connection_Cursor = Socket_Maps.No_Element then
            Log ("Error Connection_Socket ID " & Image (ID) & " not found in connection map. ");
            raise Connection_Error
              with "Connection ID " & To_ASCII (Image (ID)) & " not found in connection map. " &
              "Connection most likely was previously closed.";
         else
            return Socket_Maps.Element (Connection_Cursor);
         end if;
      end Connection_Socket;

      function Find_Connection_ID
        (Socket : Socket_Type)
         return Gnoga.Types.Connection_ID
      is
         use type Socket_Maps.Cursor;

         Cursor : Socket_Maps.Cursor := Socket_Map.First;
      begin
         while Cursor /= Socket_Maps.No_Element loop
            if Socket_Maps.Element (Cursor) = Socket then
               return Socket_Maps.Key (Cursor);
            else
               Socket_Maps.Next (Cursor);
            end if;
         end loop;

         return Gnoga.Types.No_Connection;
      end Find_Connection_ID;

      procedure Delete_All_Connections is
         procedure Do_Delete (C : in Socket_Maps.Cursor);

         procedure Do_Delete (C : in Socket_Maps.Cursor) is
         begin
            Delete_Connection (Socket_Maps.Key (C));
         end Do_Delete;
      begin
         --  Socket_Map.Iterate (Do_Delete'Access); --  provoque PROGRAM_ERROR
         --  Message: Gnoga.Server.Connection.Socket_Maps.Tree_Operations.
         --    Delete_Node_Sans_Free: attempt to tamper with cursors
         --    (container is busy)
         while not Socket_Map.Is_Empty loop
            Do_Delete (Socket_Map.First);
         end loop;
      end Delete_All_Connections;

      function Active_Connections return Ada.Containers.Count_Type is
      begin
         return Socket_Map.Length;
      end Active_Connections;
   end Connection_Manager;

   task body Event_Task_Type is
      Connection_Holder : aliased Connection_Holder_Type;
      ID                : Gnoga.Types.Connection_ID;
   begin
      ID := TID;
      --  Insure that TID is retained even if task is "deleted"

      Connection_Manager.Add_Connection_Holder (ID, Connection_Holder'Unchecked_Access);

      begin
         delay 0.3;
         --  Give time to finish handshaking

         Execute_Script (ID, "gnoga['Connection_ID']=" & Image (ID));

         Execute_Script (ID, "TRUE=true");
         Execute_Script (ID, "FALSE=false");
         --  By setting the variable TRUE and FALSE it is possible to set
         --  a property or attribute with Boolean'Image which will result
         --  in TRUE or FALSE not the case sensitive true or false
         --  expected.

         On_Connect_Event (ID, Connection_Holder'Unchecked_Access);
      exception
         when E : Connection_Error =>
            --  Browser was closed by user
            Log ("Error browser was closed by user ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
            Connection_Holder.Release;
         when E : others =>
            Connection_Holder.Release;

            Log ("Error on Connection ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
      end;

      Connection_Manager.Delete_Connection_Holder (ID);
      Connection_Manager.Finalize_Connection (ID);
      --  Insure cleanup even if socket not closed by external connection
   exception
      when E : others =>
         Log ("Connection Manager Error Connection ID " & Image (ID));
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end Event_Task_Type;

   --------------
   -- Watchdog --
   --------------

   task body Watchdog_Type is
      procedure Ping (ID : in Gnoga.Types.Connection_ID);

      procedure Ping (ID : in Gnoga.Types.Connection_ID) is
         Socket : Socket_Type := Connection_Manager.Connection_Socket (ID);
      begin
         if Socket.Content.Finalized then
            if Verbose_Output then
               Gnoga.Log ("Ping on Finalized ID " & Image (ID));
            end if;
            Connection_Manager.Delete_Connection (ID);
            Socket.Shutdown;
         elsif Socket.Content.Connection_Type = Long_Polling then
            if Verbose_Output then
               Gnoga.Log ("Ping on long polling ID " & Image (ID));
            end if;

            Execute_Script (ID, "0");

         elsif Socket.Content.Connection_Type = WebSocket then
            if Verbose_Output then
               Gnoga.Log ("Ping on websocket ID " & Image (ID));
            end if;

            Socket.WebSocket_Send ("0");
         end if;
      exception
         when E : Storage_Error =>
            Gnoga.Log ("Invalid socket, Deleting ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
            Connection_Manager.Delete_Connection (ID);
         when E : others =>
            Log ("Ping error on ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
            if Socket.Content.Connection_Type = Long_Polling then
               Gnoga.Log ("Long polling error closing ID " & Image (ID));
               Socket.Content.Finalized := True;
               Socket.Shutdown;
            else
               begin
                  delay 3.0;
                  Socket := Connection_Manager.Connection_Socket (ID);
                  Socket.WebSocket_Send ("0");
               exception
                  when E : others =>
                     Log ("Watchdog closed connection ID " & Image (ID));
                     Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));

                     begin
                        Connection_Manager.Delete_Connection (ID);
                     exception
                        when E : others =>
                           Log ("Watchdog ping error ID " & Image (ID));
                           Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
                     end;
               end;
            end if;
      end Ping;
   begin
      accept Start;

      loop
         declare
            ID : Gnoga.Types.Connection_ID;
         begin
            Connection_Manager.First (ID);
            while ID /= 0 loop
               Ping (ID);
               Connection_Manager.Next (ID);
            end loop;
         exception
            when E : others =>
               Log ("Watchdog error on websocket ID " & Image (ID));
               Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
         end;

         select
            accept Stop;
            exit;
         or
            delay 60.0;
         end select;
      end loop;
   end Watchdog_Type;

   ---------------------------
   -- Message Queue Manager --
   ---------------------------

   No_Object : exception;

   function "="
     (Left, Right : Gnoga.Gui.Base.Pointer_To_Base_Class)
      return Boolean;
   --  Properly identify equivalent objects

   function "="
     (Left, Right : Gnoga.Gui.Base.Pointer_To_Base_Class)
      return Boolean
   is
   begin
      return Left.Unique_ID = Right.Unique_ID;
   end "=";

   package Object_Maps is new Ada.Containers.Ordered_Maps (Gnoga.Types.Unique_ID, Gnoga.Gui.Base.Pointer_To_Base_Class);

   protected Object_Manager is
      function Get_Object
        (ID : Gnoga.Types.Unique_ID)
         return Gnoga.Gui.Base.Pointer_To_Base_Class;
      procedure Insert
        (ID     : in Gnoga.Types.Unique_ID;
         Object : in Gnoga.Gui.Base.Pointer_To_Base_Class);

      procedure Delete (ID : Gnoga.Types.Unique_ID);
   private
      Object_Map : Object_Maps.Map;
   end Object_Manager;

   protected body Object_Manager is
      function Get_Object
        (ID : Gnoga.Types.Unique_ID)
         return Gnoga.Gui.Base.Pointer_To_Base_Class
      is
      begin
         if Object_Map.Contains (ID) then
            return Object_Map.Element (ID);
         else
            raise No_Object with "ID " & To_ASCII (Image (ID));
         end if;
      end Get_Object;

      procedure Insert
        (ID     : in Gnoga.Types.Unique_ID;
         Object : in Gnoga.Gui.Base.Pointer_To_Base_Class)
      is
      begin
         Object_Map.Insert (Key => ID, New_Item => Object);
      end Insert;

      procedure Delete (ID : Gnoga.Types.Unique_ID) is
      begin
         if Object_Map.Contains (ID) then
            Object_Map.Delete (ID);
         end if;
      end Delete;
   end Object_Manager;

   --------------------
   -- WebSocket_Open --
   --------------------

   overriding function WebSocket_Open
     (Client : access Gnoga_HTTP_Client)
      return WebSocket_Accept
   is

      Status : Status_Line renames Get_Status_Line (Client.all);

      F : constant String := From_UTF_8 (UTF_8_Character_Array (Status.File));
   begin
      if F /= "gnoga" then
         Gnoga.Log ("Invalid URL for Websocket: " & F);
         declare
            Reason : constant String := "Invalid URL";
         begin
            return
              (Accepted => False, Length => Reason.Length, Code => 400, Reason => Standard.String (To_UTF_8 (Reason)));
         end;
      end if;

      Client.Content.Connection_Type := WebSocket;

      if On_Connect_Event /= null then
         return
           (Accepted  => True, Length => 0, Size => Max_Websocket_Message, Duplex => True, Chunked => True,
            Protocols => "");
      else
         Gnoga.Log ("No Connection event set.");
         declare
            Reason : constant String := "No connection event set";
         begin
            return
              (Accepted => False, Length => Reason.Length, Code => 400, Reason => Standard.String (To_UTF_8 (Reason)));
         end;
      end if;
   end WebSocket_Open;

   --------------------------
   -- WebSocket_Initialize --
   --------------------------

   overriding procedure WebSocket_Initialize (Client : in out Gnoga_HTTP_Client) is
      Status : Status_Line renames Get_Status_Line (Client);

      F : constant String      := From_UTF_8 (UTF_8_Character_Array (Status.Query));
      S : constant Socket_Type := Client'Unchecked_Access;

      ID : Gnoga.Types.Connection_ID := Gnoga.Types.No_Connection;

      function Get_Old_ID return String;

      function Get_Old_ID return String is
         C : constant String := "Old_ID=";

         I : constant Integer := Index (F, C);
      begin
         if I > 0 then
            return F.Slice (I + C.Length, F.Last);
         else
            return "";
         end if;
      end Get_Old_ID;

      Old_ID : constant String := Get_Old_ID;
   begin
      Connection_Manager.Add_Connection (Socket => S, New_ID => ID);

      if Old_ID /= "" and Old_ID /= "undefined" then
         if Verbose_Output then
            Gnoga.Log ("Swapping websocket connection ID " & Image (ID) & " <=> " & Old_ID);
         end if;

         begin
            Connection_Manager.Swap_Connection (ID, Value (Old_ID));
         exception
            when E : Connection_Error =>
               Gnoga.Log ("Connection error ID " & Image (ID));
               Gnoga.Log (From_UTF_8 (Ada.Exceptions.Exception_Message (E)));
               Client.Content.Finalized := True;
               Connection_Manager.Delete_Connection (ID);
               Gnoga.Log ("Connection aborted ID " & Image (ID));
         end;
      else
         Connection_Manager.Start_Connection (ID);

         if Verbose_Output then
            Gnoga.Log ("New connection ID " & Image (ID));
         end if;
      end if;
   exception
      when E : others =>
         Gnoga.Log ("Open error ID " & Image (ID));
         Gnoga.Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end WebSocket_Initialize;

   ----------------------
   -- WebSocket_Closed --
   ----------------------

   overriding procedure WebSocket_Closed
     (Client  : in out Gnoga_HTTP_Client;
      Status  : in     WebSocket_Status;
      Message : in     Standard.String)
   is
      pragma Unreferenced (Status);
      S : constant Socket_Type := Client'Unchecked_Access;

      ID : constant Gnoga.Types.Connection_ID := Connection_Manager.Find_Connection_ID (S);
   begin
      if ID /= Gnoga.Types.No_Connection then
         S.Content.Finalized := True;

         if Verbose_Output then
            if Message /= "" then
               Gnoga.Log ("Websocket connection closed ID " & Image (ID) & " with message : " & From_UTF_8 (Message));
            else
               Gnoga.Log ("Websocket connection closed ID " & Image (ID));
            end if;
         end if;

         Connection_Manager.Delete_Connection (ID);
      end if;
   end WebSocket_Closed;

   ---------------------
   -- WebSocket_Error --
   ---------------------

   overriding procedure WebSocket_Error
     (Client : in out Gnoga_HTTP_Client;
      Error  : in     Ada.Exceptions.Exception_Occurrence)
   is
      S : constant Socket_Type := Client'Unchecked_Access;

      ID : constant Gnoga.Types.Connection_ID := Connection_Manager.Find_Connection_ID (S);
   begin
      S.Content.Finalized := True;

      Gnoga.Log
        ("Connection error ID " & Image (ID) & " with message : " &
         From_ASCII (Ada.Exceptions.Exception_Information (Error)));
      --  If not reconnected by next watchdog ping connection will be deleted.
   end WebSocket_Error;

   --------------------------------
   -- Start_Long_Polling_Connect --
   --------------------------------

   procedure Start_Long_Polling_Connect
     (Client : in out Gnoga_HTTP_Client;
      ID     :    out Gnoga.Types.Connection_ID)
   is
      S : constant Socket_Type := Client'Unchecked_Access;
   begin
      Connection_Manager.Add_Connection (Socket => S, New_ID => ID);
      Connection_Manager.Start_Connection (ID);

      if Verbose_Output then
         Gnoga.Log ("New long polling connection ID " & Image (ID));
      end if;
   end Start_Long_Polling_Connect;

   --------------------
   -- Script_Manager --
   --------------------

   protected type Script_Holder_Type is
      entry Hold;
      procedure Release (Result : in String);
      function Result return String;
   private
      Connected     : Boolean := True;
      Script_Result : String;
   end Script_Holder_Type;

   protected body Script_Holder_Type is
      entry Hold when not Connected is
      begin
         null;
         --  Semaphore does not reset itself to a blocking state.
         --  This ensures that if Released before Hold that Hold
         --  will not block and connection will be released.
      end Hold;

      procedure Release (Result : in String) is
      begin
         Connected     := False;
         Script_Result := Result;
      end Release;

      function Result return String is
      begin
         return Script_Result;
      end Result;
   end Script_Holder_Type;

   type Script_Holder_Access is access all Script_Holder_Type;

   package Script_Holder_Maps is new Ada.Containers.Ordered_Maps (Gnoga.Types.Unique_ID, Script_Holder_Access);

   protected type Script_Manager_Type is
      procedure Add_Script_Holder
        (ID     :    out Gnoga.Types.Unique_ID;
         Holder : in     Script_Holder_Access);
      --  Adds a script holder to wait for script execution to end
      --  and return results;

      procedure Delete_Script_Holder (ID : in Gnoga.Types.Unique_ID);
      --  Delete script holder

      procedure Release_Hold
        (ID     : in Gnoga.Types.Unique_ID;
         Result : in String);
      --  Delete connection hold with ID.
   private
      Script_Holder_Map : Script_Holder_Maps.Map;
      Script_ID         : Gnoga.Types.Unique_ID := 0;
   end Script_Manager_Type;

   protected body Script_Manager_Type is
      procedure Add_Script_Holder
        (ID     :    out Gnoga.Types.Connection_ID;
         Holder : in     Script_Holder_Access)
      is
      begin
         Script_ID := Script_ID + 1;
         Script_Holder_Map.Insert (Script_ID, Holder);

         ID := Script_ID;
      end Add_Script_Holder;

      procedure Delete_Script_Holder (ID : in Gnoga.Types.Connection_ID) is
      begin
         Script_Holder_Map.Delete (ID);
      end Delete_Script_Holder;

      procedure Release_Hold
        (ID     : in Gnoga.Types.Unique_ID;
         Result : in String)
      is
      begin
         if Script_Holder_Map.Contains (ID) then
            Script_Holder_Map.Element (ID).Release (Result);
         end if;
      end Release_Hold;
   end Script_Manager_Type;

   Script_Manager : Script_Manager_Type;

   -----------------------------
   -- WebSocket_Received_Part --
   -----------------------------

   overriding procedure WebSocket_Received_Part
     (Client  : in out Gnoga_HTTP_Client;
      Message : in     Standard.String)
   is
   begin
      Client.Content.Input_Overflow.Add (From_UTF_8 (UTF_8_Character_Array (Message)));
   end WebSocket_Received_Part;

   ------------------------
   -- WebSocket_Received --
   ------------------------

   overriding procedure WebSocket_Received
     (Client  : in out Gnoga_HTTP_Client;
      Message : in     Standard.String)
   is
      Full_Message : constant String :=
        Client.Content.Input_Overflow.Get & From_UTF_8 (UTF_8_Character_Array (Message));
   begin
      Client.Content.Input_Overflow.Clear;

      if Full_Message = "0" then
         return;
      end if;

      Dispatch_Message (Full_Message);

   exception
      when E : others =>
         Log ("Websocket Message Error");
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end WebSocket_Received;

   ----------------------
   -- Dispatch_Message --
   ----------------------

   task type Dispatch_Task_Type (Object : Gnoga.Gui.Base.Pointer_To_Base_Class) is
      entry Start
        (Event : in String;
         Data  : in String;
         ID    : in Gnoga.Types.Unique_ID);
   end Dispatch_Task_Type;

   type Dispatch_Task_Access is access all Dispatch_Task_Type;

   procedure Free_Dispatch_Task is new Ada.Unchecked_Deallocation (Dispatch_Task_Type, Dispatch_Task_Access);

   package Dispatch_Task_Maps is new Ada.Containers.Ordered_Maps (Gnoga.Types.Unique_ID, Dispatch_Task_Access);

   protected Dispatch_Task_Objects is
      procedure Add_Dispatch_Task
        (ID            : in Gnoga.Types.Unique_ID;
         Dispatch_Task : in Dispatch_Task_Access);

      function Object
        (ID : Gnoga.Types.Unique_ID)
         return Dispatch_Task_Access;

      procedure Delete_Dispatch_Task (ID : in Gnoga.Types.Unique_ID);
   private
      Dispatch_Task_Map : Dispatch_Task_Maps.Map;
   end Dispatch_Task_Objects;

   protected body Dispatch_Task_Objects is
      procedure Add_Dispatch_Task
        (ID            : in Gnoga.Types.Unique_ID;
         Dispatch_Task : in Dispatch_Task_Access)
      is
      begin
         Dispatch_Task_Map.Insert (ID, Dispatch_Task);
      end Add_Dispatch_Task;

      function Object
        (ID : Gnoga.Types.Unique_ID)
         return Dispatch_Task_Access
      is
      begin
         return Dispatch_Task_Map.Element (ID);
      end Object;

      procedure Delete_Dispatch_Task (ID : in Gnoga.Types.Unique_ID) is
         Dummy_T : Dispatch_Task_Access := Dispatch_Task_Map.Element (ID);
      begin
         Free_Dispatch_Task (Dummy_T);
         --  http://adacore.com/developers/development-log/NF-65-H911-007-gnat
         --  This will cause Dummy_T to free upon task termination.
         Dispatch_Task_Map.Delete (ID);
      end Delete_Dispatch_Task;
   end Dispatch_Task_Objects;

   task body Dispatch_Task_Type is
      E : String;
      D : String;
      I : Gnoga.Types.Unique_ID;
   begin
      accept Start
        (Event : in String;
         Data  : in String;
         ID    : in Gnoga.Types.Unique_ID) do
         E := Event;
         D := Data;
         I := ID;
      end Start;

      Object.Flush_Buffer;

      declare
         Continue : Boolean;

         Event : constant String := E;
         Data  : constant String := D;
      begin
         Object.Fire_On_Message (Event, Data, Continue);

         if Continue then
            Object.On_Message (Event, Data);
         end if;
      end;

      Object.Flush_Buffer;

      Dispatch_Task_Objects.Delete_Dispatch_Task (I);
   exception
      when E : others =>
         Log ("Dispatch Error");
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end Dispatch_Task_Type;

   procedure Dispatch_Message (Message : in String) is
   begin
      if Message (Message.First) = 'S' then
         declare
            P1 : constant Integer := Index (Source => Message, Pattern => "|");

            UID    : constant String := Message.Slice (Message.First + 1, (P1 - 1));
            Result : constant String := Message.Slice ((P1 + 1), Message.Last);
         begin
            Script_Manager.Release_Hold (Value (UID), Result);
         end;
      else
         declare
            P1 : constant Integer := Index (Source => Message, Pattern => "|");

            P2 : constant Integer := Index (Source => Message, Pattern => "|", From => P1 + 1);

            UID        : constant String := Message.Slice (Message.First, (P1 - 1));
            Event      : constant String := Message.Slice ((P1 + 1), (P2 - 1));
            Event_Data : constant String := Message.Slice ((P2 + 1), Message.Last);

            Object : constant Gnoga.Gui.Base.Pointer_To_Base_Class := Object_Manager.Get_Object (Value (UID));

            New_ID : Gnoga.Types.Unique_ID;
         begin
            New_Unique_ID (New_ID);

            Dispatch_Task_Objects.Add_Dispatch_Task (New_ID, new Dispatch_Task_Type (Object));
            Dispatch_Task_Objects.Object (New_ID).Start (Event, Event_Data, New_ID);
         end;
      end if;
   exception
      when E : No_Object =>
         Log ("Request to dispatch message to non-existant object");
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
         return;
      when E : others =>
         Log ("Dispatch Message Error");
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end Dispatch_Message;

   -------------------
   -- String_Buffer --
   -------------------

   protected body String_Buffer is
      procedure Buffering (Value : Boolean) is
      begin
         Is_Buffering := Value;
      end Buffering;

      function Buffering return Boolean is
      begin
         return Is_Buffering;
      end Buffering;

      procedure Add (S : in String) is
         use type String;
      begin
         Buffer := Buffer & S;
      end Add;

      procedure Preface (S : in String) is
         use type String;
      begin
         Buffer := S & Buffer;
      end Preface;

      function Length return Natural is
      begin
         return Buffer.Length;
      end Length;

      function Get return String is
      begin
         return Buffer;
      end Get;

      procedure Get_And_Clear (S : out String) is
      begin
         S      := Buffer;
         Buffer := Null_UXString;
      end Get_And_Clear;

      procedure Clear is
      begin
         Buffer := Null_UXString;
      end Clear;
   end String_Buffer;

   ----------------
   -- Buffer_Add --
   ----------------

   function Buffer_Add
     (ID     : Gnoga.Types.Connection_ID;
      Script : String)
      return Boolean
   is
      Socket : constant Socket_Type := Connection_Manager.Connection_Socket (ID);
   begin
      if Socket.Content.Buffer.Buffering then
         if Socket.Content.Buffer.Length + Script.Length >= Max_Buffer_Length then
            Flush_Buffer (ID);
         end if;

         if Socket.Content.Connection_Type = WebSocket then
            Socket.Content.Buffer.Add (Script & Gnoga.Server.Connection.Common.CRLF);
         elsif Socket.Content.Connection_Type = Long_Polling then
            Socket.Content.Buffer.Add ("<script>" & Script & "</script>");
         else
            Gnoga.Log ("Buffer_Add called on unsupported connection type.");
         end if;

         return True;
      else
         return False;
      end if;
   end Buffer_Add;

   -----------------------
   -- Buffer_Connection --
   -----------------------

   function Buffer_Connection
     (ID : Gnoga.Types.Connection_ID)
      return Boolean
   is
      Socket : constant Socket_Type := Connection_Manager.Connection_Socket (ID);
   begin
      return Socket.Content.Buffer.Buffering;
   end Buffer_Connection;

   procedure Buffer_Connection
     (ID    : in Gnoga.Types.Connection_ID;
      Value : in Boolean)
   is
      Socket : constant Socket_Type := Connection_Manager.Connection_Socket (ID);
   begin
      if Value = False then
         Flush_Buffer (ID);
      end if;

      Socket.Content.Buffer.Buffering (Value);
   end Buffer_Connection;

   ------------------
   -- Flush_Buffer --
   ------------------

   procedure Flush_Buffer (ID : in Gnoga.Types.Connection_ID) is
      Socket : Socket_Type;
   begin
      if Connection_Manager.Valid (ID) then
         Socket := Connection_Manager.Connection_Socket (ID);
         if Socket.Content.Buffer.Buffering and Socket.Content.Connection_Type = WebSocket then
            Socket.Content.Buffer.Buffering (False);
            Execute_Script (ID, Socket.Content.Buffer.Get);
            Socket.Content.Buffer.Clear;
            Socket.Content.Buffer.Buffering (True);
         elsif Socket.Content.Connection_Type = Long_Polling then
            Socket.Unblock_Send;
         end if;
      end if;
   exception
      when E : Connection_Error =>
         --  Connection already closed.
         Log ("Connection ID " & Image (ID) & " already closed.");
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
      when E : others =>
         Log ("Flush_Buffer error on ID " & Image (ID));
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end Flush_Buffer;

   -------------------
   -- Buffer_Append --
   -------------------

   procedure Buffer_Append
     (ID    : in Gnoga.Types.Connection_ID;
      Value : in String)
   is
      Socket : constant Socket_Type := Connection_Manager.Connection_Socket (ID);
   begin
      Socket.Content.Buffer.Add (Value);
   end Buffer_Append;

   --------------------
   -- Execute_Script --
   --------------------

   procedure Execute_Script
     (ID     : in Gnoga.Types.Connection_ID;
      Script : in String)
   is
      procedure Try_Execute;

      procedure Try_Execute is
         Socket : constant Socket_Type := Connection_Manager.Connection_Socket (ID);
      begin
         if Socket.Content.Connection_Type = Long_Polling then
            Socket.Content.Buffer.Add ("<script>" & Script & "</script>");

            if not Socket.Content.Buffer.Buffering then
               Socket.Unblock_Send;
            end if;
         elsif Socket.Content.Connection_Type = WebSocket then
            Socket.WebSocket_Send (Standard.String (To_UTF_8 (Script)));
         end if;
      exception
         when E : Ada.Text_IO.End_Error =>
            Log ("Error Try_Execute ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
            raise Connection_Error with "Socket Closed before execute of : " & To_UTF_8 (Script);
         when E : others =>
            Log ("Error Try_Execute ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
            raise Connection_Error with "Socket Error during execute of : " & To_UTF_8 (Script);
      end Try_Execute;

   begin
      if Connection_Manager.Valid (ID) and Script /= "" then
         if not Buffer_Add (ID, Script) then
            Try_Execute;
         end if;
      end if;
   exception
      when E : others =>
         Log ("Error Execute_Script ID " & Image (ID));
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
         delay 2.0;
         Try_Execute;
   end Execute_Script;

   function Execute_Script
     (ID     : in Gnoga.Types.Connection_ID;
      Script : in String)
      return String
   is
      function Try_Execute return String;

      function Try_Execute return String is
         Script_Holder : aliased Script_Holder_Type;
      begin
         declare
            Script_ID : Gnoga.Types.Unique_ID;
            Socket    : constant Socket_Type := Connection_Manager.Connection_Socket (ID);
         begin
            Script_Manager.Add_Script_Holder (ID => Script_ID, Holder => Script_Holder'Unchecked_Access);

            declare
               Message : constant String :=
                 "ws.send (" & """S" & Image (Script_ID) & "|""+" & "eval (""" & Script & """)" & ");";
            begin
               if Socket.Content.Connection_Type = Long_Polling then
                  Socket.Content.Buffer.Add ("<script>" & Message & "</script>");
                  Socket.Unblock_Send;
               elsif Socket.Content.Connection_Type = WebSocket then
                  Socket.WebSocket_Send (Standard.String (To_UTF_8 (Message)));
               end if;

               select
                  delay Script_Time_Out; --  Timeout for browser answer

                  Script_Manager.Delete_Script_Holder (Script_ID);

                  raise Script_Error with "Timeout error, no browser response for: " & To_UTF_8 (Message);
               then abort
                  Script_Holder.Hold;
               end select;
            end;

            declare
               Result : constant String := Script_Holder.Result;
            begin
               Script_Manager.Delete_Script_Holder (Script_ID);

               return Result;
            end;
         end;
      exception
         when E : Ada.Text_IO.End_Error =>
            Log ("Error Try_Execute ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
            raise Connection_Error with "Socket Closed before execute of : " & To_UTF_8 (Script);
         when E : others =>
            Log ("Error Try_Execute ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
            raise Connection_Error with "Socket Error during execute of : " & To_UTF_8 (Script);
      end Try_Execute;
   begin
      begin
         if Connection_Manager.Valid (ID) then
            Flush_Buffer (ID);
            return Try_Execute;
         else
            raise Connection_Error with "Invalid ID " & To_ASCII (Image (ID));
         end if;
      exception
         when E : others =>
            Log ("Error Execute_Script ID " & Image (ID));
            Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
            begin
               delay 2.0;
               return Try_Execute;
            exception
               when E : others =>
                  Log ("Error Execute_Script after retrying ID " & Image (ID));
                  Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
                  Close (ID);
                  raise Connection_Error with "Invalid ID " & To_ASCII (Image (ID));
            end;
      end;
   end Execute_Script;

   ---------------------
   -- Connection_Data --
   ---------------------

   procedure Connection_Data
     (ID   : in Gnoga.Types.Connection_ID;
      Data :    access Gnoga.Types.Connection_Data_Type'Class)
   is
   begin
      Connection_Manager.Add_Connection_Data (ID, Gnoga.Types.Pointer_to_Connection_Data_Class (Data));
   end Connection_Data;

   function Connection_Data
     (ID : in Gnoga.Types.Connection_ID)
      return Gnoga.Types.Pointer_to_Connection_Data_Class
   is
   begin
      return Connection_Manager.Connection_Data (ID);
   end Connection_Data;

   ------------------------
   -- On_Connect_Handler --
   ------------------------

   procedure On_Connect_Handler (Event : in Connect_Event) is
   begin
      On_Connect_Event := Event;
   end On_Connect_Handler;

   ---------------------
   -- Connection_Type --
   ---------------------

   function Connection_Type
     (ID : Gnoga.Types.Connection_ID)
      return Gnoga_Connection_Type
   is
      Socket : constant Socket_Type := Connection_Manager.Connection_Socket (ID);
   begin
      return Socket.Content.Connection_Type;
   exception
      when E : Connection_Error =>
         Log ("Error Connection_Type on ID " & Image (ID));
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
         return None;
   end Connection_Type;

   ---------------------
   -- Connection_Path --
   ---------------------

   function Connection_Path
     (ID : Gnoga.Types.Connection_ID)
      return String
   is
      Socket : constant Socket_Type := Connection_Manager.Connection_Socket (ID);

      S : constant String := Socket.Content.Connection_Path;
   begin
      if Socket.Content.Connection_Type = Long_Polling then
         return S;
      else
         if S = "" then
            Socket.Content.Connection_Path := Left_Trim_Slashes (Execute_Script (ID, "window.location.pathname"));

            return Socket.Content.Connection_Path;
         else
            return S;
         end if;
      end if;
   exception
      when E : Connection_Error =>
         Log ("Error Connection_Path on ID " & Image (ID));
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
         return "";
   end Connection_Path;

   -------------------------------
   -- Connection_Client_Address --
   -------------------------------

   function Connection_Client_Address
     (ID : Gnoga.Types.Connection_ID)
      return String
   is
      Socket         : constant Socket_Type                 := Connection_Manager.Connection_Socket (ID);
      Client_Address : constant GNAT.Sockets.Sock_Addr_Type := Get_Client_Address (Socket.all);
   begin
      return From_UTF_8 (GNAT.Sockets.Image (Client_Address));
   exception
      when E : Connection_Error =>
         Log ("Error Connection_Client_Address on ID " & Image (ID));
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
         return "";
   end Connection_Client_Address;

   ------------------------
   -- Active_Connections --
   ------------------------

   function Active_Connections return Natural is
   begin
      return Natural (Connection_Manager.Active_Connections);
   end Active_Connections;

   -----------------------------
   -- On_Post_Request_Handler --
   -----------------------------

   procedure On_Post_Request_Handler (Event : Post_Request_Event) is
   begin
      On_Post_Request_Event := Event;
   end On_Post_Request_Handler;

   ---------------------
   -- On_Post_Handler --
   ---------------------

   procedure On_Post_Handler (Event : in Post_Event) is
   begin
      On_Post_Event := Event;
   end On_Post_Handler;

   --------------------------
   -- On_Post_File_Handler --
   --------------------------

   procedure On_Post_File_Handler (Event : in Post_File_Event) is
   begin
      On_Post_File_Event := Event;
   end On_Post_File_Handler;

   --------------------
   -- Form_Parameter --
   --------------------

   function Form_Parameter
     (ID   : Gnoga.Types.Connection_ID;
      Name : String)
      return String
   is
   begin
      return Execute_Script (ID, "params['" & Name & "'];");
   end Form_Parameter;

   -----------
   -- Valid --
   -----------

   function Valid
     (ID : Gnoga.Types.Connection_ID)
      return Boolean
   is
   begin
      if ID = Gnoga.Types.No_Connection then
         return False;
      else
         return Connection_Manager.Valid (ID);
      end if;
   end Valid;

   -----------
   -- Close --
   -----------

   procedure Close (ID : Gnoga.Types.Connection_ID) is
   begin
      if Valid (ID) then
         declare
            Socket : constant Socket_Type := Connection_Manager.Connection_Socket (ID);
         begin
            if Socket.Content.Connection_Type = Long_Polling then
               Socket.Content.Finalized := True;
            else
               Execute_Script (ID, "ws.close()");
            end if;
         exception
            when E : others =>
               Log ("Error Close on ID " & Image (ID));
               Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
         end;
      end if;
   end Close;

   -------------------
   -- HTML_On_Close --
   -------------------

   procedure HTML_On_Close
     (ID   : in Gnoga.Types.Connection_ID;
      HTML : in String)
   is
   begin
      Execute_Script (ID => ID, Script => "gnoga['html_on_close']='" & Escape_Quotes (HTML) & "';");
   end HTML_On_Close;

   ---------------------
   -- ID_Machine_Type --
   ---------------------

   protected type ID_Machine_Type is
      procedure Next_ID (ID : out Gnoga.Types.Unique_ID);
   private
      Current_ID : Gnoga.Types.Unique_ID := 0;
   end ID_Machine_Type;

   protected body ID_Machine_Type is
      procedure Next_ID (ID : out Gnoga.Types.Unique_ID) is
      begin
         Current_ID := Current_ID + 1;
         ID         := Current_ID;
      end Next_ID;
   end ID_Machine_Type;

   ID_Machine : ID_Machine_Type;

   -------------------
   -- New_Unique_ID --
   -------------------

   procedure New_Unique_ID (New_ID : out Gnoga.Types.Unique_ID) is
   begin
      ID_Machine.Next_ID (New_ID);
   end New_Unique_ID;

   -------------
   -- New_GID --
   -------------

   function New_GID return String is
      New_ID : Gnoga.Types.Unique_ID;
   begin
      New_Unique_ID (New_ID);

      return "g" & Image (New_ID);
   end New_GID;

   --------------------------
   -- Add_To_Message_Queue --
   --------------------------

   procedure Add_To_Message_Queue (Object : in out Gnoga.Gui.Base.Base_Type'Class) is
   begin
      Object_Manager.Insert (Object.Unique_ID, Object'Unchecked_Access);
   end Add_To_Message_Queue;

   -------------------------------
   -- Delete_From_Message_Queue --
   -------------------------------

   procedure Delete_From_Message_Queue (Object : in out Gnoga.Gui.Base.Base_Type'Class) is
   begin
      Object_Manager.Delete (Object.Unique_ID);
   end Delete_From_Message_Queue;

   ----------
   -- Stop --
   ----------

   procedure Stop is
      ID : Gnoga.Types.Connection_ID;
      procedure Free is new Ada.Unchecked_Deallocation (Watchdog_Type, Watchdog_Access);
      procedure Free is new Ada.Unchecked_Deallocation (Gnoga_HTTP_Server_Type, Gnoga_HTTP_Server_Access);
   begin
      if not Exit_Application_Requested and Watchdog /= null and Gnoga_HTTP_Server /= null then
         Exit_Application_Requested := True;
         Watchdog.Stop;
         Free (Watchdog);

         Connection_Manager.First (ID);
         while ID /= 0 loop
            begin
               Close (ID);
               Connection_Manager.Next (ID);
            exception
               when others =>
                  Connection_Manager.First (ID);
            end;
         end loop;

         Connection_Manager.Delete_All_Connections;

         Gnoga_HTTP_Server.Stop;
         Free (Gnoga_HTTP_Server);
      end if;
   end Stop;

   -----------
   -- Write --
   -----------

   procedure Write
     (Stream :    access Ada.Streams.Root_Stream_Type'Class;
      Item   : in Gnoga_HTTP_Content)
   is
   begin
      null;
   end Write;

   ---------
   -- Get --
   ---------

   overriding function Get
     (Source : access Gnoga_HTTP_Content)
      return Standard.String
   is
   begin
      if Source.Buffer.Length = 0 then
         if Source.Connection_Type = HTTP then
            return "";
         elsif Source.Finalized then
            declare
               ID : constant Gnoga.Types.Connection_ID := Connection_Manager.Find_Connection_ID (Source.Socket);
            begin
               Gnoga.Log ("Shutting down long polling connection ID " & Image (ID));
               return "";
            end;
         else
            raise Content_Not_Ready;
         end if;
      else
         declare
            Chunk_Size : constant := Max_HTTP_Output_Chunk - 80;

            S : String;
         begin
            Source.Buffer.Get_And_Clear (S);

            if Length (S) > Chunk_Size then
               Source.Buffer.Preface (Slice (Source => S, Low => 1 + Chunk_Size, High => Length (S)));

               return Standard.String (To_UTF_8 (Slice (Source => S, Low => 1, High => Chunk_Size)));
            else
               return Standard.String (To_UTF_8 (S));
            end if;
         end;
      end if;
   end Get;

   --------------
   -- Finalize --
   --------------

   overriding procedure Finalize (Client : in out Gnoga_HTTP_Client) is
      ID : constant Gnoga.Types.Connection_ID := Connection_Manager.Find_Connection_ID (Client'Unchecked_Access);
   begin
      if Ada.Streams.Stream_IO.Is_Open (Client.Content.FS) then
         Ada.Streams.Stream_IO.Close (Client.Content.FS);
      end if;

      if ID /= Gnoga.Types.No_Connection then
         Gnoga.Log ("Deleting connection during finalize ID " & Image (ID));
         Connection_Manager.Delete_Connection (ID);
      end if;

      HTTP_Client (Client).Finalize;
   exception
      when E : others =>
         Log ("Error Finalize Gnoga_HTTP_Client ID " & Image (ID));
         Log (From_UTF_8 (Ada.Exceptions.Exception_Information (E)));
   end Finalize;
begin
   Gnoga.Server.Connection.Common.Gnoga_Client_Factory := Global_Gnoga_Client_Factory'Access;
end Gnoga.Server.Connection;