This file is indexed.

/usr/share/perl5/Net/XMPP/Protocol.pm is in libnet-xmpp-perl 1.02-3.

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
##############################################################################
#
#  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.
#
#  Copyright (C) 1998-2004 Jabber Software Foundation http://jabber.org/
#
##############################################################################

package Net::XMPP::Protocol;

=head1 NAME

Net::XMPP::Protocol - XMPP Protocol Module

=head1 SYNOPSIS

  Net::XMPP::Protocol is a module that provides a developer easy
  access to the XMPP Instant Messaging protocol.  It provides high
  level functions to the Net::XMPP Client object.  These functions are
  inherited by that modules.

=head1 DESCRIPTION

  Protocol.pm seeks to provide enough high level APIs and automation of
  the low level APIs that writing a XMPP Client in Perl is trivial.  For
  those that wish to work with the low level you can do that too, but
  those functions are covered in the documentation for each module.

  Net::XMPP::Protocol provides functions to login, send and receive
  messages, set personal information, create a new user account, manage
  the roster, and disconnect.  You can use all or none of the functions,
  there is no requirement.

  For more information on how the details for how Net::XMPP is written
  please see the help for Net::XMPP itself.

  For more information on writing a Client see Net::XMPP::Client.

=head2 Modes

  Several of the functions take a mode argument that let you specify how
  the function should behave:

    block - send the packet with an ID, and then block until an answer
            comes back.  You can optionally specify a timeout so that
            you do not block forever.

    nonblock - send the packet with an ID, but then return that id and
               control to the master program.  Net::XMPP is still
               tracking this packet, so you must use the CheckID function
               to tell when it comes in.  (This might not be very
               useful...)

    passthru - send the packet with an ID, but do NOT register it with
               Net::XMPP, then return the ID.  This is useful when
               combined with the XPath function because you can register
               a one shot function tied to the id you get back.


=head2 Basic Functions

    use Net::XMPP qw( Client );
    $Con = new Net::XMPP::Client();                  # From
    $status = $Con->Connect(hostname=>"jabber.org"); # Net::XMPP::Client

    $Con->SetCallBacks(send=>\&sendCallBack,
                       receive=>\&receiveCallBack,
                       message=>\&messageCallBack,
                       iq=>\&handleTheIQTag);

    $Con->SetMessageCallBacks(normal=>\&messageNormalCB,
                              chat=>\&messageChatCB);

    $Con->SetPresenceCallBacks(available=>\&presenceAvailableCB,
                               unavailable=>\&presenceUnavailableCB);

    $Con->SetIQCallBacks("custom-namespace"=>
                                             {
                                                 get=>\&iqCustomGetCB,
                                                 set=>\&iqCustomSetCB,
                                                 result=>\&iqCustomResultCB,
                                             },
                                             etc...
                                            );

    $Con->SetXPathCallBacks("/message[@type='chat']"=>&messageChatCB,
                            "/message[@type='chat']"=>&otherMessageChatCB,
                            ...
                           );

    $Con->RemoveXPathCallBacks("/message[@type='chat']"=>&otherMessageChatCB);

    $Con->SetDirectXPathCallBacks("/anything"=>&anythingCB,
                                  "/anotherthing[@foo='bar']"=>&anotherthingFooBarCB,
                                  ...
                                 );

    $Con->RemoveDirectXPathCallBacks("/message[@type='chat']"=>&otherMessageChatCB);

    $error = $Con->GetErrorCode();
    $Con->SetErrorCode("Timeout limit reached");

    $status = $Con->Process();
    $status = $Con->Process(5);

    $Con->Send($object);
    $Con->Send("<tag>XML</tag>");

    $Con->Send($object,1);
    $Con->Send("<tag>XML</tag>",1);

    $Con->Disconnect();

=head2 ID Functions

    $id         = $Con->SendWithID($sendObj);
    $id         = $Con->SendWithID("<tag>XML</tag>");
    $receiveObj = $Con->SendAndReceiveWithID($sendObj);
    $receiveObj = $Con->SendAndReceiveWithID($sendObj,
                                             10);
    $receiveObj = $Con->SendAndReceiveWithID("<tag>XML</tag>");
    $receiveObj = $Con->SendAndReceiveWithID("<tag>XML</tag>",
                                             5);
    $yesno      = $Con->ReceivedID($id);
    $receiveObj = $Con->GetID($id);
    $receiveObj = $Con->WaitForID($id);
    $receiveObj = $Con->WaitForID($id,
                                  20);

=head2 Namespace Functions

    $Con->AddNamespace(ns=>"foo:bar",
                       tag=>"myfoo",
                       xpath=>{Foo=>{ path=> "foo/text()" },
                               Bar=>{ path=> "bar/text()" },
                               FooBar=>{ type=> "master" },
                              }
                      );

=head2 Message Functions

    $Con->MessageSend(to=>"bob@jabber.org",
                      subject=>"Lunch",
                      body=>"Let's go grab some...\n",
                      thread=>"ABC123",
                      priority=>10);

=head2 Presence Functions

    $Con->PresenceSend();
    $Con->PresenceSend(type=>"unavailable");
    $Con->PresenceSend(show=>"away");
    $Con->PresenceSend(signature=>...signature...);

=head2 Subscription Functions

    $Con->Subscription(type=>"subscribe",
                       to=>"bob@jabber.org");

    $Con->Subscription(type=>"unsubscribe",
                       to=>"bob@jabber.org");

    $Con->Subscription(type=>"subscribed",
                       to=>"bob@jabber.org");

    $Con->Subscription(type=>"unsubscribed",
                       to=>"bob@jabber.org");

=head2 Presence DB Functions

    $Con->PresenceDB();

    $Con->PresenceDBParse(Net::XMPP::Presence);

    $Con->PresenceDBDelete("bob\@jabber.org");
    $Con->PresenceDBDelete(Net::XMPP::JID);

    $Con->PresenceDBClear();

    $presence  = $Con->PresenceDBQuery("bob\@jabber.org");
    $presence  = $Con->PresenceDBQuery(Net::XMPP::JID);

    @resources = $Con->PresenceDBResources("bob\@jabber.org");
    @resources = $Con->PresenceDBResources(Net::XMPP::JID);

=head2 IQ  Functions

=head2 Auth Functions

    @result = $Con->AuthSend();
    @result = $Con->AuthSend(username=>"bob",
                             password=>"bobrulez",
                             resource=>"Bob");

=head2 Register Functions

    %hash   = $Con->RegisterRequest();
    %hash   = $Con->RegisterRequest(to=>"transport.jabber.org");
    %hash   = $Con->RegisterRequest(to=>"transport.jabber.org",
                                    timeout=>10);

    @result = $Con->RegisterSend(to=>"somewhere",
                                 username=>"newuser",
                                 resource=>"New User",
                                 password=>"imanewbie",
                                 email=>"newguy@new.com",
                                 key=>"some key");

=head2 Roster Functions

    $Roster = $Con->Roster();

    %roster = $Con->RosterParse($iq);
    %roster = $Con->RosterGet();
    $Con->RosterRequest();
    $Con->RosterAdd(jid=>"bob\@jabber.org",
                    name=>"Bob");
    $Con->RosterRemove(jid=>"bob@jabber.org");

=head2 Roster DB Functions

    $Con->RosterDB();

    $Con->RosterDBParse(Net::XMPP::IQ);

    $Con->RosterDBAdd("bob\@jabber.org",
                      name=>"Bob",
                      groups=>["foo"]
                     );

    $Con->RosterDBRemove("bob\@jabber.org");
    $Con->RosterDBRemove(Net::XMPP::JID);

    $Con->RosterDBClear();

    if ($Con->RosterDBExists("bob\@jabber.org")) { ...
    if ($Con->RosterDBExists(Net::XMPP::JID)) { ...

    @jids = $Con->RosterDBJIDs();

    if ($Con->RosterDBGroupExists("foo")) { ...

    @groups = $Con->RosterDBGroups();

    @jids = $Con->RosterDBGroupJIDs("foo");

    @jids = $Con->RosterDBNonGroupJIDs();

    %hash = $Con->RosterDBQuery("bob\@jabber.org");
    %hash = $Con->RosterDBQuery(Net::XMPP::JID);

    $value = $Con->RosterDBQuery("bob\@jabber.org","name");
    $value = $Con->RosterDBQuery(Net::XMPP::JID,"groups");


=head1 METHODS

=head2 Basic Functions

    GetErrorCode() - returns a string that will hopefully contain some
                     useful information about why a function returned
                     an undef to you.

    SetErrorCode(string) - set a useful error message before you return
                           an undef to the caller.

    SetCallBacks(message=>function,  - sets the callback functions for
                 presence=>function,   the top level tags listed.  The
                 iq=>function,         available tags to look for are
                 send=>function,       <message/>, <presence/>, and
                 receive=>function,    <iq/>.  If a packet is received
                 update=>function)     with an ID which is found in the
                                       registered ID list (see RegisterID
                                       below) then it is not sent to
                                       these functions, instead it
                                       is inserted into a LIST and can
                                       be retrieved by some functions
                                       we will mention later.

                                       send and receive are used to
                                       log what XML is sent and received.
                                       update is used as way to update
                                       your program while waiting for
                                       a packet with an ID to be
                                       returned (useful for GUI apps).

                                       A major change that came with
                                       the last release is that the
                                       session id is passed to the
                                       callback as the first argument.
                                       This was done to facilitate
                                       the Server module.

                                       The next argument depends on
                                       which callback you are talking
                                       about.  message, presence, and iq
                                       all get passed in Net::XMPP
                                       objects that match those types.
                                       send and receive get passed in
                                       strings.  update gets passed
                                       nothing, not even the session id.

                                       If you set the function to undef,
                                       then the callback is removed from
                                       the list.

    SetPresenceCallBacks(type=>function - sets the callback functions for
                         etc...)          the specified presence type.
                                          The function takes types as the
                                          main key, and lets you specify
                                          a function for each type of
                                          packet you can get.
                                            "available"
                                            "unavailable"
                                            "subscribe"
                                            "unsubscribe"
                                            "subscribed"
                                            "unsubscribed"
                                            "probe"
                                            "error"
                                          When it gets a <presence/>
                                          packet it checks the type=''
                                          for a defined callback.  If
                                          there is one then it calls the
                                          function with two arguments:
                                            the session ID, and the
                                            Net::XMPP::Presence object.

                                          If you set the function to
                                          undef, then the callback is
                                          removed from the list.

                        NOTE: If you use this, which is a cleaner method,
                              then you must *NOT* specify a callback for
                              presence in the SetCallBacks function.

                                          Net::XMPP defines a few default
                                          callbacks for various types:

                                          "subscribe" -
                                            replies with subscribed

                                          "unsubscribe" -
                                            replies with unsubscribed

                                          "subscribed" -
                                            replies with subscribed

                                          "unsubscribed" -
                                            replies with unsubscribed


    SetMessageCallBacks(type=>function, - sets the callback functions for
                        etc...)           the specified message type. The
                                          function takes types as the
                                          main key, and lets you specify
                                          a function for each type of
                                          packet you can get.
                                           "normal"
                                           "chat"
                                           "groupchat"
                                           "headline"
                                           "error"
                                         When it gets a <message/> packet
                                         it checks the type='' for a
                                         defined callback. If there is
                                         one then it calls the function
                                         with two arguments:
                                           the session ID, and the
                                           Net::XMPP::Message object.

                                         If you set the function to
                                         undef, then the callback is
                                         removed from the list.

                       NOTE: If you use this, which is a cleaner method,
                             then you must *NOT* specify a callback for
                             message in the SetCallBacks function.


    SetIQCallBacks(namespace=>{      - sets the callback functions for
                     get=>function,    the specified namespace. The
                     set=>function,    function takes namespaces as the
                     result=>function  main key, and lets you specify a
                   },                  function for each type of packet
                   etc...)             you can get.
                                         "get"
                                         "set"
                                         "result"
                                       When it gets an <iq/> packet it
                                       checks the type='' and the
                                       xmlns='' for a defined callback.
                                       If there is one then it calls
                                       the function with two arguments:
                                       the session ID, and the
                                       Net::XMPP::xxxx object.

                                       If you set the function to undef,
                                       then the callback is removed from
                                       the list.

                       NOTE: If you use this, which is a cleaner method,
                             then you must *NOT* specify a callback for
                             iq in the SetCallBacks function.

    SetXPathCallBacks(xpath=>function, - registers a callback function
                      etc...)            for each xpath specified.  If
                                         Net::XMPP matches the xpath,
                                         then it calls the function with
                                         two arguments:
                                           the session ID, and the
                                           Net::XMPP::Message object.

                                         Xpaths are rooted at each
                                         packet:
                                           /message[@type="chat"]
                                           /iq/*[xmlns="jabber:iq:roster"][1]
                                           ...

    RemoveXPathCallBacks(xpath=>function, - unregisters a callback
                         etc...)            function for each xpath
                                            specified.

    SetDirectXPathCallBacks(xpath=>function, - registers a callback function
                            etc...)            for each xpath specified.  If
                                               Net::XMPP matches the xpath,
                                               then it calls the function with
                                               two arguments:
                                                 the session ID, and the
                                                 XML::Stream::Node object.

                                               Xpaths are rooted at each
                                               packet:
                                                 /anything
                                                 /anotherthing/foo/[1]
                                                 ...

                                               The big difference between this
                                               and regular XPathCallBacks is
                                               the fact that this passes in
                                               the XML directly and not a
                                               Net::XMPP based object.

    RemoveDirectXPathCallBacks(xpath=>function, - unregisters a callback
                               etc...)            function for each xpath
                                                  specified.

    Process(integer) - takes the timeout period as an argument.  If no
                       timeout is listed then the function blocks until
                       a packet is received.  Otherwise it waits that
                       number of seconds and then exits so your program
                       can continue doing useful things.  NOTE: This is
                       important for GUIs.  You need to leave time to
                       process GUI commands even if you are waiting for
                       packets.  The following are the possible return
                       values, and what they mean:

                           1   - Status ok, data received.
                           0   - Status ok, no data received.
                         undef - Status not ok, stop processing.

                       IMPORTANT: You need to check the output of every
                       Process.  If you get an undef then the connection
                       died and you should behave accordingly.

    Send(object,         - takes either a Net::XMPP::xxxxx object or
         ignoreActivity)   an XML string as an argument and sends it to
    Send(string,           the server.  If you set ignoreActivty to 1,
         ignoreActivity)   then the XML::Stream module will not record
                           this packet as couting towards user activity.
=head2 ID Functions

    SendWithID(object) - takes either a Net::XMPP::xxxxx object or an
    SendWithID(string)   XML string as an argument, adds the next
                         available ID number and sends that packet to
                         the server.  Returns the ID number assigned.

    SendAndReceiveWithID(object,  - uses SendWithID and WaitForID to
                         timeout)   provide a complete way to send and
    SendAndReceiveWithID(string,    receive packets with IDs.  Can take
                         timeout)   either a Net::XMPP::xxxxx object
                                    or an XML string.  Returns the
                                    proper Net::XMPP::xxxxx object
                                    based on the type of packet
                                    received.  The timeout is passed
                                    on to WaitForID, see that function
                                    for how the timeout works.

    ReceivedID(integer) - returns 1 if a packet has been received with
                          specified ID, 0 otherwise.

    GetID(integer) - returns the proper Net::XMPP::xxxxx object based
                     on the type of packet received with the specified
                     ID.  If the ID has been received the GetID returns
                     0.

    WaitForID(integer, - blocks until a packet with the ID is received.
              timeout)   Returns the proper Net::XMPP::xxxxx object
                         based on the type of packet received.  If the
                         timeout limit is reached then if the packet
                         does come in, it will be discarded.


    NOTE:  Only <iq/> officially support ids, so sending a <message/>, or
           <presence/> with an id is a risk.  The server will ignore the
           id tag and pass it through, so both clients must support the
           id tag for these functions to be useful.

=head2 Namespace Functions

    AddNamespace(ns=>string,  - This function is very complex.
                 tag=>string,   It is a little too complex to
                 xpath=>hash)   discuss within the confines of
                                this small paragraph.  Please
                                refer to the man page for
                                Net::XMPP::Namespaces for the
                                full documentation on this
                                subject.

=head2 Message Functions

    MessageSend(hash) - takes the hash and passes it to SetMessage in
                        Net::XMPP::Message (refer there for valid
                        settings).  Then it sends the message to the
                        server.

=head2 Presence Functions

    PresenceSend()                  - no arguments will send an empty
    PresenceSend(hash,                Presence to the server to tell it
                 signature=>string)   that you are available.  If you
                                      provide a hash, then it will pass
                                      that hash to the SetPresence()
                                      function as defined in the
                                      Net::XMPP::Presence module.
                                      Optionally, you can specify a
                                      signature and a jabber:x:signed
                                      will be placed in the <presence/>.

=head2 Subscription Functions

    Subscription(hash) - taks the hash and passes it to SetPresence in
                         Net::XMPP::Presence (refer there for valid
                         settings).  Then it sends the subscription to
                         server.

                         The valid types of subscription are:

                           subscribe    - subscribe to JID's presence
                           unsubscribe  - unsubscribe from JID's presence
                           subscribed   - response to a subscribe
                           unsubscribed - response to an unsubscribe

=head2 Presence DB Functions

    PresenceDB() - Tell the object to initialize the callbacks to
                   automatically populate the Presence DB.

    PresenceDBParse(Net::XMPP::Presence) - for every presence that you
                                             receive pass the Presence
                                             object to the DB so that
                                             it can track the resources
                                             and priorities for you.
                                             Returns either the presence
                                             passed in, if it not able
                                             to parsed for the DB, or the
                                             current presence as found by
                                             the PresenceDBQuery
                                             function.

    PresenceDBDelete(string|Net::XMPP::JID) - delete thes JID entry
                                                from the DB.

    PresenceDBClear() - delete all entries in the database.

    PresenceDBQuery(string|Net::XMPP::JID) - returns the NX::Presence
                                               that was last received for
                                               the highest priority of
                                               this JID.  You can pass
                                               it a string or a NX::JID
                                               object.

    PresenceDBResources(string|Net::XMPP::JID) - returns an array of
                                                   resources in order
                                                   from highest priority
                                                   to lowest.

=head2 IQ Functions

=head2 Auth Functions

    AuthSend(username=>string, - takes all of the information and
             password=>string,   builds a Net::XMPP::IQ::Auth packet.
             resource=>string)   It then sends that packet to the
                                 server with an ID and waits for that
                                 ID to return.  Then it looks in
                                 resulting packet and determines if
                                 authentication was successful for not.
                                 The array returned from AuthSend looks
                                 like this:
                                   [ type , message ]
                                 If type is "ok" then authentication
                                 was successful, otherwise message
                                 contains a little more detail about the
                                 error.

=head2 IQ::Register Functions

    RegisterRequest(to=>string,  - send an <iq/> request to the specified
                    timeout=>int)  server/transport, if not specified it
    RegisterRequest()              sends to the current active server.
                                   The function returns a hash that
                                   contains the required fields.   Here
                                   is an example of the hash:

                                   $hash{fields}    - The raw fields from
                                                      the iq:register.
                                                      To be used if there
                                                      is no x:data in the
                                                      packet.
                                   $hash{instructions} - How to fill out
                                                         the form.
                                   $hash{form}   - The new dynamic forms.

                                   In $hash{form}, the fields that are
                                   present are the required fields the
                                   server needs.

    RegisterSend(hash) - takes the contents of the hash and passes it
                         to the SetRegister function in the module
                         Net::XMPP::Query jabber:iq:register namespace.
                         This function returns an array that looks like
                         this:

                            [ type , message ]

                         If type is "ok" then registration was
                         successful, otherwise message contains a
                         little more detail about the error.

=head2 Roster Functions

    Roster() - returns a Net::XMPP::Roster object.  This will automatically
               intercept all of the roster and presence packets sent from
               the server and give you an accurate Roster.  For more
               information please read the man page for Net::XMPP::Roster.

    RosterParse(IQ object) - returns a hash that contains the roster
                             parsed into the following data structure:

                  $roster{'bob@jabber.org'}->{name}
                                      - Name you stored in the roster

                  $roster{'bob@jabber.org'}->{subscription}
                                      - Subscription status
                                        (to, from, both, none)

                  $roster{'bob@jabber.org'}->{ask}
                                      - The ask status from this user
                                        (subscribe, unsubscribe)

                  $roster{'bob@jabber.org'}->{groups}
                                      - Array of groups that
                                        bob@jabber.org is in

    RosterGet() - sends an empty Net::XMPP::IQ::Roster tag to the
                  server so the server will send the Roster to the
                  client.  Returns the above hash from RosterParse.

    RosterRequest() - sends an empty Net::XMPP::IQ::Roster tag to the
                      server so the server will send the Roster to the
                      client.

    RosterAdd(hash) - sends a packet asking that the jid be
                      added to the roster.  The hash format
                      is defined in the SetItem function
                      in the Net::XMPP::Query jabber:iq:roster
                      namespace.

    RosterRemove(hash) - sends a packet asking that the jid be
                         removed from the roster.  The hash
                         format is defined in the SetItem function
                         in the Net::XMPP::Query jabber:iq:roster
                         namespace.

=head2 Roster DB Functions

    RosterDB() - Tell the object to initialize the callbacks to
                 automatically populate the Roster DB.  If you do this,
                 then make sure that you call RosterRequest() instead of
                 RosterGet() so that the callbacks can catch it and
                 parse it.

    RosterDBParse(IQ object) - If you want to manually control the
                               database, then you can pass in all iq
                               packets with jabber:iq:roster queries to
                               this function.

    RosterDBAdd(jid,hash) - Add a new JID into the roster DB.  The JID
                            is either a string, or a Net::XMPP::JID
                            object.  The hash must be the same format as
                            the has returned by RosterParse above, and
                            is the actual hash, not a reference.

    RosterDBRemove(jid) - Remove a JID from the roster DB. The JID is
                          either a string, or a Net::XMPP::JID object.

    RosterDBClear() - Remove all JIDs from the roster DB.

    RosterDBExists(jid) - return 1 if the JID exists in the roster DB,
                          undef otherwise.  The JID is either a string,
                          or a Net::XMPP::JID object.

    RosterDBJIDs() - returns a list of Net::XMPP::JID objects that
                     represents all of the JIDs in the DB.

    RosterDBGroups() - returns the complete list of roster groups in the
                       roster.

    RosterDBGroupExists(group) - return 1 if the group is a group in the
                                 roster DB, undef otherwise.

    RosterDBGroupJIDs(group) - returns a list of Net::XMPP::JID objects
                               that represents all of the JIDs in the
                               specified roster group.

    RosterDBNonGroupJIDs() - returns a list of Net::XMPP::JID objects
                             that represents all of the JIDs not in a
                             roster group.

    RosterDBQuery(jid) - returns a hash containing the data from the
                         roster DB for the specified JID.  The JID is
                         either a string, or a Net::XMPP::JID object.
                         The hash format the same as in RosterParse
                         above.

    RosterDBQuery(jid,key) - returns the entry from the above hash for
                             the given key.  The available keys are:
                               name, ask, subsrcription and groups
                             The JID is either a string, or a
                             Net::XMPP::JID object.


=head1 AUTHOR

Ryan Eatmon

=head1 COPYRIGHT

This module is free software, you can redistribute it and/or modify it
under the LGPL.

=cut

use Net::XMPP::Roster;
use Net::XMPP::PrivacyLists;
use strict;
use Carp;
use vars qw( %XMLNS %NEWOBJECT $SASL_CALLBACK $TLS_CALLBACK );

##############################################################################
# Define the namespaces in an easy/constant manner.
#-----------------------------------------------------------------------------
# 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";
##############################################################################

##############################################################################
# BuildObject takes a root tag and builds the correct object.  NEWOBJECT is
# the table that maps tag to package.  Override these, or provide new ones.
#-----------------------------------------------------------------------------
$NEWOBJECT{'iq'}       = "Net::XMPP::IQ";
$NEWOBJECT{'message'}  = "Net::XMPP::Message";
$NEWOBJECT{'presence'} = "Net::XMPP::Presence";
$NEWOBJECT{'jid'}      = "Net::XMPP::JID";
##############################################################################

sub _message  { shift; my $o; eval "\$o = new $NEWOBJECT{'message'}(\@_);"; return $o;  }
sub _presence { shift; my $o; eval "\$o = new $NEWOBJECT{'presence'}(\@_);"; return $o; }
sub _iq       { shift; my $o; eval "\$o = new $NEWOBJECT{'iq'}(\@_);"; return $o;       }
sub _jid      { shift; my $o; eval "\$o = new $NEWOBJECT{'jid'}(\@_);"; return $o;      }

###############################################################################
#+-----------------------------------------------------------------------------
#|
#| Base API
#|
#+-----------------------------------------------------------------------------
###############################################################################

###############################################################################
#
# GetErrorCode - if you are returned an undef, you can call this function
#                and hopefully learn more information about the problem.
#
###############################################################################
sub GetErrorCode
{
    my $self = shift;
    return ((exists($self->{ERRORCODE}) && ($self->{ERRORCODE} ne "")) ?
            $self->{ERRORCODE} :
            $!
           );
}


###############################################################################
#
# SetErrorCode - sets the error code so that the caller can find out more
#                information about the problem
#
###############################################################################
sub SetErrorCode
{
    my $self = shift;
    my ($errorcode) = @_;
    $self->{ERRORCODE} = $errorcode;
}


###############################################################################
#
# CallBack - Central callback function.  If a packet comes back with an ID
#            and the tag and ID have been registered then the packet is not
#            returned as normal, instead it is inserted in the LIST and
#            stored until the user wants to fetch it.  If the tag and ID
#            are not registered the function checks if a callback exists
#            for this tag, if it does then that callback is called,
#            otherwise the function drops the packet since it does not know
#            how to handle it.
#
###############################################################################
sub CallBack
{
    my $self = shift;
    my $sid = shift;
    my ($object) = @_;

    my $tag;
    my $id;
    my $tree;

    if (ref($object) !~ /^Net::XMPP/)
    {
        if ($self->{DEBUG}->GetLevel() >= 1 || exists($self->{CB}->{receive}))
        {
            my $xml = $object->GetXML();
            $self->{DEBUG}->Log1("CallBack: sid($sid) received($xml)");
            &{$self->{CB}->{receive}}($sid,$xml) if exists($self->{CB}->{receive});
        }

        $tag = $object->get_tag();
        $id = "";
        $id = $object->get_attrib("id")
            if defined($object->get_attrib("id"));
        $tree = $object;
    }
    else
    {
        $tag = $object->GetTag();
        $id = $object->GetID();
        $tree = $object->GetTree();
    }

    $self->{DEBUG}->Log1("CallBack: tag($tag)");
    $self->{DEBUG}->Log1("CallBack: id($id)") if ($id ne "");

    my $pass = 1;
    $pass = 0
        if (!exists($self->{CB}->{$tag}) &&
            !exists($self->{CB}->{XPath}) &&
            !exists($self->{CB}->{DirectXPath}) &&
            !$self->CheckID($tag,$id)
           );

    if ($pass)
    {
        $self->{DEBUG}->Log1("CallBack: we either want it or were waiting for it.");

        if (exists($self->{CB}->{DirectXPath}))
        {
            $self->{DEBUG}->Log1("CallBack: check directxpath");

            my $direct_pass = 0;

            foreach my $xpath (keys(%{$self->{CB}->{DirectXPath}}))
            {
                $self->{DEBUG}->Log1("CallBack: check directxpath($xpath)");
                if ($object->XPathCheck($xpath))
                {
                    foreach my $func (keys(%{$self->{CB}->{DirectXPath}->{$xpath}}))
                    {
                        $self->{DEBUG}->Log1("CallBack: goto directxpath($xpath) function($func)");
                        &{$self->{CB}->{DirectXPath}->{$xpath}->{$func}}($sid,$object);
                        $direct_pass = 1;
                    }
                }
            }

            return if $direct_pass;
        }

        my $NXObject;
        if (ref($object) !~ /^Net::XMPP/)
        {
            $NXObject = $self->BuildObject($tag,$object);
        }
        else
        {
            $NXObject = $object;
        }

        if ($NXObject == -1)
        {
            $self->{DEBUG}->Log1("CallBack: DANGER!! DANGER!! We didn't build a packet!  We're all gonna die!!");
        }
        else
        {
            if ($self->CheckID($tag,$id))
            {
                $self->{DEBUG}->Log1("CallBack: found registry entry: tag($tag) id($id)");
                $self->DeregisterID($tag,$id);
                if ($self->TimedOutID($id))
                {
                    $self->{DEBUG}->Log1("CallBack: dropping packet due to timeout");
                    $self->CleanID($id);
                }
                else
                {
                    $self->{DEBUG}->Log1("CallBack: they still want it... we still got it...");
                    $self->GotID($id,$NXObject);
                }
            }
            else
            {
                $self->{DEBUG}->Log1("CallBack: no registry entry");

                if (exists($self->{CB}->{XPath}))
                {
                    $self->{DEBUG}->Log1("CallBack: check xpath");

                    foreach my $xpath (keys(%{$self->{CB}->{XPath}}))
                    {
                        if ($NXObject->GetTree()->XPathCheck($xpath))
                        {
                            foreach my $func (keys(%{$self->{CB}->{XPath}->{$xpath}}))
                            {
                                $self->{DEBUG}->Log1("CallBack: goto xpath($xpath) function($func)");
                                &{$self->{CB}->{XPath}->{$xpath}->{$func}}($sid,$NXObject);
                            }
                        }
                    }
                }

                if (exists($self->{CB}->{$tag}))
                {
                    $self->{DEBUG}->Log1("CallBack: goto user function($self->{CB}->{$tag})");
                    &{$self->{CB}->{$tag}}($sid,$NXObject);
                }
                else
                {
                    $self->{DEBUG}->Log1("CallBack: no defined function.  Dropping packet.");
                }
            }
        }
    }
    else
    {
        $self->{DEBUG}->Log1("CallBack: a packet that no one wants... how sad. =(");
    }
}


###############################################################################
#
# BuildObject - turn the packet into an object.
#
###############################################################################
sub BuildObject
{
    my $self = shift;
    my ($tag,$tree) = @_;

    my $obj = -1;

    if (exists($NEWOBJECT{$tag}))
    {
        $self->{DEBUG}->Log1("BuildObject: tag($tag) package($NEWOBJECT{$tag})");
        eval "\$obj = new $NEWOBJECT{$tag}(\$tree);";
    }

    return $obj;
}


###############################################################################
#
# SetCallBacks - Takes a hash with top level tags to look for as the keys
#                and pointers to functions as the values.  The functions
#                are called and passed the XML::Parser::Tree objects
#                generated by XML::Stream.
#
###############################################################################
sub SetCallBacks
{
    my $self = shift;
    while($#_ >= 0)
    {
        my $func = pop(@_);
        my $tag = pop(@_);
        $self->{DEBUG}->Log1("SetCallBacks: tag($tag) func($func)");
        if (defined($func))
        {
            $self->{CB}->{$tag} = $func;
        }
        else
        {
            delete($self->{CB}->{$tag});
        }
        $self->{STREAM}->SetCallBacks(update=>$func) if ($tag eq "update");
    }
}


###############################################################################
#
# SetIQCallBacks - define callbacks for the namespaces inside an iq.
#
###############################################################################
sub SetIQCallBacks
{
    my $self = shift;

    while($#_ >= 0)
    {
        my $hash = pop(@_);
        my $namespace = pop(@_);

        foreach my $type (keys(%{$hash}))
        {
	    	$self->{DEBUG}->Log1("SetIQCallBacks: type($type) func($hash->{$type}) ".
	    		"namespace($namespace)");
            if (defined($hash->{$type}))
            {
                $self->{CB}->{IQns}->{$namespace}->{$type} = $hash->{$type};
            }
            else
            {
                delete($self->{CB}->{IQns}->{$namespace}->{$type});
            }
        }
    }
}


###############################################################################
#
# SetPresenceCallBacks - define callbacks for the different presence packets.
#
###############################################################################
sub SetPresenceCallBacks
{
    my $self = shift;
    my (%types) = @_;

    foreach my $type (keys(%types))
    {
    	$self->{DEBUG}->Log1("SetPresenceCallBacks: type($type) func($types{$type})");

        if (defined($types{$type}))
        {
            $self->{CB}->{Pres}->{$type} = $types{$type};
        }
        else
        {
            delete($self->{CB}->{Pres}->{$type});
        }
    }
}


###############################################################################
#
# SetMessageCallBacks - define callbacks for the different message packets.
#
###############################################################################
sub SetMessageCallBacks
{
    my $self = shift;
    my (%types) = @_;

    foreach my $type (keys(%types))
    {
    	$self->{DEBUG}->Log1("SetMessageCallBacks: type($type) func($types{$type})");

        if (defined($types{$type}))
        {
            $self->{CB}->{Mess}->{$type} = $types{$type};
        }
        else
        {
            delete($self->{CB}->{Mess}->{$type});
        }
    }
}


###############################################################################
#
# SetXPathCallBacks - define callbacks for packets based on XPath.
#
###############################################################################
sub SetXPathCallBacks
{
    my $self = shift;
    my (%xpaths) = @_;

    foreach my $xpath (keys(%xpaths))
    {
        $self->{DEBUG}->Log1("SetXPathCallBacks: xpath($xpath) func($xpaths{$xpath})");
        $self->{CB}->{XPath}->{$xpath}->{$xpaths{$xpath}} = $xpaths{$xpath};
    }
}


###############################################################################
#
# RemoveXPathCallBacks - remove callbacks for packets based on XPath.
#
###############################################################################
sub RemoveXPathCallBacks
{
    my $self = shift;
    my (%xpaths) = @_;

    foreach my $xpath (keys(%xpaths))
    {
        $self->{DEBUG}->Log1("RemoveXPathCallBacks: xpath($xpath) func($xpaths{$xpath})");
        delete($self->{CB}->{XPath}->{$xpath}->{$xpaths{$xpath}});
        delete($self->{CB}->{XPath}->{$xpath})
            if (scalar(keys(%{$self->{CB}->{XPath}->{$xpath}})) == 0);
        delete($self->{CB}->{XPath})
            if (scalar(keys(%{$self->{CB}->{XPath}})) == 0);
    }
}


###############################################################################
#
# SetDirectXPathCallBacks - define callbacks for packets based on XPath.
#
###############################################################################
sub SetDirectXPathCallBacks
{
    my $self = shift;
    my (%xpaths) = @_;

    foreach my $xpath (keys(%xpaths))
    {
        $self->{DEBUG}->Log1("SetDirectXPathCallBacks: xpath($xpath) func($xpaths{$xpath})");
        $self->{CB}->{DirectXPath}->{$xpath}->{$xpaths{$xpath}} = $xpaths{$xpath};
    }
}


###############################################################################
#
# RemoveDirectXPathCallBacks - remove callbacks for packets based on XPath.
#
###############################################################################
sub RemoveDirectXPathCallBacks
{
    my $self = shift;
    my (%xpaths) = @_;

    foreach my $xpath (keys(%xpaths))
    {
        $self->{DEBUG}->Log1("RemoveDirectXPathCallBacks: xpath($xpath) func($xpaths{$xpath})");
        delete($self->{CB}->{DirectXPath}->{$xpath}->{$xpaths{$xpath}});
        delete($self->{CB}->{DirectXPath}->{$xpath})
            if (scalar(keys(%{$self->{CB}->{DirectXPath}->{$xpath}})) == 0);
        delete($self->{CB}->{DirectXPath})
            if (scalar(keys(%{$self->{CB}->{DirectXPath}})) == 0);
    }
}


###############################################################################
#
# Send - Takes either XML or a Net::XMPP::xxxx object and sends that
#        packet to the server.
#
###############################################################################
sub Send
{
    my $self = shift;
    my $object = shift;
    my $ignoreActivity = shift;
    $ignoreActivity = 0 unless defined($ignoreActivity);

    if (ref($object) eq "")
    {
        $self->SendXML($object,$ignoreActivity);
    }
    else
    {
        $self->SendXML($object->GetXML(),$ignoreActivity);
    }
}


###############################################################################
#
# SendXML - Sends the XML packet to the server
#
###############################################################################
sub SendXML
{
    my $self = shift;
    my $xml = shift;
    my $ignoreActivity = shift;
    $ignoreActivity = 0 unless defined($ignoreActivity);

    $self->{DEBUG}->Log1("SendXML: sent($xml)");
    &{$self->{CB}->{send}}($self->GetStreamID(),$xml) if exists($self->{CB}->{send});
    $self->{STREAM}->IgnoreActivity($self->GetStreamID(),$ignoreActivity);
    $self->{STREAM}->Send($self->GetStreamID(),$xml);
    $self->{STREAM}->IgnoreActivity($self->GetStreamID(),0);
}


###############################################################################
#
# SendWithID - Take either XML or a Net::XMPP::xxxx object and send it
#              with the next available ID number.  Then return that ID so
#              the client can track it.
#
###############################################################################
sub SendWithID
{
    my $self = shift;
    my ($object) = @_;

    #--------------------------------------------------------------------------
    # Take the current XML stream and insert an id attrib at the top level.
    #--------------------------------------------------------------------------
    my $id = $self->UniqueID();

    $self->{DEBUG}->Log1("SendWithID: id($id)");

    my $xml;
    if (ref($object) eq "")
    {
        $self->{DEBUG}->Log1("SendWithID: in($object)");
        $xml = $object;
        $xml =~ s/^(\<[^\>]+)(\>)/$1 id\=\'$id\'$2/;
        my ($tag) = ($xml =~ /^\<(\S+)\s/);
        $self->RegisterID($tag,$id);
    }
    else
    {
        $self->{DEBUG}->Log1("SendWithID: in(",$object->GetXML(),")");
        $object->SetID($id);
        $xml = $object->GetXML();
        $self->RegisterID($object->GetTag(),$id);
    }
    $self->{DEBUG}->Log1("SendWithID: out($xml)");

    #--------------------------------------------------------------------------
    # Send the new XML string.
    #--------------------------------------------------------------------------
    $self->SendXML($xml);

    #--------------------------------------------------------------------------
    # Return the ID number we just assigned.
    #--------------------------------------------------------------------------
    return $id;
}


###############################################################################
#
# UniqueID - Increment and return a new unique ID.
#
###############################################################################
sub UniqueID
{
    my $self = shift;

    my $id_num = $self->{RCVDB}->{currentID};

    $self->{RCVDB}->{currentID}++;

    return "netjabber-$id_num";
}


###############################################################################
#
# SendAndReceiveWithID - Take either XML or a Net::XMPP::xxxxx object and
#                        send it with the next ID.  Then wait for that ID
#                        to come back and return the response in a
#                        Net::XMPP::xxxx object.
#
###############################################################################
sub SendAndReceiveWithID
{
    my $self = shift;
    my ($object,$timeout) = @_;
    &{$self->{CB}->{startwait}}() if exists($self->{CB}->{startwait});
    $self->{DEBUG}->Log1("SendAndReceiveWithID: object($object)");
    my $id = $self->SendWithID($object);
    $self->{DEBUG}->Log1("SendAndReceiveWithID: sent with id($id)");
    my $packet = $self->WaitForID($id,$timeout);
    &{$self->{CB}->{endwait}}() if exists($self->{CB}->{endwait});
    return $packet;
}


###############################################################################
#
# ReceivedID - returns 1 if a packet with the ID has been received, or 0
#              if it has not.
#
###############################################################################
sub ReceivedID
{
    my $self = shift;
    my ($id) = @_;

    $self->{DEBUG}->Log1("ReceivedID: id($id)");
    return 1 if exists($self->{RCVDB}->{$id});
    $self->{DEBUG}->Log1("ReceivedID: nope...");
    return 0;
}


###############################################################################
#
# GetID - Return the Net::XMPP::xxxxx object that is stored in the LIST
#         that matches the ID if that ID exists.  Otherwise return 0.
#
###############################################################################
sub GetID
{
    my $self = shift;
    my ($id) = @_;

    $self->{DEBUG}->Log1("GetID: id($id)");
    return $self->{RCVDB}->{$id} if $self->ReceivedID($id);
    $self->{DEBUG}->Log1("GetID: haven't gotten that id yet...");
    return 0;
}


###############################################################################
#
# CleanID - Delete the list entry for this id since we don't want a leak.
#
###############################################################################
sub CleanID
{
    my $self = shift;
    my ($id) = @_;

    $self->{DEBUG}->Log1("CleanID: id($id)");
    delete($self->{RCVDB}->{$id});
}


###############################################################################
#
# WaitForID - Keep looping and calling Process(1) to poll every second
#             until the response from the server occurs.
#
###############################################################################
sub WaitForID
{
    my $self = shift;
    my ($id,$timeout) = @_;
    $timeout = "300" unless defined($timeout);

    $self->{DEBUG}->Log1("WaitForID: id($id)");
    my $endTime = time + $timeout;
    while(!$self->ReceivedID($id) && ($endTime >= time))
    {
        $self->{DEBUG}->Log1("WaitForID: haven't gotten it yet... let's wait for more packets");
        return unless (defined($self->Process(1)));
        &{$self->{CB}->{update}}() if exists($self->{CB}->{update});
    }
    if (!$self->ReceivedID($id))
    {
        $self->TimeoutID($id);
        $self->{DEBUG}->Log1("WaitForID: timed out...");
        return;
    }
    else
    {
        $self->{DEBUG}->Log1("WaitForID: we got it!");
        my $packet = $self->GetID($id);
        $self->CleanID($id);
        return $packet;
    }
}


###############################################################################
#
# GotID - Callback to store the Net::XMPP::xxxxx object in the LIST at
#         the ID index.  This is a private helper function.
#
###############################################################################
sub GotID
{
    my $self = shift;
    my ($id,$object) = @_;

    $self->{DEBUG}->Log1("GotID: id($id) xml(",$object->GetXML(),")");
    $self->{RCVDB}->{$id} = $object;
}


###############################################################################
#
# CheckID - Checks the ID registry if this tag and ID have been registered.
#           0 = no, 1 = yes
#
###############################################################################
sub CheckID
{
    my $self = shift;
    my ($tag,$id) = @_;
    $id = "" unless defined($id);

    $self->{DEBUG}->Log1("CheckID: tag($tag) id($id)");
    return 0 if ($id eq "");
    $self->{DEBUG}->Log1("CheckID: we have that here somewhere...");
    return exists($self->{IDRegistry}->{$tag}->{$id});
}


###############################################################################
#
# TimeoutID - Timeout the tag and ID in the registry so that the CallBack
#             can know what to put in the ID list and what to pass on.
#
###############################################################################
sub TimeoutID
{
    my $self = shift;
    my ($id) = @_;

    $self->{DEBUG}->Log1("TimeoutID: id($id)");
    $self->{RCVDB}->{$id} = 0;
}


###############################################################################
#
# TimedOutID - Timeout the tag and ID in the registry so that the CallBack
#             can know what to put in the ID list and what to pass on.
#
###############################################################################
sub TimedOutID
{
    my $self = shift;
    my ($id) = @_;

    return (exists($self->{RCVDB}->{$id}) && ($self->{RCVDB}->{$id} == 0));
}


###############################################################################
#
# RegisterID - Register the tag and ID in the registry so that the CallBack
#              can know what to put in the ID list and what to pass on.
#
###############################################################################
sub RegisterID
{
    my $self = shift;
    my ($tag,$id) = @_;

    $self->{DEBUG}->Log1("RegisterID: tag($tag) id($id)");
    $self->{IDRegistry}->{$tag}->{$id} = 1;
}


###############################################################################
#
# DeregisterID - Delete the tag and ID in the registry so that the CallBack
#                can knows that it has been received.
#
###############################################################################
sub DeregisterID
{
    my $self = shift;
    my ($tag,$id) = @_;

    $self->{DEBUG}->Log1("DeregisterID: tag($tag) id($id)");
    delete($self->{IDRegistry}->{$tag}->{$id});
}


###############################################################################
#
# AddNamespace - Add a custom namespace into the mix.
#
###############################################################################
sub AddNamespace
{
    my $self = shift;
    &Net::XMPP::Namespaces::add_ns(@_);
}


###############################################################################
#
# MessageSend - Takes the same hash that Net::XMPP::Message->SetMessage
#               takes and sends the message to the server.
#
###############################################################################
sub MessageSend
{
    my $self = shift;

    my $mess = $self->_message();
    $mess->SetMessage(@_);
    $self->Send($mess);
}


##############################################################################
#
# PresenceDB - initialize the module to use the presence database
#
##############################################################################
sub PresenceDB
{
    my $self = shift;

    $self->SetXPathCallBacks('/presence'=>sub{ shift; $self->PresenceDBParse(@_) });
}


###############################################################################
#
# PresenceDBParse - adds the presence information to the Presence DB so
#                   you can keep track of the current state of the JID and
#                   all of it's resources.
#
###############################################################################
sub PresenceDBParse
{
    my $self = shift;
    my ($presence) = @_;

    $self->{DEBUG}->Log4("PresenceDBParse: pres(",$presence->GetXML(),")");

    my $type = $presence->GetType();
    $type = "" unless defined($type);
    return $presence unless (($type eq "") ||
                 ($type eq "available") ||
                 ($type eq "unavailable"));

    my $fromJID = $presence->GetFrom("jid");
    my $fromID = $fromJID->GetJID();
    $fromID = "" unless defined($fromID);
    my $resource = $fromJID->GetResource();
    $resource = " " unless ($resource ne "");
    my $priority = $presence->GetPriority();
    $priority = 0 unless defined($priority);

    $self->{DEBUG}->Log1("PresenceDBParse: fromJID(",$fromJID->GetJID("full"),") resource($resource) priority($priority) type($type)");
    $self->{DEBUG}->Log2("PresenceDBParse: xml(",$presence->GetXML(),")");

    if (exists($self->{PRESENCEDB}->{$fromID}))
    {
        my $oldPriority = $self->{PRESENCEDB}->{$fromID}->{resources}->{$resource};
        $oldPriority = "" unless defined($oldPriority);

        my $loc = 0;
        foreach my $index (0..$#{$self->{PRESENCEDB}->{$fromID}->{priorities}->{$oldPriority}})
        {
            $loc = $index
               if ($self->{PRESENCEDB}->{$fromID}->{priorities}->{$oldPriority}->[$index]->{resource} eq $resource);
        }
        splice(@{$self->{PRESENCEDB}->{$fromID}->{priorities}->{$oldPriority}},$loc,1);
        delete($self->{PRESENCEDB}->{$fromID}->{resources}->{$resource});
        delete($self->{PRESENCEDB}->{$fromID}->{priorities}->{$oldPriority})
            if (exists($self->{PRESENCEDB}->{$fromID}->{priorities}->{$oldPriority}) &&
        ($#{$self->{PRESENCEDB}->{$fromID}->{priorities}->{$oldPriority}} == -1));
        delete($self->{PRESENCEDB}->{$fromID})
            if (scalar(keys(%{$self->{PRESENCEDB}->{$fromID}})) == 0);

        $self->{DEBUG}->Log1("PresenceDBParse: remove ",$fromJID->GetJID("full")," from the DB");
    }

    if (($type eq "") || ($type eq "available"))
    {
        my $loc = -1;
        foreach my $index (0..$#{$self->{PRESENCEDB}->{$fromID}->{priorities}->{$priority}}) {
            $loc = $index
                if ($self->{PRESENCEDB}->{$fromID}->{priorities}->{$priority}->[$index]->{resource} eq $resource);
        }
        $loc = $#{$self->{PRESENCEDB}->{$fromID}->{priorities}->{$priority}}+1
            if ($loc == -1);
        $self->{PRESENCEDB}->{$fromID}->{resources}->{$resource} = $priority;
        $self->{PRESENCEDB}->{$fromID}->{priorities}->{$priority}->[$loc]->{presence} =
            $presence;
        $self->{PRESENCEDB}->{$fromID}->{priorities}->{$priority}->[$loc]->{resource} =
            $resource;

        $self->{DEBUG}->Log1("PresenceDBParse: add ",$fromJID->GetJID("full")," to the DB");
    }

    my $currentPresence = $self->PresenceDBQuery($fromJID);
    return (defined($currentPresence) ? $currentPresence : $presence);
}


###############################################################################
#
# PresenceDBDelete - delete the JID from the DB completely.
#
###############################################################################
sub PresenceDBDelete
{
    my $self = shift;
    my ($jid) = @_;

    my $indexJID = $jid;
    $indexJID = $jid->GetJID() if $jid->isa("Net::XMPP::JID");

    return if !exists($self->{PRESENCEDB}->{$indexJID});
    delete($self->{PRESENCEDB}->{$indexJID});
    $self->{DEBUG}->Log1("PresenceDBDelete: delete ",$indexJID," from the DB");
}


###############################################################################
#
# PresenceDBClear - delete all of the JIDs from the DB completely.
#
###############################################################################
sub PresenceDBClear
{
    my $self = shift;

    $self->{DEBUG}->Log1("PresenceDBClear: clearing the database");
    foreach my $indexJID (keys(%{$self->{PRESENCEDB}}))
    {
        $self->{DEBUG}->Log3("PresenceDBClear: deleting ",$indexJID," from the DB");
        delete($self->{PRESENCEDB}->{$indexJID});
    }
    $self->{DEBUG}->Log3("PresenceDBClear: database is empty");
}


###############################################################################
#
# PresenceDBQuery - retrieve the last Net::XMPP::Presence received with
#                  the highest priority.
#
###############################################################################
sub PresenceDBQuery
{
    my $self = shift;
    my ($jid) = @_;

    my $indexJID = $jid;
    $indexJID = $jid->GetJID() if $jid->isa("Net::XMPP::JID");

    return if !exists($self->{PRESENCEDB}->{$indexJID});
    return if (scalar(keys(%{$self->{PRESENCEDB}->{$indexJID}->{priorities}})) == 0);

    my $highPriority =
        (sort {$b cmp $a} keys(%{$self->{PRESENCEDB}->{$indexJID}->{priorities}}))[0];

    return $self->{PRESENCEDB}->{$indexJID}->{priorities}->{$highPriority}->[0]->{presence};
}


###############################################################################
#
# PresenceDBResources - returns a list of the resources from highest
#                       priority to lowest.
#
###############################################################################
sub PresenceDBResources
{
    my $self = shift;
    my ($jid) = @_;

    my $indexJID = $jid;
    $indexJID = $jid->GetJID() if $jid->isa("Net::XMPP::JID");

    my @resources;

    return if !exists($self->{PRESENCEDB}->{$indexJID});

    foreach my $priority (sort {$b cmp $a} keys(%{$self->{PRESENCEDB}->{$indexJID}->{priorities}}))
    {
        foreach my $index (0..$#{$self->{PRESENCEDB}->{$indexJID}->{priorities}->{$priority}})
        {
            next if ($self->{PRESENCEDB}->{$indexJID}->{priorities}->{$priority}->[$index]->{resource} eq " ");
            push(@resources,$self->{PRESENCEDB}->{$indexJID}->{priorities}->{$priority}->[$index]->{resource});
        }
    }
    return @resources;
}


###############################################################################
#
# PresenceSend - Sends a presence tag to announce your availability
#
###############################################################################
sub PresenceSend
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    $args{ignoreactivity} = 0 unless exists($args{ignoreactivity});
    my $ignoreActivity = delete($args{ignoreactivity});

    my $presence = $self->_presence();

    $presence->SetPresence(%args);
    $self->Send($presence,$ignoreActivity);
    return $presence;
}


###############################################################################
#
# PresenceProbe - Sends a presence probe to the server
#
###############################################################################
sub PresenceProbe
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }
    delete($args{type});

    my $presence = $self->_presence();
    $presence->SetPresence(type=>"probe",
                           %args);
    $self->Send($presence);
}


###############################################################################
#
# Subscription - Sends a presence tag to perform the subscription on the
#                specified JID.
#
###############################################################################
sub Subscription
{
    my $self = shift;

    my $presence = $self->_presence();
    $presence->SetPresence(@_);
    $self->Send($presence);
}


###############################################################################
#
# AuthSend - This is a self contained function to send a login iq tag with
#            an id.  Then wait for a reply what the same id to come back
#            and tell the caller what the result was.
#
###############################################################################
sub AuthSend
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    carp("AuthSend requires a username arguement")
        unless exists($args{username});
    carp("AuthSend requires a password arguement")
        unless exists($args{password});

    if($self->{STREAM}->GetStreamFeature($self->GetStreamID(),"xmpp-sasl"))
    {
        return $self->AuthSASL(%args);
    }

    return $self->AuthIQAuth(%args);
}


###############################################################################
#
# AuthIQAuth - Try and auth using jabber:iq:auth, the old Jabber way of
#              authenticating.
#
###############################################################################
sub AuthIQAuth
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    $self->{DEBUG}->Log1("AuthIQAuth: old school auth");

    carp("AuthIQAuth requires a resource arguement")
        unless exists($args{resource});

    my $authType = "digest";
    my $token;
    my $sequence;

    #--------------------------------------------------------------------------
    # First let's ask the sever what all is available in terms of auth types.
    # If we get an error, then all we can do is digest or plain.
    #--------------------------------------------------------------------------
    my $iqAuth = $self->_iq();
    $iqAuth->SetIQ(type=>"get");
    my $iqAuthQuery = $iqAuth->NewChild("jabber:iq:auth");
    $iqAuthQuery->SetUsername($args{username});
    $iqAuth = $self->SendAndReceiveWithID($iqAuth);

    return unless defined($iqAuth);
    return ( $iqAuth->GetErrorCode() , $iqAuth->GetError() )
        if ($iqAuth->GetType() eq "error");

    if ($iqAuth->GetType() eq "error")
    {
        $authType = "digest";
    }
    else
    {
        $iqAuthQuery = $iqAuth->GetChild();
        $authType = "plain" if $iqAuthQuery->DefinedPassword();
        $authType = "digest" if $iqAuthQuery->DefinedDigest();
        $authType = "zerok" if ($iqAuthQuery->DefinedSequence() &&
                    $iqAuthQuery->DefinedToken());
        $token = $iqAuthQuery->GetToken() if ($authType eq "zerok");
        $sequence = $iqAuthQuery->GetSequence() if ($authType eq "zerok");
    }

    $self->{DEBUG}->Log1("AuthIQAuth: authType($authType)");

    delete($args{digest});
    delete($args{type});

    #--------------------------------------------------------------------------
    # 0k authenticaion (http://core.jabber.org/0k.html)
    #
    # Tell the server that we want to connect this way, the server sends back
    # a token and a sequence number.  We take that token + the password and
    # SHA1 it.  Then we SHA1 it sequence number more times and send that hash.
    # The server SHA1s that hash one more time and compares it to the hash it
    # stored last time.  IF they match, we are in and it stores the hash we sent
    # for the next time and decreases the sequence number, else, no go.
    #--------------------------------------------------------------------------
    if ($authType eq "zerok")
    {
        my $hashA = Digest::SHA::sha1_hex(delete($args{password}));
        $args{hash} = Digest::SHA::sha1_hex($hashA.$token);

        for (1..$sequence)
        {
            $args{hash} = Digest::SHA::sha1_hex($args{hash});
        }
    }

    #--------------------------------------------------------------------------
    # If we have access to the SHA-1 digest algorithm then let's use it.
    # Remove the password from the hash, create the digest, and put the
    # digest in the hash instead.
    #
    # Note: Concat the Session ID and the password and then digest that
    # string to get the server to accept the digest.
    #--------------------------------------------------------------------------
    if ($authType eq "digest")
    {
        my $password = delete($args{password});
        $args{digest} = Digest::SHA::sha1_hex($self->GetStreamID().$password);
    }

    #--------------------------------------------------------------------------
    # Create a Net::XMPP::IQ object to send to the server
    #--------------------------------------------------------------------------
    my $iqLogin = $self->_iq();
    $iqLogin->SetIQ(type=>"set");
    my $iqLoginQuery = $iqLogin->NewChild("jabber:iq:auth");
    $iqLoginQuery->SetAuth(%args);

    #--------------------------------------------------------------------------
    # Send the IQ with the next available ID and wait for a reply with that
    # id to be received.  Then grab the IQ reply.
    #--------------------------------------------------------------------------
    $iqLogin = $self->SendAndReceiveWithID($iqLogin);

    #--------------------------------------------------------------------------
    # From the reply IQ determine if we were successful or not.  If yes then
    # return "".  If no then return error string from the reply.
    #--------------------------------------------------------------------------
    return unless defined($iqLogin);
    return ( $iqLogin->GetErrorCode() , $iqLogin->GetError() )
        if ($iqLogin->GetType() eq "error");

    $self->{DEBUG}->Log1("AuthIQAuth: we authed!");

    return ("ok","");
}


###############################################################################
#
# AuthSASL - Try and auth using SASL, the XMPP preferred way of authenticating.
#
###############################################################################
sub AuthSASL
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    $self->{DEBUG}->Log1("AuthSASL: shiney new auth");

    carp("AuthSASL requires a username arguement")
        unless exists($args{username});
    carp("AuthSASL requires a password arguement")
        unless exists($args{password});

    $args{resource} = "" unless exists($args{resource});

    #-------------------------------------------------------------------------
    # Create the SASLClient on our end
    #-------------------------------------------------------------------------
    my $sid = $self->{SESSION}->{id};
    my $status =
        $self->{STREAM}->SASLClient($sid,
                                    $args{username},
                                    $args{password}
                                   );

    $args{timeout} = "120" unless exists($args{timeout});

    #-------------------------------------------------------------------------
    # While we haven't timed out, keep waiting for the SASLClient to finish
    #-------------------------------------------------------------------------
    my $endTime = time + $args{timeout};
    while(!$self->{STREAM}->SASLClientDone($sid) && ($endTime >= time))
    {
        $self->{DEBUG}->Log1("AuthSASL: haven't authed yet... let's wait.");
        return unless (defined($self->Process(1)));
        &{$self->{CB}->{update}}() if exists($self->{CB}->{update});
    }

    #-------------------------------------------------------------------------
    # The loop finished... but was it done?
    #-------------------------------------------------------------------------
    if (!$self->{STREAM}->SASLClientDone($sid))
    {
        $self->{DEBUG}->Log1("AuthSASL: timed out...");
        return( "system","SASL timed out authenticating");
    }

    #-------------------------------------------------------------------------
    # Ok, it was done... but did we auth?
    #-------------------------------------------------------------------------
    if (!$self->{STREAM}->SASLClientAuthed($sid))
    {
        $self->{DEBUG}->Log1("AuthSASL: Authentication failed.");
        return ( "error", $self->{STREAM}->SASLClientError($sid));
    }

    #-------------------------------------------------------------------------
    # Phew... Restart the <stream:stream> per XMPP
    #-------------------------------------------------------------------------
    $self->{DEBUG}->Log1("AuthSASL: We authed!");
    $self->{SESSION} = $self->{STREAM}->OpenStream($sid);
    $sid = $self->{SESSION}->{id};

    $self->{DEBUG}->Log1("AuthSASL: We got a new session. sid($sid)");

    #-------------------------------------------------------------------------
    # Look in the new set of <stream:feature/>s and see if xmpp-bind was
    # offered.
    #-------------------------------------------------------------------------
    my $bind = $self->{STREAM}->GetStreamFeature($sid,"xmpp-bind");
    if ($bind)
    {
        $self->{DEBUG}->Log1("AuthSASL: Binding to resource");
        $self->BindResource($args{resource});
    }

    #-------------------------------------------------------------------------
    # Look in the new set of <stream:feature/>s and see if xmpp-session was
    # offered.
    #-------------------------------------------------------------------------
    my $session = $self->{STREAM}->GetStreamFeature($sid,"xmpp-session");
    if ($session)
    {
        $self->{DEBUG}->Log1("AuthSASL: Starting session");
        $self->StartSession();
    }

    return ("ok","");
}


##############################################################################
#
# BindResource - bind to a resource
#
##############################################################################
sub BindResource
{
    my $self = shift;
    my $resource = shift;

    $self->{DEBUG}->Log2("BindResource: Binding to resource");
    my $iq = $self->_iq();

    $iq->SetIQ(type=>"set");
    my $bind = $iq->NewChild(&ConstXMLNS("xmpp-bind"));

    if (defined($resource) && ($resource ne ""))
    {
        $self->{DEBUG}->Log2("BindResource: resource($resource)");
        $bind->SetBind(resource=>$resource);
    }

    my $result = $self->SendAndReceiveWithID($iq);
}


##############################################################################
#
# StartSession - Initialize a session
#
##############################################################################
sub StartSession
{
    my $self = shift;

    my $iq = $self->_iq();

    $iq->SetIQ(type=>"set");
    my $session = $iq->NewChild(&ConstXMLNS("xmpp-session"));

    my $result = $self->SendAndReceiveWithID($iq);
}


##############################################################################
#
# PrivacyLists - Initialize a Net::XMPP::PrivacyLists object and return it.
#
##############################################################################
sub PrivacyLists
{
    my $self = shift;

    return new Net::XMPP::PrivacyLists(connection=>$self);
}


##############################################################################
#
# PrivacyListsGet - Sends an empty IQ to the server to request that the user's
#                   Privacy Lists be sent to them.  Returns the iq packet
#                   of the result.
#
##############################################################################
sub PrivacyListsGet
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    my $iq = $self->_iq();
    $iq->SetIQ(type=>"get");
    my $query = $iq->NewChild("jabber:iq:privacy");

    if (exists($args{list}))
    {
        $query->AddList(name=>$args{list});
    }

    $iq = $self->SendAndReceiveWithID($iq);
    return unless defined($iq);

    return $iq;
}


##############################################################################
#
# PrivacyListsRequest - Sends an empty IQ to the server to request that the
#                       user's privacy lists be sent to them, and return to
#                       let the user's program handle parsing the return packet.
#
##############################################################################
sub PrivacyListsRequest
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    my $iq = $self->_iq();
    $iq->SetIQ(type=>"get");
    my $query = $iq->NewChild("jabber:iq:privacy");

    if (exists($args{list}))
    {
        $query->AddList(name=>$args{list});
    }

    $self->Send($iq);
}


##############################################################################
#
# PrivacyListsSet - Sends an empty IQ to the server to request that the
#                       user's privacy lists be sent to them, and return to
#                       let the user's program handle parsing the return packet.
#
##############################################################################
sub PrivacyListsSet
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    my $iq = $self->_iq();
    $iq->SetIQ(type=>"set");
    my $query = $iq->NewChild("jabber:iq:privacy");

    #XXX error check that there is a list
    my $list = $query->AddList(name=>$args{list});

    foreach my $item (@{$args{items}})
    {
        $list->AddItem(%{$item});
    }

    $iq = $self->SendAndReceiveWithID($iq);
    return unless defined($iq);

    return if $iq->DefinedError();

    return 1;
}


###############################################################################
#
# RegisterRequest - This is a self contained function to send an iq tag
#                   an id that requests the target address to send back
#                   the required fields.  It waits for a reply what the
#                   same id to come back and tell the caller what the
#                   fields are.
#
###############################################################################
sub RegisterRequest
{
    my $self = shift;
    my %args;
    $args{mode} = "block";
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    my $timeout = exists($args{timeout}) ? delete($args{timeout}) : undef;

    #--------------------------------------------------------------------------
    # Create a Net::XMPP::IQ object to send to the server
    #--------------------------------------------------------------------------
    my $iq = $self->_iq();
    $iq->SetIQ(to=>delete($args{to})) if exists($args{to});
    $iq->SetIQ(type=>"get");
    my $query = $iq->NewChild("jabber:iq:register");

    #--------------------------------------------------------------------------
    # Send the IQ with the next available ID and wait for a reply with that
    # id to be received.  Then grab the IQ reply.
    #--------------------------------------------------------------------------
    if ($args{mode} eq "passthru")
    {
        my $id = $self->UniqueID();
        $iq->SetIQ(id=>$id);
        $self->Send($iq);
        return $id;
    }

    return $self->SendWithID($iq) if ($args{mode} eq "nonblock");

    $iq = $self->SendAndReceiveWithID($iq,$timeout);

    #--------------------------------------------------------------------------
    # Check if there was an error.
    #--------------------------------------------------------------------------
    return unless defined($iq);
    if ($iq->GetType() eq "error")
    {
        $self->SetErrorCode($iq->GetErrorCode().": ".$iq->GetError());
        return;
    }

    my %register;
    #--------------------------------------------------------------------------
    # From the reply IQ determine what fields are required and send a hash
    # back with the fields and any values that are already defined (like key)
    #--------------------------------------------------------------------------
    $query = $iq->GetChild();
    $register{fields} = { $query->GetRegister() };

    return %register;
}


###############################################################################
#
# RegisterSend - This is a self contained function to send a registration
#                iq tag with an id.  Then wait for a reply what the same
#                id to come back and tell the caller what the result was.
#
###############################################################################
sub RegisterSend
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    #--------------------------------------------------------------------------
    # Create a Net::XMPP::IQ object to send to the server
    #--------------------------------------------------------------------------
    my $iq = $self->_iq();
    $iq->SetIQ(to=>delete($args{to})) if exists($args{to});
    $iq->SetIQ(type=>"set");
    my $iqRegister = $iq->NewChild("jabber:iq:register");
    $iqRegister->SetRegister(%args);

    #--------------------------------------------------------------------------
    # Send the IQ with the next available ID and wait for a reply with that
    # id to be received.  Then grab the IQ reply.
    #--------------------------------------------------------------------------
    $iq = $self->SendAndReceiveWithID($iq);

    #--------------------------------------------------------------------------
    # From the reply IQ determine if we were successful or not.  If yes then
    # return "".  If no then return error string from the reply.
    #--------------------------------------------------------------------------
    return unless defined($iq);
    return ( $iq->GetErrorCode() , $iq->GetError() )
        if ($iq->GetType() eq "error");
    return ("ok","");
}


##############################################################################
#
# RosterAdd - Takes the Jabber ID of the user to add to their Roster and
#             sends the IQ packet to the server.
#
##############################################################################
sub RosterAdd
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }

    my $iq = $self->_iq();
    $iq->SetIQ(type=>"set");
    my $roster = $iq->NewChild("jabber:iq:roster");
    my $item = $roster->AddItem();
    $item->SetItem(%args);

    $self->{DEBUG}->Log1("RosterAdd: xml(",$iq->GetXML(),")");
    $self->Send($iq);
}


##############################################################################
#
# RosterAdd - Takes the Jabber ID of the user to remove from their Roster
#             and sends the IQ packet to the server.
#
##############################################################################
sub RosterRemove
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }
    delete($args{subscription});

    my $iq = $self->_iq();
    $iq->SetIQ(type=>"set");
    my $roster = $iq->NewChild("jabber:iq:roster");
    my $item = $roster->AddItem();
    $item->SetItem(%args,
                   subscription=>"remove");
    $self->Send($iq);
}


##############################################################################
#
# RosterParse - Returns a hash of roster items.
#
##############################################################################
sub RosterParse
{
    my $self = shift;
    my($iq) = @_;

    my %roster;
    my $query = $iq->GetChild("jabber:iq:roster");

    if (defined($query)) #$query->GetXMLNS() eq "jabber:iq:roster")
    {
        my @items = $query->GetItems();

        foreach my $item (@items)
        {
            my $jid = $item->GetJID();
            $roster{$jid}->{name} = $item->GetName();
            $roster{$jid}->{subscription} = $item->GetSubscription();
            $roster{$jid}->{ask} = $item->GetAsk();
            $roster{$jid}->{groups} = [ $item->GetGroup() ];
        }
    }

    return %roster;
}


##############################################################################
#
# RosterGet - Sends an empty IQ to the server to request that the user's
#             Roster be sent to them.  Returns a hash of roster items.
#
##############################################################################
sub RosterGet
{
    my $self = shift;

    my $iq = $self->_iq();
    $iq->SetIQ(type=>"get");
    my $query = $iq->NewChild("jabber:iq:roster");

    $iq = $self->SendAndReceiveWithID($iq);

    return unless defined($iq);

    return $self->RosterParse($iq);
}


##############################################################################
#
# RosterRequest - Sends an empty IQ to the server to request that the user's
#                 Roster be sent to them, and return to let the user's program
#                 handle parsing the return packet.
#
##############################################################################
sub RosterRequest
{
    my $self = shift;

    my $iq = $self->_iq();
    $iq->SetIQ(type=>"get");
    my $query = $iq->NewChild("jabber:iq:roster");

    $self->Send($iq);
}


##############################################################################
#
# Roster - Initialize a Net::XMPP::Roster object and return it.
#
##############################################################################
sub Roster
{
    my $self = shift;

    return new Net::XMPP::Roster(connection=>$self);
}


##############################################################################
#
# RosterDB - initialize the module to use the roster database
#
##############################################################################
sub RosterDB
{
    my $self = shift;

    $self->SetXPathCallBacks('/iq[@type="result" or @type="set"]/query[@xmlns="jabber:iq:roster"]'=>sub{ shift; $self->RosterDBParse(@_) });
}


##############################################################################
#
# RosterDBAdd - adds the entry to the Roster DB.
#
##############################################################################
sub RosterDBAdd
{
    my $self = shift;
    my ($jid,%item) = @_;

    $self->{ROSTERDB}->{JIDS}->{$jid} = \%item;

    foreach my $group (@{$item{groups}})
    {
        $self->{ROSTERDB}->{GROUPS}->{$group}->{$jid} = 1;
    }
}


###############################################################################
#
# RosterDBClear - delete all of the JIDs from the DB completely.
#
###############################################################################
sub RosterDBClear
{
    my $self = shift;

    $self->{DEBUG}->Log1("RosterDBClear: clearing the database");
    foreach my $jid ($self->RosterDBJIDs())
    {
        $self->{DEBUG}->Log3("RosterDBClear: deleting ",$jid->GetJID()," from the DB");
        $self->RosterDBRemove($jid);
    }
    $self->{DEBUG}->Log3("RosterDBClear: database is empty");
}


##############################################################################
#
# RosterDBExists - allows you to query if the JID exists in the Roster DB.
#
##############################################################################
sub RosterDBExists
{
    my $self = shift;
    my ($jid) = @_;

    if ($jid->isa("Net::XMPP::JID"))
    {
        $jid = $jid->GetJID();
    }

    return unless exists($self->{ROSTERDB});
    return unless exists($self->{ROSTERDB}->{JIDS});
    return unless exists($self->{ROSTERDB}->{JIDS}->{$jid});
    return 1;
}


##############################################################################
#
# RosterDBGroupExists - allows you to query if the group exists in the Roster
#                       DB.
#
##############################################################################
sub RosterDBGroupExists
{
    my $self = shift;
    my ($group) = @_;

    return unless exists($self->{ROSTERDB});
    return unless exists($self->{ROSTERDB}->{GROUPS});
    return unless exists($self->{ROSTERDB}->{GROUPS}->{$group});
    return 1;
}


##############################################################################
#
# RosterDBGroupJIDs - returns a list of the current groups in your roster.
#
##############################################################################
sub RosterDBGroupJIDs
{
    my $self = shift;
    my $group = shift;

    return unless $self->RosterDBGroupExists($group);
    my @jids;
    foreach my $jid (keys(%{$self->{ROSTERDB}->{GROUPS}->{$group}}))
    {
        push(@jids,$self->_jid($jid));
    }
    return @jids;
}


##############################################################################
#
# RosterDBGroups - returns a list of the current groups in your roster.
#
##############################################################################
sub RosterDBGroups
{
    my $self = shift;

    return () unless exists($self->{ROSTERDB}->{GROUPS});
    return () if (scalar(keys(%{$self->{ROSTERDB}->{GROUPS}})) == 0);
    return keys(%{$self->{ROSTERDB}->{GROUPS}});
}


##############################################################################
#
# RosterDBJIDs - returns a list of all of the JIDs in your roster.
#
##############################################################################
sub RosterDBJIDs
{
    my $self = shift;
    my $group = shift;

    my @jids;

    return () unless exists($self->{ROSTERDB});
    return () unless exists($self->{ROSTERDB}->{JIDS});
    foreach my $jid (keys(%{$self->{ROSTERDB}->{JIDS}}))
    {
        push(@jids,$self->_jid($jid));
    }
    return @jids;
}


##############################################################################
#
# RosterDBNonGroupJIDs - returns a list of the JIDs not in a group.
#
##############################################################################
sub RosterDBNonGroupJIDs
{
    my $self = shift;
    my $group = shift;

    my @jids;

    return () unless exists($self->{ROSTERDB});
    return () unless exists($self->{ROSTERDB}->{JIDS});
    foreach my $jid (keys(%{$self->{ROSTERDB}->{JIDS}}))
    {
        next if (exists($self->{ROSTERDB}->{JIDS}->{$jid}->{groups}) &&
                 ($#{$self->{ROSTERDB}->{JIDS}->{$jid}->{groups}} > -1));

        push(@jids,$self->_jid($jid));
    }
    return @jids;
}


##############################################################################
#
# RosterDBParse - takes an iq packet that containsa roster, parses it, and puts
#                 the roster into the Roster DB.
#
##############################################################################
sub RosterDBParse
{
    my $self = shift;
    my ($iq) = @_;

    #print "RosterDBParse: iq(",$iq->GetXML(),")\n";

    my $type = $iq->GetType();
    return unless (($type eq "set") || ($type eq "result"));

    my %newroster = $self->RosterParse($iq);

    $self->RosterDBProcessParsed(%newroster);
}


##############################################################################
#
# RosterDBProcessParsed - takes a parsed roster and puts it into the Roster DB.
#
##############################################################################
sub RosterDBProcessParsed
{
    my $self = shift;
    my (%roster) = @_;

    foreach my $jid (keys(%roster))
    {
        $self->RosterDBRemove($jid);

        if ($roster{$jid}->{subscription} ne "remove")
        {
            $self->RosterDBAdd($jid, %{$roster{$jid}} );
        }
    }
}


##############################################################################
#
# RosterDBQuery - allows you to get one of the pieces of info from the
#                 Roster DB.
#
##############################################################################
sub RosterDBQuery
{
    my $self = shift;
    my $jid = shift;
    my $key = shift;

    if ($jid->isa("Net::XMPP::JID"))
    {
        $jid = $jid->GetJID();
    }

    return unless $self->RosterDBExists($jid);
    if (defined($key))
    {
        return unless exists($self->{ROSTERDB}->{JIDS}->{$jid}->{$key});
        return $self->{ROSTERDB}->{JIDS}->{$jid}->{$key};
    }
    return %{$self->{ROSTERDB}->{JIDS}->{$jid}};
}


##############################################################################
#
# RosterDBRemove - removes the JID from the Roster DB.
#
##############################################################################
sub RosterDBRemove
{
    my $self = shift;
    my ($jid) = @_;

    if ($self->RosterDBExists($jid))
    {
        if (defined($self->RosterDBQuery($jid,"groups")))
        {
            foreach my $group (@{$self->RosterDBQuery($jid,"groups")})
            {
                delete($self->{ROSTERDB}->{GROUPS}->{$group}->{$jid});
                delete($self->{ROSTERDB}->{GROUPS}->{$group})
                    if (scalar(keys(%{$self->{ROSTERDB}->{GROUPS}->{$group}})) == 0);
                delete($self->{ROSTERDB}->{GROUPS})
                    if (scalar(keys(%{$self->{ROSTERDB}->{GROUPS}})) == 0);
            }
        }

        delete($self->{ROSTERDB}->{JIDS}->{$jid});
    }
}




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

##############################################################################
#
# TLSInit - Initialize the connection for TLS.
#
##############################################################################
sub TLSInit
{
    my $self = shift;

    $TLS_CALLBACK = sub{ $self->ProcessTLSStanza( @_ ) };
    $self->SetDirectXPathCallBacks('/[@xmlns="'.&ConstXMLNS("xmpp-tls").'"]'=>$TLS_CALLBACK);
}


##############################################################################
#
# ProcessTLSStanza - process a TLS based packet.
#
##############################################################################
sub ProcessTLSStanza
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

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

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

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


##############################################################################
#
# TLSStart - client function to have the socket start TLS.
#
##############################################################################
sub TLSStart
{
    my $self = shift;
    my $timeout = shift;
    $timeout = 120 unless defined($timeout);
    $timeout = 120 if ($timeout eq "");

    $self->TLSSendStartTLS();

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

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

    $self->RestartStream($timeout);
}


##############################################################################
#
# TLSClientProceed - handle a <proceed/> packet.
#
##############################################################################
sub TLSClientProceed
{
    my $self = shift;
    my $node = shift;

    my ($status,$message) = $self->{STREAM}->StartTLS($self->GetStreamID());

    if ($status)
    {
        $self->{TLS}->{done} = 1;
        $self->{TLS}->{secure} = 1;
    }
    else
    {
        $self->{TLS}->{done} = 1;
        $self->{TLS}->{error} = $message;
    }

    $self->RemoveDirectXPathCallBacks('/[@xmlns="'.&ConstXMLNS("xmpp-tls").'"]'=>$TLS_CALLBACK);
}


##############################################################################
#
# TLSClientSecure - return 1 if the socket is secure, 0 otherwise.
#
##############################################################################
sub TLSClientSecure
{
    my $self = shift;

    return $self->{TLS}->{secure};
}


##############################################################################
#
# TLSClientDone - return 1 if the TLS process is done
#
##############################################################################
sub TLSClientDone
{
    my $self = shift;

    return $self->{TLS}->{done};
}


##############################################################################
#
# TLSClientError - return the TLS error if any
#
##############################################################################
sub TLSClientError
{
    my $self = shift;

    return $self->{TLS}->{error};
}


##############################################################################
#
# TLSClientFailure - handle a <failure/>
#
##############################################################################
sub TLSClientFailure
{
    my $self = shift;
    my $node = shift;

    my $type = &XML::Stream::XPath($node,"*/name()");

    $self->{TLS}->{error} = $type;
    $self->{TLS}->{done} = 1;
}


##############################################################################
#
# TLSSendFailure - Send a <failure/> in the TLS namespace
#
##############################################################################
sub TLSSendFailure
{
    my $self = shift;
    my $type = shift;

    $self->Send("<failure xmlns='".&ConstXMLNS('xmpp-tls')."'><${type}/></failure>");
}


##############################################################################
#
# TLSSendStartTLS - send a <starttls/> in the TLS namespace.
#
##############################################################################
sub TLSSendStartTLS
{
    my $self = shift;

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




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

##############################################################################
#
# SASLInit - Initialize the connection for SASL.
#
##############################################################################
sub SASLInit
{
    my $self = shift;

    $SASL_CALLBACK = sub{ $self->ProcessSASLStanza( @_ ) };
    $self->SetDirectXPathCallBacks('/[@xmlns="'.&ConstXMLNS("xmpp-sasl").'"]'=> $SASL_CALLBACK);
}


##############################################################################
#
# ProcessSASLStanza - process a SASL based packet.
#
##############################################################################
sub ProcessSASLStanza
{
    my $self = shift;
    my $sid = shift;
    my $node = shift;

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

    if ($tag eq "challenge")
    {
        $self->SASLAnswerChallenge($node);
    }

    if ($tag eq "failure")
    {
        $self->SASLClientFailure($node);
    }

    if ($tag eq "success")
    {
        $self->SASLClientSuccess($node);
    }
}


##############################################################################
#
# SASLAnswerChallenge - when we get a <challenge/> we need to do the grunt
#                       work to return a <response/>.
#
##############################################################################
sub SASLAnswerChallenge
{
    my $self = shift;
    my $node = shift;

    my $challenge64 = &XML::Stream::XPath($node,"text()");
    my $challenge = MIME::Base64::decode_base64($challenge64);

    my $response = $self->SASLGetClient()->client_step($challenge);

    my $response64 = MIME::Base64::encode_base64($response,"");
    $self->SASLSendResponse($response64);
}


###############################################################################
#
# SASLClient - This is a helper function to perform all of the required steps
#              for doing SASL with the server.
#
###############################################################################
sub SASLClient
{
    my $self = shift;
    my $username = shift;
    my $password = shift;

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

    return unless defined($mechanisms);

    my $sasl = new Authen::SASL(mechanism=>join(" ",@{$mechanisms}),
                                callback=>{ user => $username,
                                            pass => $password
                                          }
                               );

    $self->{SASL}->{client} = $sasl->client_new();
    $self->{SASL}->{username} = $username;
    $self->{SASL}->{password} = $password;
    $self->{SASL}->{authed} = 0;
    $self->{SASL}->{done} = 0;

    $self->SASLSendAuth();
}


##############################################################################
#
# SASLClientAuthed - return 1 if we authed via SASL, 0 otherwise
#
##############################################################################
sub SASLClientAuthed
{
    my $self = shift;

    return $self->{SASL}->{authed};
}


##############################################################################
#
# SASLClientDone - return 1 if the SASL process is finished
#
##############################################################################
sub SASLClientDone
{
    my $self = shift;

    return $self->{SASL}->{done};
}


##############################################################################
#
# SASLClientError - return the error if any
#
##############################################################################
sub SASLClientError
{
    my $self = shift;

    return $self->{SASL}->{error};
}


##############################################################################
#
# SASLClientFailure - handle a received <failure/>
#
##############################################################################
sub SASLClientFailure
{
    my $self = shift;
    my $node = shift;

    my $type = &XML::Stream::XPath($node,"*/name()");

    $self->{SASL}->{error} = $type;
    $self->{SASL}->{done} = 1;
}


##############################################################################
#
# SASLClientSuccess - handle a received <success/>
#
##############################################################################
sub SASLClientSuccess
{
    my $self = shift;
    my $node = shift;

    $self->{SASL}->{authed} = 1;
    $self->{SASL}->{done} = 1;

    $self->RemoveDirectXPathCallBacks('/[@xmlns="'.&ConstXMLNS("xmpp-sasl").'"]'=>$SASL_CALLBACK);
}


###############################################################################
#
# SASLGetClient - This is a helper function to return the SASL client object.
#
###############################################################################
sub SASLGetClient
{
    my $self = shift;

    return $self->{SASL}->{client};
}


##############################################################################
#
# SASLSendAuth - send an <auth/> in the SASL namespace
#
##############################################################################
sub SASLSendAuth
{
    my $self = shift;

    $self->Send("<auth xmlns='".&ConstXMLNS('xmpp-sasl')."' mechanism='".$self->SASLGetClient()->mechanism()."'/>");
}


##############################################################################
#
# SASLSendChallenge - Send a <challenge/> in the SASL namespace
#
##############################################################################
sub SASLSendChallenge
{
    my $self = shift;
    my $challenge = shift;

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


##############################################################################
#
# SASLSendFailure - Send a <failure/> tag in the SASL namespace
#
##############################################################################
sub SASLSendFailure
{
    my $self = shift;
    my $type = shift;

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


##############################################################################
#
# SASLSendResponse - Send a <response/> tag in the SASL namespace
#
##############################################################################
sub SASLSendResponse
{
    my $self = shift;
    my $response = shift;

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




##############################################################################
#+----------------------------------------------------------------------------
#|
#| Default CallBacks
#|
#+----------------------------------------------------------------------------
##############################################################################


##############################################################################
#
# xmppCallbackInit - initialize the default callbacks
#
##############################################################################
sub xmppCallbackInit
{
    my $self = shift;

    $self->{DEBUG}->Log1("xmppCallbackInit: start");

    $self->SetCallBacks(iq=>sub{ $self->callbackIQ(@_) },
                        presence=>sub{ $self->callbackPresence(@_) },
                        message=>sub{ $self->callbackMessage(@_) },
                        );

    $self->SetPresenceCallBacks(subscribe=>sub{ $self->callbackPresenceSubscribe(@_) },
                                unsubscribe=>sub{ $self->callbackPresenceUnsubscribe(@_) },
                                subscribed=>sub{ $self->callbackPresenceSubscribed(@_) },
                                unsubscribed=>sub{ $self->callbackPresenceUnsubscribed(@_) },
                               );

    $self->TLSInit();
    $self->SASLInit();

    $self->{DEBUG}->Log1("xmppCallbackInit: stop");
}


##############################################################################
#
# callbackMessage - default callback for <message/> packets.
#
##############################################################################
sub callbackMessage
{
    my $self = shift;
    my $sid = shift;
    my $message = shift;

    my $type = "normal";
    $type = $message->GetType() if $message->DefinedType();

   	$self->{DEBUG}->Log1("callbackMessage: type($type) sid($sid) ");

    if (exists($self->{CB}->{Mess}->{$type})
      #&& (ref($self->{CB}->{Mess}->{$type}) =~ /CODE/)
       )
    {
        &{$self->{CB}->{Mess}->{$type}}($sid,$message);
    }
    else
    {
      	$self->{DEBUG}->Log1("callbackMessage: type($type) not code (ref($self->{CB}->{Mess}->{$type})) ");
    }
}


##############################################################################
#
# callbackPresence - default callback for <presence/> packets.
#
##############################################################################
sub callbackPresence
{
    my $self = shift;
    my $sid = shift;
    my $presence = shift;

    my $type = "available";
    $type = $presence->GetType() if $presence->DefinedType();

   	$self->{DEBUG}->Log1("callbackPresence: type($type) sid($sid) ");

    if (exists($self->{CB}->{Pres}->{$type})
#       && (ref($self->{CB}->{Pres}->{$type}) =~ /CODE/)
        )
    {
        &{$self->{CB}->{Pres}->{$type}}($sid,$presence);
    }
}


##############################################################################
#
# callbackIQ - default callback for <iq/> packets.
#
##############################################################################
sub callbackIQ
{
    my $self = shift;
    my $sid = shift;
    my $iq = shift;

    $self->{DEBUG}->Log1("callbackIQ: sid($sid) iq($iq)");

    return unless $iq->DefinedChild();
    my $query = $iq->GetChild();
    return unless defined($query);

    my $type = $iq->GetType();
    my $ns = $query->GetXMLNS();

    $self->{DEBUG}->Log1("callbackIQ: type($type) ns($ns)");

    if (exists($self->{CB}->{IQns}->{$ns})
        && (ref($self->{CB}->{IQns}->{$ns}) != 'HASH' )
        )
    {
        $self->{DEBUG}->Log1("callbackIQ: goto user function( $self->{CB}->{IQns}->{$ns} )");
        &{$self->{CB}->{IQns}->{$ns}}($sid,$iq);

    }
    elsif (exists($self->{CB}->{IQns}->{$ns}->{$type})
#        && (ref($self->{CB}->{IQns}->{$ns}->{$type}) =~ /CODE/)
        )
    {
        $self->{DEBUG}->Log1("callbackIQ: goto user function( $self->{CB}->{IQns}->{$ns}->{$type} )");
        &{$self->{CB}->{IQns}->{$ns}->{$type}}($sid,$iq);
    }
}


##############################################################################
#
# callbackPresenceSubscribe - default callback for subscribe packets.
#
##############################################################################
sub callbackPresenceSubscribe
{
    my $self = shift;
    my $sid = shift;
    my $presence = shift;

    my $reply = $presence->Reply(type=>"subscribed");
    $self->Send($reply,1);
    $reply->SetType("subscribe");
    $self->Send($reply,1);
}


##############################################################################
#
# callbackPresenceUnsubscribe - default callback for unsubscribe packets.
#
##############################################################################
sub callbackPresenceUnsubscribe
{
    my $self = shift;
    my $sid = shift;
    my $presence = shift;

    my $reply = $presence->Reply(type=>"unsubscribed");
    $self->Send($reply,1);
}


##############################################################################
#
# callbackPresenceSubscribed - default callback for subscribed packets.
#
##############################################################################
sub callbackPresenceSubscribed
{
    my $self = shift;
    my $sid = shift;
    my $presence = shift;

    my $reply = $presence->Reply(type=>"subscribed");
    $self->Send($reply,1);
}


##############################################################################
#
# callbackPresenceUnsubscribed - default callback for unsubscribed packets.
#
##############################################################################
sub callbackPresenceUnsubscribed
{
    my $self = shift;
    my $sid = shift;
    my $presence = shift;

    my $reply = $presence->Reply(type=>"unsubscribed");
    $self->Send($reply,1);
}



##############################################################################
#+----------------------------------------------------------------------------
#|
#| Stream functions
#|
#+----------------------------------------------------------------------------
##############################################################################
sub GetStreamID
{
    my $self = shift;

    return $self->{SESSION}->{id};
}


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

    return $self->{STREAM}->GetStreamFeature($self->GetStreamID(),$feature);
}


sub RestartStream
{
    my $self = shift;
    my $timeout = shift;

    $self->{SESSION} =
        $self->{STREAM}->OpenStream($self->GetStreamID(),$timeout);
    return $self->GetStreamID();
}


##############################################################################
#
# ConstXMLNS - Return the namespace from the constant string.
#
##############################################################################
sub ConstXMLNS
{
    my $const = shift;

    return $XMLNS{$const};
}


1;