This file is indexed.

/usr/share/perl5/XML/Stream.pm is in libxml-stream-perl 1.24-2+deb9u1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
##############################################################################
#
#  This library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Library General Public
#  License as published by the Free Software Foundation; either
#  version 2 of the License, 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.  See the GNU
#  Library General Public License for more details.
#
#  You should have received a copy of the GNU Library General Public
#  License along with this library; if not, write to the
#  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#  Boston, MA  02111-1307, USA.
#
#  Jabber
#  Copyright (C) 1998-2004 Jabber Software Foundation http://jabber.org/
#
##############################################################################

package XML::Stream;

=head1 NAME

XML::Stream - Creates an XML Stream connection and parses return data

=head1 SYNOPSIS

XML::Stream is an attempt at solidifying the use of XML via streaming.

=head1 DESCRIPTION

This module provides the user with methods to connect to a remote
server, send a stream of XML to the server, and receive/parse an XML
stream from the server.  It is primarily based work for the Etherx XML
router developed by the Jabber Development Team.  For more information
about this project visit http://xmpp.org/protocols/streams/.

XML::Stream gives the user the ability to define a central callback
that will be used to handle the tags received from the server.  These
tags are passed in the format defined at instantiation time.
the closing tag of an object is seen, the tree is finished and passed
to the call back function.  What the user does with it from there is up
to them.

For a detailed description of how this module works, and about the data
structure that it returns, please view the source of Stream.pm and
look at the detailed description at the end of the file.


NOTE: The parser that XML::Stream::Parser provides, as are most Perl
parsers, is synchronous.  If you are in the middle of parsing a
packet and call a user defined callback, the Parser is blocked until
your callback finishes.  This means you cannot be operating on a
packet, send out another packet and wait for a response to that packet.
It will never get to you.  Threading might solve this, but as we all
know threading in Perl is not quite up to par yet.  This issue will be
revisted in the future.

=head1 METHODS

=cut

use 5.008;
use strict;
use warnings;

use Sys::Hostname;
use IO::Socket;
use IO::Select;
use FileHandle;
use Carp;
use POSIX;
use Authen::SASL;
use MIME::Base64;
use utf8;
use Encode;
use Scalar::Util qw(weaken);

use XML::Stream::IO::Select::Win32;
use XML::Stream::Tools;

$SIG{PIPE} = "IGNORE";

use vars qw($VERSION $PAC $SSL $NONBLOCKING %HANDLERS $NETDNS %XMLNS );

##############################################################################
# Define the namespaces in an easy/constant manner.
#-----------------------------------------------------------------------------
# 0.9
#-----------------------------------------------------------------------------
$XMLNS{'stream'}        = "http://etherx.jabber.org/streams";

#-----------------------------------------------------------------------------
# 1.0
#-----------------------------------------------------------------------------
$XMLNS{'xmppstreams'}   = "urn:ietf:params:xml:ns:xmpp-streams";
$XMLNS{'xmpp-bind'}     = "urn:ietf:params:xml:ns:xmpp-bind";
$XMLNS{'xmpp-sasl'}     = "urn:ietf:params:xml:ns:xmpp-sasl";
$XMLNS{'xmpp-session'}  = "urn:ietf:params:xml:ns:xmpp-session";
$XMLNS{'xmpp-tls'}      = "urn:ietf:params:xml:ns:xmpp-tls";
##############################################################################


if (eval "require Net::DNS;" )
{
    require Net::DNS;
    import Net::DNS;
    $NETDNS = 1;
}
else
{
    $NETDNS = 0;
}


$VERSION = "1.24";
$NONBLOCKING = 0;

#use XML::Stream::Namespace;
use XML::Stream::Parser;
use XML::Stream::XPath;

##############################################################################
#
# Setup the exportable objects
#
##############################################################################
my @EXPORT_OK = qw(Tree Node);

sub import
{
    my $class = shift;

    foreach my $module (@_)
    {
        eval "use XML::Stream::$module;";
        die($@) if ($@);

        my $lc = lc($module);
        
        eval("\$HANDLERS{\$lc}->{startElement} = \\&XML::Stream::${module}::_handle_element;");
        eval("\$HANDLERS{\$lc}->{endElement}   = \\&XML::Stream::${module}::_handle_close;");
        eval("\$HANDLERS{\$lc}->{characters}   = \\&XML::Stream::${module}::_handle_cdata;");
    }
}

=pod

=head2 new


  new(
      debug      => string,
      debugfh    => FileHandle,
      debuglevel => 0|1|N,
      debugtime  => 0|1,
      style      => string)

Creates the XML::Stream object.
B<debug> should be set to the path for the debug log
to be written.  If set to "stdout" then the
debug will go there. Also, you can specify
a filehandle that already exists by using
B<debugfh>.

B<debuglevel> determines the amount of debug to generate.
0 is the least, 1 is a little more, N is the limit you want.

B<debugtime> determines wether a timestamp should be preappended
to the entry.
B<style> defines the way the data structure is
returned.  The two available styles are:

  tree - L<XML::Parser> Tree format
  node - L<XML::Stream::Node> format

For more information see the respective man pages.

=cut
 
sub new
{
    my $proto = shift;
    my $self = { };

    bless($self,$proto);

    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    $self->{DATASTYLE} = "tree";
    $self->{DATASTYLE} = delete($args{style}) if exists($args{style});

    if ((($self->{DATASTYLE} eq "tree") && !defined($XML::Stream::Tree::LOADED)) ||
        (($self->{DATASTYLE} eq "node") && !defined($XML::Stream::Node::LOADED))
       )
    {
        croak( qq{The style that you have chosen was not defined when you "use"d the module.\n} );
    }

    $self->{DEBUGARGS} = \%args;
    XML::Stream::Tools::setup_debug($self, %args); 

    my $hostname = hostname();
    my $address = gethostbyname($hostname) ||
        die("Cannot resolve $hostname: $!");
    my $fullname = gethostbyaddr($address,AF_INET) || $hostname;

    $self->debug(1,"new: hostname = ($fullname)");

    #---------------------------------------------------------------------------
    # Setup the defaults that the module will work with.
    #---------------------------------------------------------------------------
    $self->{SIDS}->{default}->{hostname} = "";
    $self->{SIDS}->{default}->{port} = "";
    $self->{SIDS}->{default}->{sock} = 0;
    $self->{SIDS}->{default}->{ssl} = 0;
    $self->{SIDS}->{default}->{_tls} = 0;
    $self->{SIDS}->{default}->{ssl_verify} = 0x01; # verify peer by default
    $self->{SIDS}->{default}->{ssl_ca_path} = '/etc/ssl/certs';
    $self->{SIDS}->{default}->{namespace} = "";
    $self->{SIDS}->{default}->{myhostname} = $fullname;
    $self->{SIDS}->{default}->{derivedhostname} = $fullname;
    $self->{SIDS}->{default}->{id} = "";

    #---------------------------------------------------------------------------
    # We are only going to use one callback, let the user call other callbacks
    # on his own.
    #---------------------------------------------------------------------------
    my $weak = $self;
    weaken $weak;
    $self->SetCallBacks(node=>sub { $weak->_node(@_) });

    weaken $self->{CB} if $self->{CB};

    $self->{IDCOUNT} = 0;

    return $self;
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Incoming Connection Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 Listen

Starts the stream by listening on a port for someone to connect,
and send the opening stream tag, and then sending a response based
on if the received header was correct for this stream.  Server
name, port, and namespace are required otherwise we don't know
where to listen and what namespace to accept.

=cut

sub Listen
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    my $serverid = "server$args{port}";

    return if exists($self->{SIDS}->{$serverid});

    push(@{$self->{SIDS}->{server}},$serverid);

    foreach my $key (keys(%{$self->{SIDS}->{default}}))
    {
        $self->{SIDS}->{$serverid}->{$key} = $self->{SIDS}->{default}->{$key};
    }

    foreach my $key (keys(%args))
    {
        $self->{SIDS}->{$serverid}->{$key} = $args{$key};
    }

    $self->debug(1,"Listen: start");

    if ($self->{SIDS}->{$serverid}->{namespace} eq "")
    {
        $self->SetErrorCode($serverid,"Namespace not specified");
        return;
    }

    #---------------------------------------------------------------------------
    # Check some things that we have to know in order get the connection up
    # and running.  Server hostname, port number, namespace, etc...
    #---------------------------------------------------------------------------
    if ($self->{SIDS}->{$serverid}->{hostname} eq "")
    {
        $self->SetErrorCode("$serverid","Server hostname not specified");
        return;
    }
    if ($self->{SIDS}->{$serverid}->{port} eq "")
    {
        $self->SetErrorCode("$serverid","Server port not specified");
        return;
    }
    if ($self->{SIDS}->{$serverid}->{myhostname} eq "")
    {
        $self->{SIDS}->{$serverid}->{myhostname} = $self->{SIDS}->{$serverid}->{derivedhostname};
    }

    #-------------------------------------------------------------------------
    # Open the connection to the listed server and port.  If that fails then
    # abort ourselves and let the user check $! on his own.
    #-------------------------------------------------------------------------

    while($self->{SIDS}->{$serverid}->{sock} == 0)
    {
        $self->{SIDS}->{$serverid}->{sock} =
            IO::Socket::INET->new(LocalHost=>$self->{SIDS}->{$serverid}->{hostname},
                                 LocalPort=>$self->{SIDS}->{$serverid}->{port},
                                 Reuse=>1,
                                 Listen=>10,
                                 Proto=>'tcp');
        select(undef,undef,undef,.1);
    }
    $self->{SIDS}->{$serverid}->{status} = 1;
    $self->nonblock($self->{SIDS}->{$serverid}->{sock});
    $self->{SIDS}->{$serverid}->{sock}->autoflush(1);

    $self->{SELECT} =
        IO::Select->new($self->{SIDS}->{$serverid}->{sock});
    $self->{SIDS}->{$serverid}->{select} =
        IO::Select->new($self->{SIDS}->{$serverid}->{sock});

    $self->{SOCKETS}->{$self->{SIDS}->{$serverid}->{sock}} = "$serverid";

    return $serverid;
}


##############################################################################

=pod

=head2 ConnectionAccept

Accept an incoming connection.

=cut

sub ConnectionAccept
{
    my $self = shift;
    my $serverid = shift;

    my $sid = $self->NewSID();

    $self->debug(1,"ConnectionAccept: sid($sid)");

    $self->{SIDS}->{$sid}->{sock} = $self->{SIDS}->{$serverid}->{sock}->accept();

    $self->nonblock($self->{SIDS}->{$sid}->{sock});
    $self->{SIDS}->{$sid}->{sock}->autoflush(1);

    $self->debug(3,"ConnectionAccept: sid($sid) client($self->{SIDS}->{$sid}->{sock}) server($self->{SIDS}->{$serverid}->{sock})");

    $self->{SELECT}->add($self->{SIDS}->{$sid}->{sock});

    #-------------------------------------------------------------------------
    # Create the XML::Stream::Parser and register our callbacks
    #-------------------------------------------------------------------------
    my $weak = $self;
    weaken $weak;
    $self->{SIDS}->{$sid}->{parser} =
        XML::Stream::Parser->new(%{$self->{DEBUGARGS}},
                                nonblocking=>$NONBLOCKING,
                                sid=>$sid,
                                style=>$self->{DATASTYLE},
                                Handlers=>{
                                    startElement=>sub{ $weak->_handle_root(@_) },
                                    endElement=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{endElement}}($weak,@_) },
                                    characters=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{characters}}($weak,@_) },
                                }
                               );

    $self->{SIDS}->{$sid}->{select} =
        IO::Select->new($self->{SIDS}->{$sid}->{sock});
    $self->{SIDS}->{$sid}->{connectiontype} = "tcpip";
    $self->{SOCKETS}->{$self->{SIDS}->{$sid}->{sock}} = $sid;

    $self->InitConnection($sid,$serverid);

    #---------------------------------------------------------------------------
    # Grab the init time so that we can check if we get data in the timeout
    # period or not.
    #---------------------------------------------------------------------------
    $self->{SIDS}->{$sid}->{activitytimeout} = time;

    return $sid;
}


##############################################################################

=pod

=head2 Respond

If this is a listening socket then we need to respond to the
opening <stream:stream/>.

=cut

sub Respond
{
    my $self = shift;
    my $sid = shift;
    my $serverid = $self->{SIDS}->{$sid}->{serverid};

    my $root = $self->GetRoot($sid);
    
    if ($root->{xmlns} ne $self->{SIDS}->{$serverid}->{namespace})
    {
        my $error = $self->StreamError($sid,"invalid-namespace","Invalid namespace specified");
        $self->Send($sid,$error);

        $self->{SIDS}->{$sid}->{sock}->flush();
        select(undef,undef,undef,1);
        $self->Disconnect($sid);
    }

    #---------------------------------------------------------------------------
    # Next, we build the opening handshake.
    #---------------------------------------------------------------------------
    my %stream_args;

    $stream_args{from} =
        (exists($self->{SIDS}->{$serverid}->{from}) ?
         $self->{SIDS}->{$serverid}->{from} :
         $self->{SIDS}->{$serverid}->{hostname}
        );

    $stream_args{to} = $self->GetRoot($sid)->{from};
    $stream_args{id} = $sid;
    $stream_args{namespaces} = $self->{SIDS}->{$serverid}->{namespaces};

    my $stream =
        $self->StreamHeader(
            xmlns=>$self->{SIDS}->{$serverid}->{namespace},
            xmllang=>"en",
            %stream_args
        );

    #---------------------------------------------------------------------------
    # Then we send the opening handshake.
    #---------------------------------------------------------------------------
    $self->Send($sid,$stream);
    delete($self->{SIDS}->{$sid}->{activitytimeout});
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Outgoing Connection Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 Connect

Starts the stream by connecting to the server, sending the opening
stream tag, and then waiting for a response and verifying that it
is correct for this stream.  Server name, port, and namespace are
required otherwise we don't know where to send the stream to...

  Connect(hostname=>string,       
          port=>integer, 
          to=>string,             
          from=>string,           
          myhostname=>string,     
          namespace=>string,      
          namespaces=>array,      
          connectiontype=>string, 
          ssl=>0|1,
          ssl_verify =>0x00|0x01|0x02|0x04,
          ssl_ca_path=>string,
          srv=>string)

Opens a tcp connection to the
specified server and sends the proper
opening XML Stream tag.  C<hostname>,
C<port>, and C<namespace> are required.
namespaces allows you to use
XML::Stream::Namespace objects.

C<to> is needed if you want the stream
to attribute to be something other
than the hostname you are connecting
to.

C<from> is needed if you want the
stream from attribute to be something
other than the hostname you are
connecting from.

C<myhostname> should
not be needed but if the module
cannot determine your hostname
properly (check the debug log), set
this to the correct value, or if you
want the other side of the  stream to
think that you are someone else.  The
type determines the kind of
connection that is made:

  "tcpip"    - TCP/IP (default)
  "stdinout" - STDIN/STDOUT
  "http"     - HTTP

HTTP recognizes proxies if the ENV
variables http_proxy or https_proxy
are set.

C<ssl> specifies whether an SSL socket
should be used for encrypted co-
mmunications.

C<ssl_verify> determines whether peer
certificate verification takes place.
See the documentation for the
SSL_verify_mode parameter to
L<IO::Socket::SSL->new()|IO::Socket::SSL>.
The default value is 0x01 causing the
server certificate to be verified, and
requiring that ssl_ca_path be set.

C<ssl_ca_path> should be set to the path to
either a directory containing hashed CA
certificates, or a single file containing
acceptable CA certifictes concatenated
together. This parameter is required if
ssl_verify is set to anything other than
0x00 (no verification).

If srv is specified AND Net::DNS is
installed and can be loaded, then
an SRV query is sent to srv.hostname
and the results processed to replace
the hostname and port.  If the lookup
fails, or Net::DNS cannot be loaded,
then hostname and port are left alone
as the defaults.

This function returns the same hash from GetRoot()
below. Make sure you get the SID
(Session ID) since you have to use it
to call most other functions in here.

=cut

sub Connect
{
    my $self = shift;

    foreach my $key (keys(%{$self->{SIDS}->{default}}))
    {
        $self->{SIDS}->{newconnection}->{$key} = $self->{SIDS}->{default}->{$key};
    }
    while($#_ >= 0) { $self->{SIDS}->{newconnection}->{ lc pop(@_) } = pop(@_); }
    
    my $timeout = exists($self->{SIDS}->{newconnection}->{timeout}) ?
                  delete($self->{SIDS}->{newconnection}->{timeout}) :
                  "";

    $self->debug(4,"Connect: timeout($timeout)");
    

    if (exists($self->{SIDS}->{newconnection}->{srv}))
    {
        $self->debug(1,"Connect: srv requested");
        if ($NETDNS)
        {
            my $res = Net::DNS::Resolver->new();
            my $query = $res->query($self->{SIDS}->{newconnection}->{srv}.".".$self->{SIDS}->{newconnection}->{hostname},"SRV");
            
            if ($query)
            { 
                $self->{SIDS}->{newconnection}->{hostname} = ($query->answer)[0]->target();
                $self->{SIDS}->{newconnection}->{port} = ($query->answer)[0]->port();
                $self->debug(1,"Connect: srv host: $self->{SIDS}->{newconnection}->{hostname}");
                $self->debug(1,"Connect: srv post: $self->{SIDS}->{newconnection}->{port}");
            }
            else
            {
                $self->debug(1,"Connect: srv query failed");
            }
        }
        else
        {
            $self->debug(1,"Connect: srv query failed");
        }
        delete($self->{SIDS}->{newconnection}->{srv});
    }

    $self->{SIDS}->{newconnection}->{connectiontype} = "tcpip"
        unless exists($self->{SIDS}->{newconnection}->{connectiontype});

    $self->debug(1,"Connect: type($self->{SIDS}->{newconnection}->{connectiontype})");

    if ($self->{SIDS}->{newconnection}->{namespace} eq "")
    {
        $self->SetErrorCode("newconnection","Namespace not specified");
        return;
    }

    # Set ssl_params for newconnection ssl or tls is set
    if (   1 == $self->{SIDS}->{newconnection}->{ssl}
        || 1 == $self->{SIDS}->{newconnection}->{_tls} )
    {
        my %ssl_params = (
            SSL_verify_mode => $self->{SIDS}->{newconnection}->{ssl_verify},
        );

        if ( 0x00 != $self->{SIDS}->{newconnection}->{ssl_verify} )
        {
            die ("Invalid or unreadable path specified for ssl_ca_path.")
                unless -e -r $self->{SIDS}->{newconnection}->{ssl_ca_path};

            if (-f $self->{SIDS}->{newconnection}->{ssl_ca_path} )
            {
                $ssl_params{'SSL_ca_file'} = $self->{SIDS}->{newconnection}->{ssl_ca_path};
            }
            else
            {
                $ssl_params{'SSL_ca_path'} = $self->{SIDS}->{newconnection}->{ssl_ca_path};
            }
        }

        $self->{SIDS}->{newconnection}->{ssl_params} = \%ssl_params;
    }

    #---------------------------------------------------------------------------
    # TCP/IP
    #---------------------------------------------------------------------------
    if ($self->{SIDS}->{newconnection}->{connectiontype} eq "tcpip")
    {
        #-----------------------------------------------------------------------
        # Check some things that we have to know in order get the connection up
        # and running.  Server hostname, port number, namespace, etc...
        #-----------------------------------------------------------------------
        if ($self->{SIDS}->{newconnection}->{hostname} eq "")
        {
            $self->SetErrorCode("newconnection","Server hostname not specified");
            return;
        }
        if ($self->{SIDS}->{newconnection}->{port} eq "")
        {
            $self->SetErrorCode("newconnection","Server port not specified");
            return;
        }
        if ($self->{SIDS}->{newconnection}->{myhostname} eq "")
        {
            $self->{SIDS}->{newconnection}->{myhostname} = $self->{SIDS}->{newconnection}->{derivedhostname};
        }

        #-----------------------------------------------------------------------
        # Open the connection to the listed server and port.  If that fails then
        # abort ourselves and let the user check $! on his own.
        #-----------------------------------------------------------------------
        $self->{SIDS}->{newconnection}->{sock} =
            IO::Socket::INET->new(PeerAddr=>$self->{SIDS}->{newconnection}->{hostname},
                                 PeerPort=>$self->{SIDS}->{newconnection}->{port},
                                 Proto=>"tcp",
                                 (($timeout ne "") ? ( Timeout=>$timeout ) : ()),
                                );
        return unless $self->{SIDS}->{newconnection}->{sock};

        if ($self->{SIDS}->{newconnection}->{ssl} == 1)
        {
            $self->debug(1,"Connect: Convert normal socket to SSL");
            $self->debug(1,"Connect: sock($self->{SIDS}->{newconnection}->{sock})");
            $self->LoadSSL();

            $self->{SIDS}->{newconnection}->{sock} = IO::Socket::SSL::socketToSSL(
                    $self->{SIDS}->{newconnection}->{sock},
                    $self->{SIDS}->{newconnection}->{ssl_params}
            );
            $self->debug(1,"Connect: ssl_sock($self->{SIDS}->{newconnection}->{sock})");
            $self->debug(1,"Connect: SSL: We are secure") if ($self->{SIDS}->{newconnection}->{sock});
        }
        return unless $self->{SIDS}->{newconnection}->{sock};
    }

    #---------------------------------------------------------------------------
    # STDIN/OUT
    #---------------------------------------------------------------------------
    if ($self->{SIDS}->{newconnection}->{connectiontype} eq "stdinout")
    {
        $self->{SIDS}->{newconnection}->{sock} =
            FileHandle->new(">&STDOUT");
    }  

    #---------------------------------------------------------------------------
    # HTTP
    #---------------------------------------------------------------------------
    if ($self->{SIDS}->{newconnection}->{connectiontype} eq "http")
    {
        #-----------------------------------------------------------------------
        # Check some things that we have to know in order get the connection up
        # and running.  Server hostname, port number, namespace, etc...
        #-----------------------------------------------------------------------
        if ($self->{SIDS}->{newconnection}->{hostname} eq "")
        {
            $self->SetErrorCode("newconnection","Server hostname not specified");
            return;
        }
        if ($self->{SIDS}->{newconnection}->{port} eq "")
        {
            $self->SetErrorCode("newconnection","Server port not specified");
            return;
        }
        if ($self->{SIDS}->{newconnection}->{myhostname} eq "")
        {
            $self->{SIDS}->{newconnection}->{myhostname} = $self->{SIDS}->{newconnection}->{derivedhostname};
        }

        if (!defined($PAC))
        {
            eval("use HTTP::ProxyAutoConfig;");
            if ($@)
            {
                $PAC = 0;
            }
            else
            {
                require HTTP::ProxyAutoConfig;
                $PAC = HTTP::ProxyAutoConfig->new();
            }
        }

        if ($PAC eq "0") {
            if (exists($ENV{"http_proxy"}))
            {
                my($host,$port) = ($ENV{"http_proxy"} =~ /^(\S+)\:(\d+)$/);
                $self->{SIDS}->{newconnection}->{httpproxyhostname} = $host;
                $self->{SIDS}->{newconnection}->{httpproxyport} = $port;
                $self->{SIDS}->{newconnection}->{httpproxyhostname} =~ s/^http\:\/\///;
            }
            if (exists($ENV{"https_proxy"}))
            {
                my($host,$port) = ($ENV{"https_proxy"} =~ /^(\S+)\:(\d+)$/);
                $self->{SIDS}->{newconnection}->{httpsproxyhostname} = $host;
                $self->{SIDS}->{newconnection}->{httpsproxyport} = $port;
                $self->{SIDS}->{newconnection}->{httpsproxyhostname} =~ s/^https?\:\/\///;
            }
        }
        else
        {
            my $proxy = $PAC->FindProxy("http://".$self->{SIDS}->{newconnection}->{hostname});
            if ($proxy ne "DIRECT")
            {
                ($self->{SIDS}->{newconnection}->{httpproxyhostname},$self->{SIDS}->{newconnection}->{httpproxyport}) = ($proxy =~ /^PROXY ([^:]+):(\d+)$/);
            }

            $proxy = $PAC->FindProxy("https://".$self->{SIDS}->{newconnection}->{hostname});

            if ($proxy ne "DIRECT")
            {
                ($self->{SIDS}->{newconnection}->{httpsproxyhostname},$self->{SIDS}->{newconnection}->{httpsproxyport}) = ($proxy =~ /^PROXY ([^:]+):(\d+)$/);
            }
        }

        $self->debug(1,"Connect: http_proxy($self->{SIDS}->{newconnection}->{httpproxyhostname}:$self->{SIDS}->{newconnection}->{httpproxyport})")
            if (exists($self->{SIDS}->{newconnection}->{httpproxyhostname}) &&
                defined($self->{SIDS}->{newconnection}->{httpproxyhostname}) &&
                exists($self->{SIDS}->{newconnection}->{httpproxyport}) &&
                defined($self->{SIDS}->{newconnection}->{httpproxyport}));
        $self->debug(1,"Connect: https_proxy($self->{SIDS}->{newconnection}->{httpsproxyhostname}:$self->{SIDS}->{newconnection}->{httpsproxyport})")
            if (exists($self->{SIDS}->{newconnection}->{httpsproxyhostname}) &&
                defined($self->{SIDS}->{newconnection}->{httpsproxyhostname}) &&
                exists($self->{SIDS}->{newconnection}->{httpsproxyport}) &&
                defined($self->{SIDS}->{newconnection}->{httpsproxyport}));

        #-----------------------------------------------------------------------
        # Open the connection to the listed server and port.  If that fails then
        # abort ourselves and let the user check $! on his own.
        #-----------------------------------------------------------------------
        my $connect = "CONNECT $self->{SIDS}->{newconnection}->{hostname}:$self->{SIDS}->{newconnection}->{port} HTTP/1.1\r\nHost: $self->{SIDS}->{newconnection}->{hostname}\r\n\r\n";
        my $put = "PUT http://$self->{SIDS}->{newconnection}->{hostname}:$self->{SIDS}->{newconnection}->{port} HTTP/1.1\r\nHost: $self->{SIDS}->{newconnection}->{hostname}\r\nProxy-Connection: Keep-Alive\r\n\r\n";

        my $connected = 0;
        #-----------------------------------------------------------------------
        # Combo #0 - The user didn't specify a proxy
        #-----------------------------------------------------------------------
        if (!exists($self->{SIDS}->{newconnection}->{httpproxyhostname}) &&
            !exists($self->{SIDS}->{newconnection}->{httpsproxyhostname}))
        {

            $self->debug(1,"Connect: Combo #0: User did not specify a proxy... connecting DIRECT");

            $self->debug(1,"Connect: Combo #0: Create normal socket");
            $self->{SIDS}->{newconnection}->{sock} =
            IO::Socket::INET->new(PeerAddr=>$self->{SIDS}->{newconnection}->{hostname},
                                 PeerPort=>$self->{SIDS}->{newconnection}->{port},
                                 Proto=>"tcp",
                                 (($timeout ne "") ? ( Timeout=>$timeout ) : ()),
                                );
            $connected = defined($self->{SIDS}->{newconnection}->{sock});
            $self->debug(1,"Connect: Combo #0: connected($connected)");
            #            if ($connected)
            #            {
            #                $self->{SIDS}->{newconnection}->{sock}->syswrite($put,length($put),0);
            #                my $buff;
            #                $self->{SIDS}->{newconnection}->{sock}->sysread($buff,4*POSIX::BUFSIZ);
            #                my ($code) = ($buff =~ /^\S+\s+(\S+)\s+/);
            #                $self->debug(1,"Connect: Combo #1: buff($buff)");
            #                $connected = 0 if ($code !~ /2\d\d/);
            #            }
            #            $self->debug(1,"Connect: Combo #0: connected($connected)");
          }

        #-----------------------------------------------------------------------
        # Combo #1 - PUT through http_proxy
        #-----------------------------------------------------------------------
        if (!$connected &&
            exists($self->{SIDS}->{newconnection}->{httpproxyhostname}) &&
            ($self->{SIDS}->{newconnection}->{ssl} == 0))
        {

            $self->debug(1,"Connect: Combo #1: PUT through http_proxy");
            $self->{SIDS}->{newconnection}->{sock} =
                IO::Socket::INET->new(PeerAddr=>$self->{SIDS}->{newconnection}->{httpproxyhostname},
                                     PeerPort=>$self->{SIDS}->{newconnection}->{httpproxyport},
                                     Proto=>"tcp",
                                     (($timeout ne "") ? ( Timeout=>$timeout ) : ()),
                                    );
            $connected = defined($self->{SIDS}->{newconnection}->{sock});
            $self->debug(1,"Connect: Combo #1: connected($connected)");
            if ($connected)
            {
                $self->debug(1,"Connect: Combo #1: send($put)");
                $self->{SIDS}->{newconnection}->{sock}->syswrite($put,length($put),0);
                my $buff;
                $self->{SIDS}->{newconnection}->{sock}->sysread($buff,4*POSIX::BUFSIZ);
                my ($code) = ($buff =~ /^\S+\s+(\S+)\s+/);
                $self->debug(1,"Connect: Combo #1: buff($buff)");
                $connected = 0 if ($code !~ /2\d\d/);
            }
            $self->debug(1,"Connect: Combo #1: connected($connected)");
        }
        #-----------------------------------------------------------------------
        # Combo #2 - CONNECT through http_proxy
        #-----------------------------------------------------------------------
        if (!$connected &&
            exists($self->{SIDS}->{newconnection}->{httpproxyhostname}) &&
            ($self->{SIDS}->{newconnection}->{ssl} == 0))
        {

            $self->debug(1,"Connect: Combo #2: CONNECT through http_proxy");
            $self->{SIDS}->{newconnection}->{sock} =
                IO::Socket::INET->new(PeerAddr=>$self->{SIDS}->{newconnection}->{httpproxyhostname},
                                     PeerPort=>$self->{SIDS}->{newconnection}->{httpproxyport},
                                     Proto=>"tcp",
                                     (($timeout ne "") ? ( Timeout=>$timeout ) : ()),
                                    );
            $connected = defined($self->{SIDS}->{newconnection}->{sock});
            $self->debug(1,"Connect: Combo #2: connected($connected)");
            if ($connected)
            {
                $self->{SIDS}->{newconnection}->{sock}->syswrite($connect,length($connect),0);
                my $buff;
                $self->{SIDS}->{newconnection}->{sock}->sysread($buff,4*POSIX::BUFSIZ);
                my ($code) = ($buff =~ /^\S+\s+(\S+)\s+/);
                $self->debug(1,"Connect: Combo #2: buff($buff)");
                $connected = 0 if ($code !~ /2\d\d/);
            }
            $self->debug(1,"Connect: Combo #2: connected($connected)");
        }

        #-----------------------------------------------------------------------
        # Combo #3 - CONNECT through https_proxy
        #-----------------------------------------------------------------------
        if (!$connected &&
            exists($self->{SIDS}->{newconnection}->{httpsproxyhostname}))
        {
            $self->debug(1,"Connect: Combo #3: CONNECT through https_proxy");
            $self->{SIDS}->{newconnection}->{sock} =
                IO::Socket::INET->new(PeerAddr=>$self->{SIDS}->{newconnection}->{httpsproxyhostname},
                                     PeerPort=>$self->{SIDS}->{newconnection}->{httpsproxyport},
                                     Proto=>"tcp");
            $connected = defined($self->{SIDS}->{newconnection}->{sock});
            $self->debug(1,"Connect: Combo #3: connected($connected)");
            if ($connected)
            {
                $self->{SIDS}->{newconnection}->{sock}->syswrite($connect,length($connect),0);
                my $buff;
                $self->{SIDS}->{newconnection}->{sock}->sysread($buff,4*POSIX::BUFSIZ);
                my ($code) = ($buff =~ /^\S+\s+(\S+)\s+/);
                $self->debug(1,"Connect: Combo #3: buff($buff)");
                $connected = 0 if ($code !~ /2\d\d/);
            }
            $self->debug(1,"Connect: Combo #3: connected($connected)");
        }

        #-----------------------------------------------------------------------
        # We have failed
        #-----------------------------------------------------------------------
        if (!$connected)
        {
            $self->debug(1,"Connect: No connection... I have failed... I.. must... end it all...");
            $self->SetErrorCode("newconnection","Unable to open a connection to destination.  Please check your http_proxy and/or https_proxy environment variables.");
            return;
        }

        return unless $self->{SIDS}->{newconnection}->{sock};

        $self->debug(1,"Connect: We are connected");

        if (($self->{SIDS}->{newconnection}->{ssl} == 1) &&
            (ref($self->{SIDS}->{newconnection}->{sock}) eq "IO::Socket::INET"))
        {
            $self->debug(1,"Connect: Convert normal socket to SSL");
            $self->debug(1,"Connect: sock($self->{SIDS}->{newconnection}->{sock})");
            $self->LoadSSL();
            $self->{SIDS}->{newconnection}->{sock} = IO::Socket::SSL::socketToSSL(
                    $self->{SIDS}->{newconnection}->{sock},
                    $self->{SIDS}->{newconnection}->{ssl_params}
            );
            $self->debug(1,"Connect: ssl_sock($self->{SIDS}->{newconnection}->{sock})");
            $self->debug(1,"Connect: SSL: We are secure") if ($self->{SIDS}->{newconnection}->{sock});
        }
        return unless $self->{SIDS}->{newconnection}->{sock};
    }

    $self->debug(1,"Connect: Got a connection");

    $self->{SIDS}->{newconnection}->{sock}->autoflush(1);

    return $self->OpenStream("newconnection",$timeout);
}


##############################################################################

=pod

=head2 OpenStream

Send the opening stream and save the root element info.

=cut

sub OpenStream
{
    my $self = shift;
    my $currsid = shift;
    my $timeout = shift;
    $timeout = "" unless defined($timeout);

    $self->InitConnection($currsid,$currsid);

    #---------------------------------------------------------------------------
    # Next, we build the opening handshake.
    #---------------------------------------------------------------------------
    my %stream_args;
    
    if (($self->{SIDS}->{$currsid}->{connectiontype} eq "tcpip") ||
        ($self->{SIDS}->{$currsid}->{connectiontype} eq "http"))
    {
        $stream_args{to}= $self->{SIDS}->{$currsid}->{hostname}
            unless exists($self->{SIDS}->{$currsid}->{to});
        
        $stream_args{to} = $self->{SIDS}->{$currsid}->{to}
            if exists($self->{SIDS}->{$currsid}->{to});

        $stream_args{from} = $self->{SIDS}->{$currsid}->{myhostname}
            if (!exists($self->{SIDS}->{$currsid}->{from}) &&
                ($self->{SIDS}->{$currsid}->{myhostname} ne "")
               );
        
        $stream_args{from} = $self->{SIDS}->{$currsid}->{from}
            if exists($self->{SIDS}->{$currsid}->{from});
        
        $stream_args{id} = $self->{SIDS}->{$currsid}->{id}
            if (exists($self->{SIDS}->{$currsid}->{id}) &&
                ($self->{SIDS}->{$currsid}->{id} ne "")
               );

        $stream_args{namespaces} = $self->{SIDS}->{$currsid}->{namespaces};
    }
    
    my $stream =
        $self->StreamHeader(
            xmlns=>$self->{SIDS}->{$currsid}->{namespace},
            xmllang=>"en",
            %stream_args
        );

    #---------------------------------------------------------------------------
    # Create the XML::Stream::Parser and register our callbacks
    #---------------------------------------------------------------------------
    my $weak = $self;
    weaken $weak;
    $self->{SIDS}->{$currsid}->{parser} =
        XML::Stream::Parser->new(%{$self->{DEBUGARGS}},
                                nonblocking=>$NONBLOCKING,
                                sid=>$currsid,
                                style=>$self->{DATASTYLE},
                                Handlers=>{
                                    startElement=>sub{ $weak->_handle_root(@_) },
                                    endElement=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{endElement}}($weak, @_) },
                                    characters=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{characters}}($weak, @_) },
                                }
                               );

    $self->{SIDS}->{$currsid}->{select} =
        IO::Select->new($self->{SIDS}->{$currsid}->{sock});

    if (($self->{SIDS}->{$currsid}->{connectiontype} eq "tcpip") ||
            ($self->{SIDS}->{$currsid}->{connectiontype} eq "http"))
    {
        $self->{SELECT} = IO::Select->new($self->{SIDS}->{$currsid}->{sock});
        $self->{SOCKETS}->{$self->{SIDS}->{$currsid}->{sock}} = "newconnection";
    }

    if ($self->{SIDS}->{$currsid}->{connectiontype} eq "stdinout")
    {
        $self->{SELECT} = IO::Select->new(*STDIN);
        $self->{SOCKETS}->{$self->{SIDS}->{$currsid}->{sock}} = $currsid;
        $self->{SOCKETS}->{*STDIN} = $currsid;
        $self->{SIDS}->{$currsid}->{select}->add(*STDIN);
    }

    $self->{SIDS}->{$currsid}->{status} = 0;

    #---------------------------------------------------------------------------
    # Then we send the opening handshake.
    #---------------------------------------------------------------------------
    $self->Send($currsid,$stream) || return;

    #---------------------------------------------------------------------------
    # Before going on let's make sure that the server responded with a valid
    # root tag and that the stream is open.
    #---------------------------------------------------------------------------
    my $buff = "";
    my $timeEnd = ($timeout eq "") ? "" : time + $timeout;
    while($self->{SIDS}->{$currsid}->{status} == 0)
    {
        my $now = time;
        my $wait = (($timeEnd eq "") || ($timeEnd - $now > 10)) ? 10 :
                    $timeEnd - $now;

        $self->debug(5,"Connect: can_read(",join(",",$self->{SIDS}->{$currsid}->{select}->can_read(0)),")");
        if ($self->{SIDS}->{$currsid}->{select}->can_read($wait))
        {
            $self->{SIDS}->{$currsid}->{status} = -1
                unless defined($buff = $self->Read($currsid));
            return unless($self->{SIDS}->{$currsid}->{status} == 0);
            return unless($self->ParseStream($currsid,$buff) == 1);
        }
        else
        {
            if ($timeout ne "")
            {
                if (time >= $timeEnd)
                {
                    $self->SetErrorCode($currsid,"Timeout limit reached");
                    return;
                }
            }
        }

        return if($self->{SIDS}->{$currsid}->{select}->has_exception(0));
    }
    return if($self->{SIDS}->{$currsid}->{status} != 1);

    $self->debug(3,"Connect: status($self->{SIDS}->{$currsid}->{status})");

    my $sid = $self->GetRoot($currsid)->{id};
    $| = 1;
    foreach my $key (keys(%{$self->{SIDS}->{$currsid}}))
    {
        $self->{SIDS}->{$sid}->{$key} = $self->{SIDS}->{$currsid}->{$key};
    }
    $self->{SIDS}->{$sid}->{parser}->setSID($sid);

    if (($self->{SIDS}->{$sid}->{connectiontype} eq "tcpip") ||
        ($self->{SIDS}->{$sid}->{connectiontype} eq "http"))
    {
        $self->{SOCKETS}->{$self->{SIDS}->{$currsid}->{sock}} = $sid;
    }

    if ($self->{SIDS}->{$sid}->{connectiontype} eq "stdinout")
    {
        $self->{SOCKETS}->{$self->{SIDS}->{$currsid}->{sock}} = $sid;
        $self->{SOCKETS}->{*STDIN} = $sid;
    }

    delete($self->{SIDS}->{$currsid})
        unless $currsid eq $sid;

    if (exists($self->GetRoot($sid)->{version}) &&
        ($self->GetRoot($sid)->{version} ne ""))
    {
        while(!$self->ReceivedStreamFeatures($sid))
        {
            $self->Process(1);
        }
    }
        
    return $self->GetRoot($sid);
}


##############################################################################

=pod

=head2 OpenFile

Starts the stream by opening a file and setting it up so that
Process reads from the filehandle to get the incoming stream.

 OpenFile(string)

Opens a filehandle to the argument specified, and
pretends that it is a stream.  It will ignore the
outer tag, and not check if it was a
<stream:stream/>. This is useful for writing a
program that has to parse any XML file that is
basically made up of small packets (like RDF).

=cut

sub OpenFile
{
    my $self = shift;
    my $file = shift;

    $self->debug(1,"OpenFile: file($file)");

    $self->{SIDS}->{newconnection}->{connectiontype} = "file";

    $self->{SIDS}->{newconnection}->{sock} = FileHandle->new($file);
    $self->{SIDS}->{newconnection}->{sock}->autoflush(1);

    $self->RegisterPrefix("newconnection",&ConstXMLNS("stream"),"stream");

    #---------------------------------------------------------------------------
    # Create the XML::Stream::Parser and register our callbacks
    #---------------------------------------------------------------------------
    my $weak = $self;
    weaken $weak;
    $self->{SIDS}->{newconnection}->{parser} =
        XML::Stream::Parser->new(%{$self->{DEBUGARGS}},
                    nonblocking=>$NONBLOCKING,
                    sid=>"newconnection",
                    style=>$self->{DATASTYLE},
                    Handlers=>{
                         startElement=>sub{ $weak->_handle_root(@_) },
                         endElement=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{endElement}}($weak, @_) },
                         characters=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{characters}}($weak, @_) },
                        }
                 );

    # select is not implemented for filehandles on win32 (see perlport)
    # so we fake it out using XML::Stream::IO::Select::Win32
    if ( $^O =~ /mswin32/i ) {
        $self->{SIDS}->{newconnection}->{select}
            = XML::Stream::IO::Select::Win32->new(
                $self->{SIDS}->{newconnection}->{sock});

        $self->{SELECT}
            = XML::Stream::IO::Select::Win32->new(
                $self->{SIDS}->{newconnection}->{sock});
    }
    else {
        $self->{SIDS}->{newconnection}->{select}
            = IO::Select->new($self->{SIDS}->{newconnection}->{sock});

        $self->{SELECT}
            = IO::Select->new($self->{SIDS}->{newconnection}->{sock});
    }

    $self->{SIDS}->{newconnection}->{status} = 0;

    my $buff = "";
    while($self->{SIDS}->{newconnection}->{status} == 0)
    {
        $self->debug(5,"OpenFile: can_read(",join(",",$self->{SIDS}->{newconnection}->{select}->can_read(0)),")");
        if ($self->{SIDS}->{newconnection}->{select}->can_read(0))
        {
            $self->{SIDS}->{newconnection}->{status} = -1
                unless defined($buff = $self->Read("newconnection"));
            return unless($self->{SIDS}->{newconnection}->{status} == 0);
            return unless($self->ParseStream("newconnection",$buff) == 1);
        }

        return if($self->{SIDS}->{newconnection}->{select}->has_exception(0) &&
                  $self->{SIDS}->{newconnection}->{sock}->error());
    }
    return if($self->{SIDS}->{newconnection}->{status} != 1);


    my $sid = $self->NewSID();
    foreach my $key (keys(%{$self->{SIDS}->{newconnection}}))
    {
        $self->{SIDS}->{$sid}->{$key} = $self->{SIDS}->{newconnection}->{$key};
    }
    $self->{SIDS}->{$sid}->{parser}->setSID($sid);

    $self->{SOCKETS}->{$self->{SIDS}->{newconnection}->{sock}} = $sid;

    delete($self->{SIDS}->{newconnection});

    return $sid;
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Common Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 Disconnect

Sends the closing XML tag and shuts down the socket.

  Disconnect(sid)

Sends the proper closing XML tag and closes the specified socket down.

=cut

sub Disconnect
{
    my $self = shift;
    my $sid = shift;

    $self->Send($sid,"</stream:stream>");
    close($self->{SIDS}->{$sid}->{sock})
        if (($self->{SIDS}->{$sid}->{connectiontype} eq "tcpip") ||
    ($self->{SIDS}->{$sid}->{connectiontype} eq "http"));
    delete($self->{SOCKETS}->{$self->{SIDS}->{$sid}->{sock}});
    foreach my $key (keys(%{$self->{SIDS}->{$sid}}))
    {
        delete($self->{SIDS}->{$sid}->{$key});
    }
    delete($self->{SIDS}->{$sid});
}


##############################################################################

=pod

=head2 InitConnection

Initialize the connection data structure

=cut

sub InitConnection
{
    my $self = shift;
    my $sid = shift;
    my $serverid = shift;

    #---------------------------------------------------------------------------
    # Set the default STATUS so that we can keep track of it throughout the
    # session.
    #   1 = no errors
    #   0 = no data has been received yet
    #  -1 = error from handlers
    #  -2 = error but keep the connection alive so that we can send some info.
    #---------------------------------------------------------------------------
    $self->{SIDS}->{$sid}->{status} = 0;

    #---------------------------------------------------------------------------
    # A storage place for when we don't have a callback registered and we need
    # to stockpile the nodes we receive until Process is called and we return
    # them.
    #---------------------------------------------------------------------------
    $self->{SIDS}->{$sid}->{nodes} = ();

    #---------------------------------------------------------------------------
    # If there is an error on the stream, then we need a place to indicate that.
    #---------------------------------------------------------------------------
    $self->{SIDS}->{$sid}->{streamerror} = {};

    #---------------------------------------------------------------------------
    # Grab the init time so that we can keep the connection alive by sending " "
    #---------------------------------------------------------------------------
    $self->{SIDS}->{$sid}->{keepalive} = time;

    #---------------------------------------------------------------------------
    # Keep track of the "server" we are connected to so we can check stuff
    # later.
    #---------------------------------------------------------------------------
    $self->{SIDS}->{$sid}->{serverid} = $serverid;

    #---------------------------------------------------------------------------
    # Mark the stream:features as MIA.
    #---------------------------------------------------------------------------
    $self->{SIDS}->{$sid}->{streamfeatures}->{received} = 0;
    
    #---------------------------------------------------------------------------
    # First acitivty is the connection... duh. =)
    #---------------------------------------------------------------------------
    $self->MarkActivity($sid);
}


##############################################################################

=pod

=head2 ParseStream

Takes the incoming stream and makes sure that only full
XML tags gets passed to the parser.  If a full tag has not
read yet, then the Stream saves the incomplete part and
sends the rest to the parser.

=cut

sub ParseStream
{
    my $self = shift;
    my $sid = shift;
    my $stream = shift;

    $stream = "" unless defined($stream);

    $self->debug(3,"ParseStream: sid($sid) stream($stream)");

    $self->{SIDS}->{$sid}->{parser}->parse($stream);

    if (exists($self->{SIDS}->{$sid}->{streamerror}->{type}))
    {
        $self->debug(3,"ParseStream: ERROR($self->{SIDS}->{$sid}->{streamerror}->{type})");
        $self->SetErrorCode($sid,$self->{SIDS}->{$sid}->{streamerror});
        return 0;
    }

    return 1;
}


##############################################################################

=pod

=head2 Process

Checks for data on the socket and returns a status code depending
on if there was data or not.  If a timeout is not defined in the
call then the timeout defined in Connect() is used.  If a timeout
of 0 is used then the call blocks until it gets some data,
otherwise it returns after the timeout period.

  Process(integer)

Waits for data to be available on the socket.  If
a timeout is specified then the Process function
waits that period of time before returning nothing.
If a timeout period is not specified then the
function blocks until data is received.  The
function returns a hash with session ids as the key,
and status values or data as the hash values.

=cut

sub Process
{
    my $self = shift;
    my $timeout = shift;
    $timeout = "" unless defined($timeout);

    $self->debug(4,"Process: timeout($timeout)");
    #---------------------------------------------------------------------------
    # We need to keep track of what's going on in the function and tell the
    # outside world about it so let's return something useful.  We track this
    # information based on sid:
    #    -1    connection closed and error
    #     0    connection open but no data received.
    #     1    connection open and data received.
    #   array  connection open and the data that has been collected
    #          over time (No CallBack specified)
    #---------------------------------------------------------------------------
    my %status;
    foreach my $sid (keys(%{$self->{SIDS}}))
    {
        next if ($sid eq "default");
        $self->debug(5,"Process: initialize sid($sid) status to 0");
        $status{$sid} = 0;
    }

    #---------------------------------------------------------------------------
    # Either block until there is data and we have parsed it all, or wait a
    # certain period of time and then return control to the user.
    #---------------------------------------------------------------------------
    my $block = 1;
    my $timeEnd = ($timeout eq "") ? "" : time + $timeout;
    while($block == 1)
    {
        $self->debug(4,"Process: let's wait for data");

        my $now = time;
        my $wait = (($timeEnd eq "") || ($timeEnd - $now > 10)) ? 10 :
                    $timeEnd - $now;

        foreach my $connection ($self->{SELECT}->can_read($wait))
        {
            $self->debug(4,"Process: connection($connection)");
            $self->debug(4,"Process: sid($self->{SOCKETS}->{$connection})");
            $self->debug(4,"Process: connection_status($self->{SIDS}->{$self->{SOCKETS}->{$connection}}->{status})");

            next unless (($self->{SIDS}->{$self->{SOCKETS}->{$connection}}->{status} == 1) ||
                         exists($self->{SIDS}->{$self->{SOCKETS}->{$connection}}->{activitytimeout}));

            my $processit = 1;
            if (exists($self->{SIDS}->{server}))
            {
                foreach my $serverid (@{$self->{SIDS}->{server}})
                {
                    if (exists($self->{SIDS}->{$serverid}->{sock}) &&
                        ($connection == $self->{SIDS}->{$serverid}->{sock}))
                    {
                        my $sid = $self->ConnectionAccept($serverid);
                        $status{$sid} = 0;
                        $processit = 0;
                        last;
                    }
                }
            }
            if ($processit == 1)
            {
                my $sid = $self->{SOCKETS}->{$connection};
                $self->debug(4,"Process: there's something to read");
                $self->debug(4,"Process: connection($connection) sid($sid)");
                my $buff;
                $self->debug(4,"Process: read");
                $status{$sid} = 1;
                $self->{SIDS}->{$sid}->{status} = -1
                    if (!defined($buff = $self->Read($sid)));
                $buff = "" unless defined($buff);
                $self->debug(4,"Process: connection_status($self->{SIDS}->{$sid}->{status})");
                $status{$sid} = -1 unless($self->{SIDS}->{$sid}->{status} == 1);
                $self->debug(4,"Process: parse($buff)");
                $status{$sid} = -1 unless($self->ParseStream($sid,$buff) == 1);
            }
            $block = 0;
        }

        if ($timeout ne "")
        {
            if (time >= $timeEnd)
            {
                $self->debug(4,"Process: Everyone out of the pool! Time to stop blocking.");
                $block = 0;
            }
        }

        $self->debug(4,"Process: timeout($timeout)");

        if (exists($self->{CB}->{update}))
        {
            $self->debug(4,"Process: Calling user defined update function");
            &{$self->{CB}->{update}}();
        }

        $block = 1 if $self->{SELECT}->can_read(0);

        #---------------------------------------------------------------------
        # Check for connections that need to be kept alive
        #---------------------------------------------------------------------
        $self->debug(4,"Process: check for keepalives");
        foreach my $sid (keys(%{$self->{SIDS}}))
        {
            next if ($sid eq "default");
            next if ($sid =~ /^server/);
            next if ($status{$sid} == -1);
            if ((time - $self->{SIDS}->{$sid}->{keepalive}) > 10)
            {
                $self->IgnoreActivity($sid,1);
                $self->{SIDS}->{$sid}->{status} = -1
                    if !defined($self->Send($sid," "));
                $status{$sid} = -1 unless($self->{SIDS}->{$sid}->{status} == 1);
                if ($status{$sid} == -1)
                {
                    $self->debug(2,"Process: Keep-Alive failed.  What the hell happened?!?!");
                    $self->debug(2,"Process: connection_status($self->{SIDS}->{$sid}->{status})");
                }
                $self->IgnoreActivity($sid,0);
            }
        }
        #---------------------------------------------------------------------
        # Check for connections that have timed out.
        #---------------------------------------------------------------------
        $self->debug(4,"Process: check for timeouts");
        foreach my $sid (keys(%{$self->{SIDS}}))
        {
            next if ($sid eq "default");
            next if ($sid =~ /^server/);

            if (exists($self->{SIDS}->{$sid}->{activitytimeout}))
            {
                $self->debug(4,"Process: sid($sid) time(",time,") timeout($self->{SIDS}->{$sid}->{activitytimeout})");
            }
            else
            {
                $self->debug(4,"Process: sid($sid) time(",time,") timeout(undef)");
            }
            
            $self->Respond($sid)
                if (exists($self->{SIDS}->{$sid}->{activitytimeout}) &&
                    defined($self->GetRoot($sid)));
            $self->Disconnect($sid)
                if (exists($self->{SIDS}->{$sid}->{activitytimeout}) &&
                    ((time - $self->{SIDS}->{$sid}->{activitytimeout}) > 10) &&
                     ($self->{SIDS}->{$sid}->{status} != 1));
        }


        #---------------------------------------------------------------------
        # If any of the connections have status == -1 then return so that the
        # user can handle it.
        #---------------------------------------------------------------------
        foreach my $sid (keys(%status))
        {
            if ($status{$sid} == -1)
            {
                $self->debug(4,"Process: sid($sid) is broken... let's tell someone and watch it hit the fan... =)");
                $block = 0;
            }
        }

        $self->debug(2,"Process: block($block)");
    }

    #---------------------------------------------------------------------------
    # If the Select has an error then shut this party down.
    #---------------------------------------------------------------------------
    foreach my $connection ($self->{SELECT}->has_exception(0))
    {
        $self->debug(4,"Process: has_exception sid($self->{SOCKETS}->{$connection})");
        $status{$self->{SOCKETS}->{$connection}} = -1;
    }

    #---------------------------------------------------------------------------
    # If there are data structures that have not been collected return
    # those, otherwise return the status which indicates if nodes were read or
    # not.
    #---------------------------------------------------------------------------
    foreach my $sid (keys(%status))
    {
        $status{$sid} = $self->{SIDS}->{$sid}->{nodes}
            if (($status{$sid} == 1) &&
                ($#{$self->{SIDS}->{$sid}->{nodes}} > -1));
    }

    return %status;
}


##############################################################################

=pod


=head2 Read

Takes the data from the server and returns a string

=cut

sub Read
{
    my $self = shift;
    my $sid = shift;
    my $buff;
    my $status = 1;

    $self->debug(3,"Read: sid($sid)");
    $self->debug(3,"Read: connectionType($self->{SIDS}->{$sid}->{connectiontype})");
    $self->debug(3,"Read: socket($self->{SIDS}->{$sid}->{sock})");

    return if ($self->{SIDS}->{$sid}->{status} == -1);

    if (!defined($self->{SIDS}->{$sid}->{sock}))
    {
        $self->{SIDS}->{$sid}->{status} = -1;
        $self->SetErrorCode($sid,"Socket does not defined.");
        return;
    }

    $self->{SIDS}->{$sid}->{sock}->flush();

    $status = $self->{SIDS}->{$sid}->{sock}->sysread($buff,4*POSIX::BUFSIZ)
        if (($self->{SIDS}->{$sid}->{connectiontype} eq "tcpip") ||
    ($self->{SIDS}->{$sid}->{connectiontype} eq "http") ||
    ($self->{SIDS}->{$sid}->{connectiontype} eq "file"));
    $status = sysread(STDIN,$buff,1024)
        if ($self->{SIDS}->{$sid}->{connectiontype} eq "stdinout");

    $buff =~ s/^HTTP[\S\s]+\n\n// if ($self->{SIDS}->{$sid}->{connectiontype} eq "http");
    $self->debug(1,"Read: buff($buff)");
    $self->debug(3,"Read: status($status)") if defined($status);
    $self->debug(3,"Read: status(undef)") unless defined($status);
    $self->{SIDS}->{$sid}->{keepalive} = time
        unless (($buff eq "") || !defined($status) || ($status == 0));
    if (defined($status) && ($status != 0))
    {
        $buff = Encode::decode_utf8($buff);
        return $buff;
    }
    #return $buff unless (!defined($status) || ($status == 0));
    $self->debug(1,"Read: ERROR");
    return;
}


#############################################################################

=pod

=head2 Send

Takes the data string and sends it to the server

  Send(sid, string);

Sends the string over the specified connection as is.
This does no checking if valid XML was sent or not.
Best behavior when sending information.

=cut

sub Send
{
    my $self = shift;
    my $sid = shift;
    $self->debug(1,"Send: (@_)");
    $self->debug(3,"Send: sid($sid)");
    $self->debug(3,"Send: status($self->{SIDS}->{$sid}->{status})");
    
    $self->{SIDS}->{$sid}->{keepalive} = time;

    return if ($self->{SIDS}->{$sid}->{status} == -1);

    if (!defined($self->{SIDS}->{$sid}->{sock}))
    {
        $self->debug(3,"Send: socket not defined");
        $self->{SIDS}->{$sid}->{status} = -1;
        $self->SetErrorCode($sid,"Socket not defined.");
        return;
    }
    else
    {
        $self->debug(3,"Send: socket($self->{SIDS}->{$sid}->{sock})");
    }

    $self->{SIDS}->{$sid}->{sock}->flush();

    if ($self->{SIDS}->{$sid}->{select}->can_write(0))
    {
        $self->debug(3,"Send: can_write");
        
        $self->{SENDSTRING} = Encode::encode_utf8(join("",@_));

        $self->{SENDWRITTEN} = 0;
        $self->{SENDOFFSET} = 0;
        $self->{SENDLENGTH} = length($self->{SENDSTRING});
        while ($self->{SENDLENGTH})
        {
            $self->{SENDWRITTEN} = $self->{SIDS}->{$sid}->{sock}->syswrite($self->{SENDSTRING},$self->{SENDLENGTH},$self->{SENDOFFSET});

            if (!defined($self->{SENDWRITTEN}))
            {
                $self->debug(4,"Send: SENDWRITTEN(undef)");
                $self->debug(4,"Send: Ok... what happened?  Did we lose the connection?");
                $self->{SIDS}->{$sid}->{status} = -1;
                $self->SetErrorCode($sid,"Socket died for an unknown reason.");
                return;
            }
            
            $self->debug(4,"Send: SENDWRITTEN($self->{SENDWRITTEN})");

            $self->{SENDLENGTH} -= $self->{SENDWRITTEN};
            $self->{SENDOFFSET} += $self->{SENDWRITTEN};
        }
    }
    else
    {
        $self->debug(3,"Send: can't write...");
    }

    return if($self->{SIDS}->{$sid}->{select}->has_exception(0));

    $self->debug(3,"Send: no exceptions");

    $self->{SIDS}->{$sid}->{keepalive} = time;

    $self->MarkActivity($sid);

    return 1;
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Feature Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 ProcessStreamFeatures

Process the <stream:featutres/> block.

=cut

sub ProcessStreamFeatures
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

    $self->{SIDS}->{$sid}->{streamfeatures}->{received} = 1;

    #-------------------------------------------------------------------------
    # SASL - 1.0
    #-------------------------------------------------------------------------
    my @sasl = &XPath($node,'*[@xmlns="'.&ConstXMLNS('xmpp-sasl').'"]');
    if ($#sasl > -1)
    {
        if (&XPath($sasl[0],"name()") eq "mechanisms")
        {
            my @mechanisms = &XPath($sasl[0],"mechanism/text()");
            $self->{SIDS}->{$sid}->{streamfeatures}->{'xmpp-sasl'} = \@mechanisms;
        }
    }
    
    #-------------------------------------------------------------------------
    # XMPP-TLS - 1.0
    #-------------------------------------------------------------------------
    my @tls = &XPath($node,'*[@xmlns="'.&ConstXMLNS('xmpp-tls').'"]');
    if ($#tls > -1)
    {
        if (&XPath($tls[0],"name()") eq "starttls")
        {
            $self->{SIDS}->{$sid}->{streamfeatures}->{'xmpp-tls'} = 1;
            my @required = &XPath($tls[0],"required");
            if ($#required > -1)
            {
                $self->{SIDS}->{$sid}->{streamfeatures}->{'xmpp-tls'} = "required";
            }
        }
    }
    
    #-------------------------------------------------------------------------
    # XMPP-Bind - 1.0
    #-------------------------------------------------------------------------
    my @bind = &XPath($node,'*[@xmlns="'.&ConstXMLNS('xmpp-bind').'"]');
    if ($#bind > -1)
    {
        $self->{SIDS}->{$sid}->{streamfeatures}->{'xmpp-bind'} = 1;
    }
    
    #-------------------------------------------------------------------------
    # XMPP-Session - 1.0
    #-------------------------------------------------------------------------
    my @session = &XPath($node,'*[@xmlns="'.&ConstXMLNS('xmpp-session').'"]');
    if ($#session > -1)
    {
        $self->{SIDS}->{$sid}->{streamfeatures}->{'xmpp-session'} = 1;
    }
    
}


##############################################################################

=pod

=head2 GetStreamFeature

Return the value of the stream feature (if any).

=cut

sub GetStreamFeature
{
    my $self = shift;
    my $sid = shift;
    my $feature = shift;

    return unless exists($self->{SIDS}->{$sid}->{streamfeatures}->{$feature});
    return $self->{SIDS}->{$sid}->{streamfeatures}->{$feature};
}


##############################################################################

=pod

=head2 ReceivedStreamFeatures

Have we received the stream:features yet?

=cut

sub ReceivedStreamFeatures
{
    my $self = shift;
    my $sid = shift;
    my $feature = shift;

    return $self->{SIDS}->{$sid}->{streamfeatures}->{received};
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| TLS Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 ProcessTLSPacket

Process a TLS based packet.

=cut

sub ProcessTLSPacket
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

    my $tag = &XPath($node,"name()");

    if ($tag eq "failure")
    {
        $self->TLSClientFailure($sid,$node);
    }
    
    if ($tag eq "proceed")
    {
        $self->TLSClientProceed($sid,$node);
    }
}


##############################################################################

=pod

=head2 StartTLS

Client function to have the socket start TLS.

=cut

sub StartTLS
{
    my $self = shift;
    my $sid = shift;
    my $timeout = shift;
    $timeout = 120 unless defined($timeout);
    $timeout = 120 if ($timeout eq "");
    
    $self->TLSStartTLS($sid);

    my $endTime = time + $timeout;
    while(!$self->TLSClientDone($sid) && ($endTime >= time))
    {
        $self->Process(1);
    }

    if (!$self->TLSClientSecure($sid))
    {
        return;
    }

    return $self->OpenStream($sid,$timeout);
}


##############################################################################

=pod

=head2 TLSStartTLS

Send a <starttls/> in the TLS namespace.

=cut

sub TLSStartTLS
{
    my $self = shift;
    my $sid = shift;

    $self->Send($sid,"<starttls xmlns='".&ConstXMLNS('xmpp-tls')."'/>");
}


##############################################################################

=pod

=head2 TLSClientProceed

Handle a <proceed/> packet.

=cut

sub TLSClientProceed
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

    $self->debug(1,"TLSClientProceed: Convert normal socket to SSL");
    $self->debug(1,"TLSClientProceed: sock($self->{SIDS}->{$sid}->{sock})");
    if (!$self->LoadSSL())
    {
        $self->{SIDS}->{$sid}->{tls}->{error} = "Could not load IO::Socket::SSL.";
        $self->{SIDS}->{$sid}->{tls}->{done} = 1;
        return;
    }
    
    IO::Socket::SSL->start_SSL(
        $self->{SIDS}->{$sid}->{sock},
        $self->{SIDS}->{$sid}->{ssl_params}
    );

    $self->debug(1,"TLSClientProceed: ssl_sock($self->{SIDS}->{$sid}->{sock})");
    $self->debug(1,"TLSClientProceed: SSL: We are secure")
        if ($self->{SIDS}->{$sid}->{sock});
    
    $self->{SIDS}->{$sid}->{tls}->{done} = 1;
    $self->{SIDS}->{$sid}->{tls}->{secure} = 1;
}


##############################################################################

=pod

=head2 TLSClientSecure

Return 1 if the socket is secure, 0 otherwise.

=cut

sub TLSClientSecure
{
    my $self = shift;
    my $sid = shift;
    
    return $self->{SIDS}->{$sid}->{tls}->{secure};
}


##############################################################################

=pod

=head2 TLSClientDone

Return 1 if the TLS process is done

=cut

sub TLSClientDone
{
    my $self = shift;
    my $sid = shift;
    
    return $self->{SIDS}->{$sid}->{tls}->{done};
}


##############################################################################

=pod

=head2 TLSClientError

return the TLS error if any

=cut

sub TLSClientError
{
    my $self = shift;
    my $sid = shift;
    
    return $self->{SIDS}->{$sid}->{tls}->{error};
}


##############################################################################

=pod

=head2 TLSClientFailure

Handle a <failure/>

=cut

sub TLSClientFailure
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;
    
    my $type = &XPath($node,"*/name()");

    $self->{SIDS}->{$sid}->{tls}->{error} = $type;
    $self->{SIDS}->{$sid}->{tls}->{done} = 1;
}


##############################################################################


=pod

=head2 TLSFailure

Send a <failure/> in the TLS namespace

=cut

sub TLSFailure
{
    my $self = shift;
    my $sid = shift;
    my $type = shift;
    
    $self->Send($sid,"<failure xmlns='".&ConstXMLNS('xmpp-tls')."'><${type}/></failure>");
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| SASL Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################


=pod

=head2 ProcessSASLPacket

Process a SASL based packet.

=cut

sub ProcessSASLPacket
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

    my $tag = &XPath($node,"name()");

    if ($tag eq "challenge")
    {
        $self->SASLAnswerChallenge($sid,$node);
    }
    
    if ($tag eq "failure")
    {
        $self->SASLClientFailure($sid,$node);
    }
    
    if ($tag eq "success")
    {
        $self->SASLClientSuccess($sid,$node);
    }
}


##############################################################################

=pod

=head2 SASLAnswerChallenge

When we get a <challenge/> we need to do the grunt
work to return a <response/>.

=cut

sub SASLAnswerChallenge
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

    my $challenge64 = &XPath($node,"text()");
    my $challenge = MIME::Base64::decode_base64($challenge64);
    
    #-------------------------------------------------------------------------
    # As far as I can tell, if the challenge contains rspauth, then we authed.
    # If you try to send that to Authen::SASL, it will spew warnings about
    # the missing qop, nonce, etc...  However, in order for jabberd2 to think
    # that you answered, you have to send back an empty response.  Not sure
    # which approach is right... So let's hack for now.
    #-------------------------------------------------------------------------
    my $response = "";
    if ($challenge !~ /rspauth\=/)
    {
        $response = $self->{SIDS}->{$sid}->{sasl}->{client}->client_step($challenge);
    }

    my $response64 = "";
    if (defined $response)
    {
        $response64 = MIME::Base64::encode_base64($response,"");
    }

    $self->SASLResponse($sid,$response64);
}


##############################################################################


=pod

=head2 SASLAuth

Send an <auth/> in the SASL namespace

=cut

sub SASLAuth
{
    my $self = shift;
    my $sid = shift;

    my $first_step = $self->{SIDS}->{$sid}->{sasl}->{client}->client_start();
    my $first_step64 = MIME::Base64::encode_base64($first_step,"");

    $self->Send($sid,
        "<auth xmlns='" . &ConstXMLNS('xmpp-sasl') .
        "' mechanism='" . $self->{SIDS}->{$sid}->{sasl}->{client}->mechanism() .
# from http://blogs.perl.org/users/marco_fontani/2010/03/google-talk-with-perl.html
# not yet in use
#        "' " .
#        q{xmlns:ga='http://www.google.com/talk/protocol/auth'
#            ga:client-uses-full-bind-result='true'} .    # JID
        "'>" . $first_step64 . "</auth>");
}


##############################################################################

=pod

=head2 SASLChallenge

Send a <challenge/> in the SASL namespace

=cut

sub SASLChallenge
{
    my $self = shift;
    my $sid = shift;
    my $challenge = shift;

    $self->Send($sid,"<challenge xmlns='".&ConstXMLNS('xmpp-sasl')."'>${challenge}</challenge>");
}


###############################################################################


=pod

=head2 SASLClient

This is a helper function to perform all of the required steps for doing SASL with the server.

=cut

sub SASLClient
{
    my $self = shift;
    my $sid = shift;
    my $username = shift;
    my $password = shift;

    my $mechanisms = $self->GetStreamFeature($sid,"xmpp-sasl");

    return unless defined($mechanisms);

    # Here we assume that if 'to' is available, then a domain is being
    # specified that does not match the hostname of the jabber server
    # and that we should use that to form the bare JID for SASL auth.
    my $domain .=  $self->{SIDS}->{$sid}->{to}
        ? $self->{SIDS}->{$sid}->{to}
        : $self->{SIDS}->{$sid}->{hostname};

    my $authname = $username . '@' . $domain;
    
    my $sasl = Authen::SASL->new(mechanism=>join(" ",@{$mechanisms}),
                                callback=>{
                                           authname => $authname,

                                           user     => $username,
                                           pass     => $password
                                          }
                               );

    $self->{SIDS}->{$sid}->{sasl}->{client} = $sasl->client_new('xmpp', $domain);
    $self->{SIDS}->{$sid}->{sasl}->{username} = $username;
    $self->{SIDS}->{$sid}->{sasl}->{password} = $password;
    $self->{SIDS}->{$sid}->{sasl}->{authed} = 0;
    $self->{SIDS}->{$sid}->{sasl}->{done} = 0;

    $self->SASLAuth($sid);
}


##############################################################################

=pod

=head2 SASLClientAuthed

Return 1 if we authed via SASL, 0 otherwise

=cut

sub SASLClientAuthed
{
    my $self = shift;
    my $sid = shift;
    
    return $self->{SIDS}->{$sid}->{sasl}->{authed};
}


##############################################################################

=pod

=head2 SASLClientDone

Return 1 if the SASL process is finished

=cut

sub SASLClientDone
{
    my $self = shift;
    my $sid = shift;
    
    return $self->{SIDS}->{$sid}->{sasl}->{done};
}


##############################################################################

=pod

=head2 SASLClientError

Return the error if any

=cut

sub SASLClientError
{
    my $self = shift;
    my $sid = shift;
    
    return $self->{SIDS}->{$sid}->{sasl}->{error};
}


##############################################################################

=pod

=head2 SASLClientFailure

Handle a received <failure/>

=cut

sub SASLClientFailure
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;
    
    my $type = &XPath($node,"*/name()");

    $self->{SIDS}->{$sid}->{sasl}->{error} = $type;
    $self->{SIDS}->{$sid}->{sasl}->{done} = 1;
}


##############################################################################

=pod

=head2 SASLClientSuccess

handle a received <success/>

=cut

sub SASLClientSuccess
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;
    
    $self->{SIDS}->{$sid}->{sasl}->{authed} = 1;
    $self->{SIDS}->{$sid}->{sasl}->{done} = 1;
}


##############################################################################

=pod

=head2 SASLFailure

Send a <failure/> tag in the SASL namespace

=cut

sub SASLFailure
{
    my $self = shift;
    my $sid = shift;
    my $type = shift;
    
    $self->Send($sid,"<failure xmlns='".&ConstXMLNS('xmpp-sasl')."'><${type}/></failure>");
}


##############################################################################

=pod

=head2 SASLResponse

Send a <response/> tag in the SASL namespace

=cut

sub SASLResponse
{
    my $self = shift;
    my $sid = shift;
    my $response = shift;

    $self->Send($sid,"<response xmlns='".&ConstXMLNS('xmpp-sasl')."'>${response}</response>");
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Packet Handlers
#|
#+----------------------------------------------------------------------------
##############################################################################


##############################################################################
#
# ProcessStreamPacket - process the <stream:XXXX/> packet
#
##############################################################################
sub ProcessStreamPacket
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

    my $tag = &XPath($node,"name()");
    my $stream_prefix = $self->StreamPrefix($sid);
    my ($type) = ($tag =~ /^${stream_prefix}\:(.+)$/);

    $self->ProcessStreamError($sid,$node) if ($type eq "error");
    $self->ProcessStreamFeatures($sid,$node) if ($type eq "features");
}


##############################################################################
#
# _handle_root - handles a root tag and checks that it is a stream:stream tag
#                with the proper namespace.  If not then it sets the STATUS
#                to -1 and let's the outer code know that an error occurred.
#                Then it changes the Start tag handlers to the methond listed
#                in $self->{DATASTYLE}
#
##############################################################################
sub _handle_root
{
    my $self = shift;
    my ($sax, $tag, %att) = @_;
    my $sid = $sax->getSID();

    $self->debug(2,"_handle_root: sid($sid) sax($sax) tag($tag) att(",%att,")");

    $self->{SIDS}->{$sid}->{rootTag} = $tag;

    if ($self->{SIDS}->{$sid}->{connectiontype} ne "file")
    {
        #---------------------------------------------------------------------
        # Make sure we are receiving a valid stream on the same namespace.
        #---------------------------------------------------------------------
        
        $self->debug(3,"_handle_root: ($self->{SIDS}->{$self->{SIDS}->{$sid}->{serverid}}->{namespace})");
        $self->{SIDS}->{$sid}->{status} =
            ((($tag eq "stream:stream") &&
               exists($att{'xmlns'}) &&
               ($att{'xmlns'} eq $self->{SIDS}->{$self->{SIDS}->{$sid}->{serverid}}->{namespace})
              ) ?
              1 :
              -1
            );
        $self->debug(3,"_handle_root: status($self->{SIDS}->{$sid}->{status})");
    }
    else
    {
        $self->{SIDS}->{$sid}->{status} = 1;
    }

    #-------------------------------------------------------------------------
    # Get the root tag attributes and save them for later.  You never know when
    # you'll need to check the namespace or the from attributes sent by the
    # server.
    #-------------------------------------------------------------------------
    $self->{SIDS}->{$sid}->{root} = \%att;

    #-------------------------------------------------------------------------
    # Run through the various xmlns:*** attributes and register the namespace
    # to prefix map.
    #-------------------------------------------------------------------------
    foreach my $key (keys(%att))
    {
        if ($key =~ /^xmlns\:(.+?)$/)
        {
            $self->debug(5,"_handle_root: RegisterPrefix: prefix($att{$key}) ns($1)");
            $self->RegisterPrefix($sid,$att{$key},$1);
        }
    }
    
    #-------------------------------------------------------------------------
    # Sometimes we will get an error, so let's parse the tag assuming that we
    # got a stream:error
    #-------------------------------------------------------------------------
    my $stream_prefix = $self->StreamPrefix($sid);
    $self->debug(5,"_handle_root: stream_prefix($stream_prefix)");
    
    if ($tag eq $stream_prefix.":error")
    {
        &XML::Stream::Tree::_handle_element($self,$sax,$tag,%att)
            if ($self->{DATASTYLE} eq "tree");
        &XML::Stream::Node::_handle_element($self,$sax,$tag,%att)
            if ($self->{DATASTYLE} eq "node");
    }

    #---------------------------------------------------------------------------
    # Now that we have gotten a root tag, let's look for the tags that make up
    # the stream.  Change the handler for a Start tag to another function.
    #---------------------------------------------------------------------------
    my $weak = $self;
    weaken $weak;
    $sax->setHandlers(startElement=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{startElement}}($weak, @_) },
                endElement=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{endElement}}($weak, @_) },
                characters=>sub{ &{$HANDLERS{$weak->{DATASTYLE}}->{characters}}($weak, @_) },
             );
}


##############################################################################
#
# _node - internal callback for nodes.  All it does is place the nodes in a
#         list so that Process() can return them later.
#
##############################################################################
sub _node
{
    my $self = shift;
    my $sid = shift;
    my @node = shift;

    if (ref($node[0]) eq "XML::Stream::Node")
    {
        push(@{$self->{SIDS}->{$sid}->{nodes}},$node[0]);
    }
    else
    {
        push(@{$self->{SIDS}->{$sid}->{nodes}},\@node);
    }
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Error Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 GetErrorCode

if you are returned an undef, you can call this function
and hopefully learn more information about the problem.

  GetErrorCode(sid)

returns a string for the specified session that
will hopefully contain some useful information
about why Process or Connect returned an undef
to you.

=cut

sub GetErrorCode
{
    my $self = shift;
    my $sid = shift;

    $sid = "newconnection" unless defined($sid);

    $self->debug(3,"GetErrorCode: sid($sid)");
    return ((exists($self->{SIDS}->{$sid}->{errorcode}) &&
             (ref($self->{SIDS}->{$sid}->{errorcode}) eq "HASH")) ?
            $self->{SIDS}->{$sid}->{errorcode} :
            { type=>"system",
              text=>$!,
            }
           );
}


##############################################################################
#
# SetErrorCode - sets the error code so that the caller can find out more
#                information about the problem
#
##############################################################################
sub SetErrorCode
{
    my $self = shift;
    my $sid = shift;
    my $errorcode = shift;

    $self->{SIDS}->{$sid}->{errorcode} = $errorcode;
}


##############################################################################
#
# ProcessStreamError - Take the XML packet and extract out the error.
#
##############################################################################
sub ProcessStreamError
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

    $self->{SIDS}->{$sid}->{streamerror}->{type} = "unknown";
    $self->{SIDS}->{$sid}->{streamerror}->{node} = $node;
    
    #-------------------------------------------------------------------------
    # Check for older 0.9 streams and handle the errors for them.
    #-------------------------------------------------------------------------
    if (!exists($self->{SIDS}->{$sid}->{root}->{version}) ||
        ($self->{SIDS}->{$sid}->{root}->{version} eq "") ||
        ($self->{SIDS}->{$sid}->{root}->{version} < 1.0)
       )
    {
        $self->{SIDS}->{$sid}->{streamerror}->{text} =
            &XPath($node,"text()");
        return;
    }

    #-------------------------------------------------------------------------
    # Otherwise we are in XMPP land with real stream errors.
    #-------------------------------------------------------------------------
    my @errors = &XPath($node,'*[@xmlns="'.&ConstXMLNS("xmppstreams").'"]');

    my $type;
    my $text;
    foreach my $error (@errors)
    {
        if (&XPath($error,"name()") eq "text")
        {
            $self->{SIDS}->{$sid}->{streamerror}->{text} =
                &XPath($error,"text()");
        }
        else
        {
            $self->{SIDS}->{$sid}->{streamerror}->{type} =
                &XPath($error,"name()");
        }
    }
}


##############################################################################

=pod

=head2 StreamError

Given a type and text, generate a <stream:error/> packet to
send back to the other side.

=cut

sub StreamError
{
    my $self = shift;
    my $sid = shift;
    my $type = shift;
    my $text = shift;

    my $root = $self->GetRoot($sid);
    my $stream_base = $self->StreamPrefix($sid);
    my $error = "<${stream_base}:error>";

    if (exists($root->{version}) && ($root->{version} ne ""))
    {
        $error .= "<${type} xmlns='".&ConstXMLNS('xmppstreams')."'/>";
        if (defined($text))
        {
            $error .= "<text xmlns='".&ConstXMLNS('xmppstreams')."'>";
            $error .= $text;
            $error .= "</text>";
        }
    }
    else
    {
        $error .= $text;
    }

    $error .= "</${stream_base}:error>";

    return $error;
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Activity Monitoring Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################
#
# IgnoreActivity - Set the flag that will ignore the activity monitor.
#
##############################################################################
sub IgnoreActivity
{
    my $self = shift;
    my $sid = shift;
    my $ignoreActivity = shift;
    $ignoreActivity = 1 unless defined($ignoreActivity);

    $self->debug(3,"IgnoreActivity: ignoreActivity($ignoreActivity)");
    $self->debug(4,"IgnoreActivity: sid($sid)");

    $self->{SIDS}->{$sid}->{ignoreActivity} = $ignoreActivity;
}


##############################################################################
#
# LastActivity - Return the time of the last activity.
#
##############################################################################
sub LastActivity
{
    my $self = shift;
    my $sid = shift;

    $self->debug(3,"LastActivity: sid($sid)");
    $self->debug(1,"LastActivity: lastActivity($self->{SIDS}->{$sid}->{lastActivity})");

    return $self->{SIDS}->{$sid}->{lastActivity};
}


##############################################################################
#
# MarkActivity - Record the current time for this sid.
#
##############################################################################
sub MarkActivity
{
    my $self = shift;
    my $sid = shift;

    return if (exists($self->{SIDS}->{$sid}->{ignoreActivity}) &&
               ($self->{SIDS}->{$sid}->{ignoreActivity} == 1));

    $self->debug(3,"MarkActivity: sid($sid)");

    $self->{SIDS}->{$sid}->{lastActivity} = time;
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| XML Node Interface functions
#|
#|   These are generic wrappers around the Tree and Node data types.  The
#| problem being that the Tree class cannot support methods.
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 SetXMLData

Takes a host of arguments and sets a portion of the specified
data strucure with that data.  The function works in two
modes "single" or "multiple".  "single" denotes that the
function should locate the current tag that matches this
data and overwrite it's contents with data passed in.
"multiple" denotes that a new tag should be created even if
others exist.

type    - single or multiple
XMLTree - pointer to XML::Stream data object (tree or node)
tag     - name of tag to create/modify (if blank assumes
          working with top level tag)
data    - CDATA to set for tag
attribs - attributes to ADD to tag

=cut

sub SetXMLData
{
    return &XML::Stream::Node::SetXMLData(@_) if (ref($_[1]) eq "XML::Stream::Node");
    return &XML::Stream::Tree::SetXMLData(@_) if (ref($_[1]) eq "ARRAY");
}


##############################################################################

=pod

=head2 GetXMLData

Takes a host of arguments and returns various data structures
that match them.

type C<existence> - returns 1 or 0 if the tag exists in the top level.

C<value> - returns either the CDATA of the tag, or the
value of the attribute depending on which is
sought.  This ignores any mark ups to the data
and just returns the raw CDATA.

C<value array>
returns an array of strings representing
all of the CDATA in the specified tag.
This ignores any mark ups to the data
and just returns the raw CDATA.

C<tree> - returns a data structure that represents the
XML with the specified tag as the root tag.
Depends on the format that you are working with.

C<tree array> returns an array of data structures each
with the specified tag as the root tag.

C<child array> - returns a list of all children nodes
                not including CDATA nodes.

C<attribs> - returns a hash with the attributes, and
            their values, for the things that match
            the parameters

C<count> - returns the number of things that match
          the arguments

C<tag> - returns the root tag of this tree

XMLTree - pointer to XML::Stream data structure

C<tag>  - tag to pull data from.  If blank then the top level
          tag is accessed.
C<attrib>  - attribute value to retrieve.  Ignored for types
          "value array", "tree", "tree array".  If paired
          with value can be used to filter tags based on
          attributes and values.
C<value>   - only valid if an attribute is supplied.  Used to
          filter for tags that only contain this attribute.
          Useful to search through multiple tags that all
          reference different name spaces.

=cut

sub GetXMLData
{
    return &XML::Stream::Node::GetXMLData(@_) if (ref($_[1]) eq "XML::Stream::Node");
    return &XML::Stream::Tree::GetXMLData(@_) if (ref($_[1]) eq "ARRAY");
}


##############################################################################

=pod

=head2 XPath

Run an xpath query on a node and return back the result.

XPath(node,path) returns an array of results that match the xpath.
node can be any of the three types (Tree, Node).

=cut

sub XPath
{
    my $tree = shift;
    my $path = shift;
    
    my $query = XML::Stream::XPath::Query->new($path);
    my $result = $query->execute($tree);
    if ($result->check())
    {
        my %attribs = $result->getAttribs();
        return %attribs if (scalar(keys(%attribs)) > 0);
        
        my @values = $result->getValues();
        @values = $result->getList() unless ($#values > -1);
        return @values if wantarray;
        return $values[0];
    }
    return;
}


##############################################################################

=pod

=head2 XPathCheck

Run an xpath query on a node and return 1 or 0 if the path is
valid.

=cut

sub XPathCheck
{
    my $tree = shift;
    my $path = shift;
    
    my $query = XML::Stream::XPath::Query->new($path);
    my $result = $query->execute($tree);
    return $result->check();
}


##############################################################################

=pod

=head2 XML2Config

Takes an XML data tree and turns it into a hash of hashes.
This only works for certain kinds of XML trees like this:

                <foo>
                  <bar>1</bar>
                  <x>
                    <y>foo</y>
                  </x>
                  <z>5</z>
                  <z>6</z>
                </foo>

The resulting hash would be:

                $hash{bar} = 1;
                $hash{x}->{y} = "foo";
                $hash{z}->[0] = 5;
                $hash{z}->[1] = 6;

Good for config files.

=cut

sub XML2Config
{
    return &XML::Stream::Node::XML2Config(@_) if (ref($_[0]) eq "XML::Stream::Node");
    return &XML::Stream::Tree::XML2Config(@_) if (ref($_[0]) eq "ARRAY");
}


##############################################################################

=pod


=head2 Config2XML

Takes a hash and produces an XML string from it.  If the hash looks like this:

                $hash{bar} = 1;
                $hash{x}->{y} = "foo";
                $hash{z}->[0] = 5;
                $hash{z}->[1] = 6;

The resulting xml would be:

                <foo>
                  <bar>1</bar>
                  <x>
                    <y>foo</y>
                  </x>
                  <z>5</z>
                  <z>6</z>
                </foo>

Good for config files.

=cut

sub Config2XML
{
    my ($tag,$hash,$indent) = @_;
    $indent = "" unless defined($indent);

    my $xml;

    if (ref($hash) eq "ARRAY")
    {
        foreach my $item (@{$hash})
        {
            $xml .= &XML::Stream::Config2XML($tag,$item,$indent);
        }
    }
    else
    {
        if ((ref($hash) eq "HASH") && ((scalar keys(%{$hash})) == 0))
        {
            $xml .= "$indent<$tag/>\n";
        }
        else
        {
            if (ref($hash) eq "")
            {
                if ($hash eq "")
                {
                    return "$indent<$tag/>\n";
                }
                else
                {
                    return "$indent<$tag>$hash</$tag>\n";
                }
            }
            else
            {
                $xml .= "$indent<$tag>\n";
                foreach my $item (sort {$a cmp $b} keys(%{$hash}))
                {
                    $xml .= &XML::Stream::Config2XML($item,$hash->{$item},"  $indent");
                }
                $xml .= "$indent</$tag>\n";
            }
        }
    }
    return $xml;
}


##############################################################################

=pod

=head2 EscapeXML

Simple function to make sure that no bad characters make it into
in the XML string that might cause the string to be
misinterpreted.

=cut

sub EscapeXML
{
    my $data = shift;

    if (defined($data))
    {
        $data =~ s/&/&amp;/g;
        $data =~ s/</&lt;/g;
        $data =~ s/>/&gt;/g;
        $data =~ s/\"/&quot;/g;
        $data =~ s/\'/&apos;/g;
    }

    return $data;
}


##############################################################################

=pod

=head2 UnescapeXML

Simple function to take an escaped string and return it to normal.

=cut

sub UnescapeXML
{
    my $data = shift;

    if (defined($data))
    {
        $data =~ s/&amp;/&/g;
        $data =~ s/&lt;/</g;
        $data =~ s/&gt;/>/g;
        $data =~ s/&quot;/\"/g;
        $data =~ s/&apos;/\'/g;
    }

    return $data;
}


##############################################################################

=pod

=head2 BuildXML

Takes one of the data formats that XML::Stream supports and call
the proper BuildXML_xxx function on it.

=cut

sub BuildXML
{
    return &XML::Stream::Node::BuildXML(@_) if (ref($_[0]) eq "XML::Stream::Node");
    return &XML::Stream::Tree::BuildXML(@_) if (ref($_[0]) eq "ARRAY");
    return &XML::Stream::Tree::BuildXML(@_) if (ref($_[1]) eq "ARRAY");
}



##############################################################################
#+----------------------------------------------------------------------------
#|
#| Namespace/Prefix Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 ConstXMLNS

Return the namespace from the constant string.

=cut

sub ConstXMLNS
{
    my $const = shift;
    
    return $XMLNS{$const};
}


##############################################################################
#
# StreamPrefix - Return the prefix of the <stream:stream/>
#
##############################################################################
sub StreamPrefix
{
    my $self = shift;
    my $sid = shift;
    
    return $self->ns2prefix($sid,&ConstXMLNS("stream"));
}


##############################################################################
#
# RegisterPrefix - setup the map for namespace to prefix
#
##############################################################################
sub RegisterPrefix
{
    my $self = shift;
    my $sid = shift;
    my $ns = shift;
    my $prefix = shift;

    $self->{SIDS}->{$sid}->{ns2prefix}->{$ns} = $prefix;
}


##############################################################################
#
# ns2prefix - for a stream, return the prefix for the given namespace
#
##############################################################################
sub ns2prefix
{
    my $self = shift;
    my $sid = shift;
    my $ns = shift;

    return $self->{SIDS}->{$sid}->{ns2prefix}->{$ns};
}




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Helper Functions
#|
#+----------------------------------------------------------------------------
##############################################################################

##############################################################################

=pod

=head2 GetRoot

Returns the hash of attributes for the root <stream:stream/> tag
so that any attributes returned can be accessed.  from and any
xmlns:foobar might be important.

  GetRoot(sid)

Returns the attributes that the stream:stream tag sent
by the other end listed in a hash for the specified session.

=cut

sub GetRoot
{
    my $self = shift;
    my $sid = shift;
    return unless exists($self->{SIDS}->{$sid}->{root});
    return $self->{SIDS}->{$sid}->{root};
}


##############################################################################

=pod

=head2 GetSock

returns the Socket so that an outside function can access it if desired.

  GetSock(sid)

Returns a pointer to the IO::Socket object for the specified session.

=cut

sub GetSock
{
    my $self = shift;
    my $sid = shift;
    return $self->{SIDS}->{$sid}->{sock};
}


##############################################################################
#
# LoadSSL - simple call to set everything up for SSL one time.
#
##############################################################################
sub LoadSSL
{
    my $self = shift;

    $self->debug(1,"LoadSSL: Load the IO::Socket::SSL module");
    
    if (defined($SSL) && ($SSL == 1))
    {
        $self->debug(1,"LoadSSL: Success");
        return 1;
    }
    
    if (defined($SSL) && ($SSL == 0))
    {
        $self->debug(1,"LoadSSL: Failure");
        return;
    }

    my $SSL_Version = "0.81";
    eval "use IO::Socket::SSL $SSL_Version";
    if ($@)
    {
        croak("IO::Socket::SSL v$SSL_Version or greater is required.");
    }
    $SSL = 1;

    $self->debug(1,"LoadSSL: Success");
    return 1;
}


##############################################################################
#
# Host2SID - For a server this allows you to lookup the SID of a stream server
#            based on the hostname that is is listening on.
#
##############################################################################
sub Host2SID
{
    my $self = shift;
    my $hostname = shift;

    foreach my $sid (keys(%{$self->{SIDS}}))
    {
        next if ($sid eq "default");
        next if ($sid =~ /^server/);

        return $sid if ($self->{SIDS}->{$sid}->{hostname} eq $hostname);
    }
    return;
}


##############################################################################

=pod

=head2 NewSID

Returns a session ID to send to an incoming stream in the return
header.  By default it just increments a counter and returns that,
or you can define a function and set it using the SetCallBacks
function.

=cut

sub NewSID
{
    my $self = shift;
    return &{$self->{CB}->{sid}}() if (exists($self->{CB}->{sid}) &&
                       defined($self->{CB}->{sid}));
    return $$.time.$self->{IDCOUNT}++;
}


###########################################################################

=pod

=head2 SetCallBacks

Takes a hash with top level tags to look for as the keys
and pointers to functions as the values.

  SetCallBacks(node=>function, update=>function);

Sets the callback that should be called in various situations.

C<node> is used to handle the data structures that are built for each top level tag.
C<update> is used for when Process is blocking waiting for data, but you
want your original code to be updated.

=cut

sub SetCallBacks
{
    my $self = shift;

    my $weak = $self;
    weaken $weak;
    while($#_ >= 0) {
        my $func = pop(@_);
        my $tag = pop(@_);
        if (($tag eq "node") && !defined($func))
        {
            $self->SetCallBacks(node=>sub { $weak->_node(@_) });
        }
        else
        {
            $self->debug(1,"SetCallBacks: tag($tag) func($func)");
            $self->{CB}->{$tag} = $func;
        }
    }
}


##############################################################################
#
# StreamHeader - Given the arguments, return the opening stream header.
#
##############################################################################
sub StreamHeader
{
    my $self = shift;
    my (%args) = @_;

    my $stream;
    $stream .= "<?xml version='1.0'?>";
    $stream .= "<stream:stream ";
    $stream .= "version='1.0' ";
    $stream .= "xmlns:stream='".&ConstXMLNS("stream")."' ";
    $stream .= "xmlns='$args{xmlns}' ";
    $stream .= "to='$args{to}' " if exists($args{to});
    $stream .= "from='$args{from}' " if exists($args{from});
    $stream .= "xml:lang='$args{xmllang}' " if exists($args{xmllang});

    foreach my $ns (@{$args{namespaces}})
    {
        $stream .= " ".$ns->GetStream();
    }
    
    $stream .= ">";

    return $stream;
}


###########################################################################
#
# debug - prints the arguments to the debug log if debug is turned on.
#
###########################################################################
sub debug
{
    return if ($_[1] > $_[0]->{DEBUGLEVEL});
    my $self = shift;
    my ($limit,@args) = @_;
    return if ($self->{DEBUGFILE} eq "");
    my $fh = $self->{DEBUGFILE};
    if ($self->{DEBUGTIME} == 1)
    {
        my ($sec,$min,$hour) = localtime(time);
        print $fh sprintf("[%02d:%02d:%02d] ",$hour,$min,$sec);
    }
    print $fh "XML::Stream: @args\n";
}


##############################################################################
#
# nonblock - set the socket to be non-blocking.
#
##############################################################################
sub nonblock
{
    my $self = shift;
    my $socket = shift;

    #--------------------------------------------------------------------------
    # Code copied from POE::Wheel::SocketFactory...
    # Win32 does things one way...
    #--------------------------------------------------------------------------
    if ($^O eq "MSWin32")
    {
        ioctl( $socket, 0x80000000 | (4 << 16) | (ord('f') << 8) | 126, 1) ||
            croak("Can't make socket nonblocking (win32): $!");
        return;
    }

    #--------------------------------------------------------------------------
    # And UNIX does them another
    #--------------------------------------------------------------------------
    my $flags = fcntl($socket, F_GETFL, 0)
        or die "Can't get flags for socket: $!\n";
    fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
        or die "Can't make socket nonblocking: $!\n";
}


##############################################################################
#
# printData - debugging function to print out any data structure in an
#             organized manner.  Very useful for debugging XML::Parser::Tree
#             objects.  This is a private function that will only exist in
#             in the development version.
#
##############################################################################
sub printData
{
    print &sprintData(@_);
}


##############################################################################
#
# sprintData - debugging function to build a string out of any data structure
#              in an organized manner.  Very useful for debugging
#              XML::Parser::Tree objects and perl hashes of hashes.
#
#              This is a private function.
#
##############################################################################
sub sprintData
{
    my ($preString,$data) = @_;

    my $outString = "";

    if (ref($data) eq "HASH")
    {
        my $key;
        foreach $key (sort { $a cmp $b } keys(%{$data}))
        {
            if (ref($$data{$key}) eq "")
            {
                my $value = defined($$data{$key}) ? $$data{$key} : "";
                $outString .= $preString."{'$key'} = \"".$value."\";\n";
            }
            else
            {
                if (ref($$data{$key}) =~ /Net::Jabber/)
                {
                    $outString .= $preString."{'$key'} = ".ref($$data{$key}).";\n";
                }
                else
                {
                    $outString .= $preString."{'$key'};\n";
                    $outString .= &sprintData($preString."{'$key'}->",$$data{$key});
                }
            }
        }
    }
    else
    {
        if (ref($data) eq "ARRAY")
        {
            my $index;
            foreach $index (0..$#{$data})
            {
                if (ref($$data[$index]) eq "")
                {
                    $outString .= $preString."[$index] = \"$$data[$index]\";\n";
                }
                else
                {
                    if (ref($$data[$index]) =~ /Net::Jabber/)
                    {
                        $outString .= $preString."[$index] = ".ref($$data[$index]).";\n";
                    }
                    else
                    {
                        $outString .= $preString."[$index];\n";
                        $outString .= &sprintData($preString."[$index]->",$$data[$index]);
                    }
                }
            }
        }
        else
        {
            if (ref($data) eq "REF")
            {
                $outString .= &sprintData($preString."->",$$data);
            }
            else
            {
                if (ref($data) eq "")
                {
                    $outString .= $preString." = \"$data\";\n";
                }
                else
                {
                     $outString .= $preString." = ".ref($data).";\n";
                }
            }
        }
    }

    return $outString;
}

=pod

=head1 VARIABLES

  $NONBLOCKING

Tells the Parser to enter into a nonblocking state.  This
might cause some funky behavior since you can get nested
callbacks while things are waiting.  1=on, 0=off(default).

=head1 EXAMPLES

simple example

  use XML::Stream qw( Tree );

  $stream = XML::Stream->new;

  my $status = $stream->Connect(hostname => "jabber.org",
                                port => 5222,
                                namespace => "jabber:client");

  if (!defined($status)) {
    print "ERROR: Could not connect to server\n";
    print "       (",$stream->GetErrorCode(),")\n";
    exit(0);
  }

  while($node = $stream->Process()) {
    # do something with $node
  }

  $stream->Disconnect();


Example using a handler

  use XML::Stream qw( Tree );

  $stream = XML::Stream->new;
  $stream->SetCallBacks(node=>\&noder);
  $stream->Connect(hostname => "jabber.org",
		   port => 5222,
		   namespace => "jabber:client",
		   timeout => undef) || die $!;

  # Blocks here forever, noder is called for incoming
  # packets when they arrive.
  while(defined($stream->Process())) { }

  print "ERROR: Stream died (",$stream->GetErrorCode(),")\n";

  sub noder
  {
    my $sid = shift;
    my $node = shift;
    # do something with $node
  }

=head1 AUTHOR

Tweaked, tuned, and brightness changes by Ryan Eatmon, reatmon@ti.com
in May of 2000.
Colorized, and Dolby Surround sound added by Thomas Charron,
tcharron@jabber.org
By Jeremie in October of 1999 for http://etherx.jabber.org/streams/

Currently maintained by Darian Anthony Patrick.

=head1 COPYRIGHT

Copyright (C) 1998-2004 Jabber Software Foundation http://jabber.org/

This module licensed under the LGPL, version 2.1.

=cut

1;