This file is indexed.

/usr/lib/python3/dist-packages/nbxmpp/protocol.py is in python3-nbxmpp 0.5.3-1.

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
##   protocol.py
##
##   Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
##
##   This program is free software; you can redistribute it and/or modify
##   it under the terms of the GNU General Public License as published by
##   the Free Software Foundation; either version 2, or (at your option)
##   any later version.
##
##   This program 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 General Public License for more details.

# $Id: protocol.py,v 1.52 2006/01/09 22:08:57 normanr Exp $

"""
Protocol module contains tools that are needed for processing of xmpp-related
data structures, including jabber-objects like JID or different stanzas and
sub- stanzas) handling routines
"""

from .simplexml import Node, NodeBuilder
import time
import string
import hashlib

def ascii_upper(s):
    return s.upper()

NS_ACTIVITY       = 'http://jabber.org/protocol/activity'             # XEP-0108
NS_ADDRESS        = 'http://jabber.org/protocol/address'              # XEP-0033
NS_AGENTS         = 'jabber:iq:agents'
NS_AMP            = 'http://jabber.org/protocol/amp'
NS_AMP_ERRORS     = NS_AMP + '#errors'
NS_ARCHIVE        = 'urn:xmpp:archive'                                # XEP-0136
NS_ARCHIVE_AUTO   = NS_ARCHIVE + ':auto'                              # XEP-0136
NS_ARCHIVE_MANAGE = NS_ARCHIVE + ':manage'                            # XEP-0136
NS_ARCHIVE_MANUAL = NS_ARCHIVE + ':manual'                            # XEP-0136
NS_ARCHIVE_PREF   = NS_ARCHIVE + ':pref'
NS_ATOM           = 'http://www.w3.org/2005/Atom'
NS_ATTENTION      = 'urn:xmpp:attention:0'                            # XEP-0224
NS_AUTH           = 'jabber:iq:auth'
NS_AVATAR         = 'http://www.xmpp.org/extensions/xep-0084.html#ns-metadata'
NS_BIND           = 'urn:ietf:params:xml:ns:xmpp-bind'
NS_BLOCKING       = 'urn:xmpp:blocking'                               # XEP-0191
NS_BOB            = 'urn:xmpp:bob'                                    # XEP-0231
NS_BOOKMARKS      = 'storage:bookmarks'                               # XEP-0048
NS_BROWSE         = 'jabber:iq:browse'
NS_BROWSING       = 'http://jabber.org/protocol/browsing'             # XEP-0195
NS_BYTESTREAM     = 'http://jabber.org/protocol/bytestreams'          # XEP-0065
NS_CAPS           = 'http://jabber.org/protocol/caps'                 # XEP-0115
NS_CAPTCHA        = 'urn:xmpp:captcha'                                # XEP-0158
NS_CARBONS        = 'urn:xmpp:carbons:2'                              # XEP-0280
NS_CHATSTATES     = 'http://jabber.org/protocol/chatstates'           # XEP-0085
NS_CHATTING       = 'http://jabber.org/protocol/chatting'             # XEP-0194
NS_CLIENT         = 'jabber:client'
NS_CONDITIONS     = 'urn:xmpp:muc:conditions:0'                       # XEP-0306
NS_COMMANDS       = 'http://jabber.org/protocol/commands'
NS_COMPONENT_ACCEPT = 'jabber:component:accept'
NS_COMPONENT_1    = 'http://jabberd.jabberstudio.org/ns/component/1.0'
NS_COMPRESS       = 'http://jabber.org/protocol/compress'             # XEP-0138
NS_CONFERENCE     = 'jabber:x:conference'
NS_CORRECT        = 'urn:xmpp:message-correct:0'                      # XEP-0308
NS_DATA           = 'jabber:x:data'                                   # XEP-0004
NS_DATA_MEDIA     = 'urn:xmpp:media-element'                          # XEP-0221
NS_DELAY          = 'jabber:x:delay'
NS_DELAY2         = 'urn:xmpp:delay'
NS_DIALBACK       = 'jabber:server:dialback'
NS_DISCO          = 'http://jabber.org/protocol/disco'
NS_DISCO_INFO     = NS_DISCO + '#info'
NS_DISCO_ITEMS    = NS_DISCO + '#items'
NS_ENCRYPTED      = 'jabber:x:encrypted'                              # XEP-0027
NS_ESESSION       = 'http://www.xmpp.org/extensions/xep-0116.html#ns'
NS_ESESSION_INIT  = 'http://www.xmpp.org/extensions/xep-0116.html#ns-init' # XEP-0116
NS_EVENT          = 'jabber:x:event'                                  # XEP-0022
NS_FEATURE        = 'http://jabber.org/protocol/feature-neg'
NS_FILE           = 'http://jabber.org/protocol/si/profile/file-transfer' # XEP-0096
NS_FORWARD        = 'urn:xmpp:forward:0'                              # XEP-0297
NS_GAMING         = 'http://jabber.org/protocol/gaming'               # XEP-0196
NS_GATEWAY        = 'jabber:iq:gateway'                               # XEP-0100
NS_GEOLOC         = 'http://jabber.org/protocol/geoloc'               # XEP-0080
NS_GROUPCHAT      = 'gc-1.0'
NS_MSG_HINTS      = 'urn:xmpp:hints'                                  # XEP-0280
NS_HTTP_AUTH      = 'http://jabber.org/protocol/http-auth'            # XEP-0070
NS_HTTP_BIND      = 'http://jabber.org/protocol/httpbind'             # XEP-0124
NS_IBB            = 'http://jabber.org/protocol/ibb'
NS_INVISIBLE      = 'presence-invisible'                              # Jabberd2
NS_IQ             = 'iq'                                              # Jabberd2
NS_JINGLE         ='urn:xmpp:jingle:1'                                # XEP-0166
NS_JINGLE_ERRORS  = 'urn:xmpp:jingle:errors:1'                        # XEP-0166
NS_JINGLE_RTP     = 'urn:xmpp:jingle:apps:rtp:1'                      # XEP-0167
NS_JINGLE_RTP_AUDIO = 'urn:xmpp:jingle:apps:rtp:audio'                # XEP-0167
NS_JINGLE_RTP_VIDEO = 'urn:xmpp:jingle:apps:rtp:video'                # XEP-0167
NS_JINGLE_FILE_TRANSFER ='urn:xmpp:jingle:apps:file-transfer:3'        # XEP-0234
NS_JINGLE_XTLS='urn:xmpp:jingle:security:xtls:0'                      # XTLS: EXPERIMENTAL security layer of jingle
NS_JINGLE_RAW_UDP = 'urn:xmpp:jingle:transports:raw-udp:1'            # XEP-0177
NS_JINGLE_ICE_UDP = 'urn:xmpp:jingle:transports:ice-udp:1'            # XEP-0176
NS_JINGLE_BYTESTREAM ='urn:xmpp:jingle:transports:s5b:1'              # XEP-0260
NS_JINGLE_IBB     = 'urn:xmpp:jingle:transports:ibb:1'                # XEP-0261
NS_LAST           = 'jabber:iq:last'
NS_LOCATION       = 'http://jabber.org/protocol/geoloc'               # XEP-0080
NS_MAM            = 'urn:xmpp:mam:0'                                  # XEP-0313
NS_MESSAGE        = 'message'                                         # Jabberd2
NS_MOOD           = 'http://jabber.org/protocol/mood'                 # XEP-0107
NS_MUC            = 'http://jabber.org/protocol/muc'
NS_MUC_USER       = NS_MUC + '#user'
NS_MUC_ADMIN      = NS_MUC + '#admin'
NS_MUC_OWNER      = NS_MUC + '#owner'
NS_MUC_UNIQUE     = NS_MUC + '#unique'
NS_MUC_CONFIG     = NS_MUC + '#roomconfig'
NS_NICK           = 'http://jabber.org/protocol/nick'                 # XEP-0172
NS_OFFLINE        = 'http://www.jabber.org/jeps/jep-0030.html'        # XEP-0013
NS_PHYSLOC        = 'http://jabber.org/protocol/physloc'              # XEP-0112
NS_PING           = 'urn:xmpp:ping'                                   # XEP-0199
NS_PRESENCE       = 'presence'                                        # Jabberd2
NS_PRIVACY        = 'jabber:iq:privacy'
NS_PRIVATE        = 'jabber:iq:private'
NS_PROFILE        = 'http://jabber.org/protocol/profile'              # XEP-0154
NS_PUBSUB         = 'http://jabber.org/protocol/pubsub'               # XEP-0060
NS_PUBSUB_EVENT   = 'http://jabber.org/protocol/pubsub#event'
NS_PUBSUB_PUBLISH_OPTIONS = NS_PUBSUB + '#publish-options'            # XEP-0060
NS_PUBSUB_OWNER   = 'http://jabber.org/protocol/pubsub#owner'         # XEP-0060
NS_REGISTER       = 'jabber:iq:register'
NS_ROSTER         = 'jabber:iq:roster'
NS_ROSTERNOTES    = 'storage:rosternotes'
NS_ROSTERX        = 'http://jabber.org/protocol/rosterx'              # XEP-0144
NS_ROSTER_VER     = 'urn:xmpp:features:rosterver'                     # XEP-0273
NS_RPC            = 'jabber:iq:rpc'                                   # XEP-0009
NS_RSM            = 'http://jabber.org/protocol/rsm'
NS_SASL           = 'urn:ietf:params:xml:ns:xmpp-sasl'
NS_SECLABEL       = 'urn:xmpp:sec-label:0'
NS_SECLABEL_CATALOG = 'urn:xmpp:sec-label:catalog:2'
NS_SEARCH         = 'jabber:iq:search'
NS_SERVER         = 'jabber:server'
NS_SESSION        = 'urn:ietf:params:xml:ns:xmpp-session'
NS_SI             = 'http://jabber.org/protocol/si'                   # XEP-0096
NS_SI_PUB         = 'http://jabber.org/protocol/sipub'                # XEP-0137
NS_SIGNED         = 'jabber:x:signed'                                 # XEP-0027
NS_SSN            = 'urn:xmpp:ssn'                                    # XEP-0155
NS_STANZA_CRYPTO  = 'http://www.xmpp.org/extensions/xep-0200.html#ns' # XEP-0200
NS_STANZAS        = 'urn:ietf:params:xml:ns:xmpp-stanzas'
NS_STREAM         = 'http://affinix.com/jabber/stream'
NS_STREAMS        = 'http://etherx.jabber.org/streams'
NS_TIME           = 'jabber:iq:time'                                  # XEP-0900
NS_TIME_REVISED   = 'urn:xmpp:time'                                   # XEP-0202
NS_TLS            = 'urn:ietf:params:xml:ns:xmpp-tls'
NS_TUNE           = 'http://jabber.org/protocol/tune'                 # XEP-0118
NS_VACATION       = 'http://jabber.org/protocol/vacation'
NS_VCARD          = 'vcard-temp'
NS_GMAILNOTIFY    = 'google:mail:notify'
NS_GTALKSETTING   = 'google:setting'
NS_VCARD_UPDATE   = NS_VCARD + ':x:update'
NS_VERSION        = 'jabber:iq:version'
NS_VIEWING        = 'http://jabber.org/protocol/viewing'              # XEP--197
NS_WAITINGLIST    = 'http://jabber.org/protocol/waitinglist'          # XEP-0130
NS_XHTML_IM       = 'http://jabber.org/protocol/xhtml-im'             # XEP-0071
NS_XHTML          = 'http://www.w3.org/1999/xhtml'                    # "
NS_X_OOB          = 'jabber:x:oob'                                    # XEP-0066
NS_DATA_LAYOUT    = 'http://jabber.org/protocol/xdata-layout'         # XEP-0141
NS_DATA_VALIDATE  = 'http://jabber.org/protocol/xdata-validate'       # XEP-0122
NS_XMPP_STREAMS   = 'urn:ietf:params:xml:ns:xmpp-streams'
NS_RECEIPTS       = 'urn:xmpp:receipts'
NS_PUBKEY_PUBKEY  = 'urn:xmpp:pubkey:2'                                              # XEP-0189
NS_PUBKEY_REVOKE  = 'urn:xmpp:revoke:2'
NS_PUBKEY_ATTEST  = 'urn:xmpp:attest:2'
NS_STREAM_MGMT    = 'urn:xmpp:sm:2'                                   # XEP-198
NS_HASHES         = 'urn:xmpp:hashes:1'                               # XEP-300
NS_HASHES_MD5     = 'urn:xmpp:hash-function-textual-names:md5'
NS_HASHES_SHA1    = 'urn:xmpp:hash-function-textual-names:sha-1'
NS_HASHES_SHA256  = 'urn:xmpp:hash-function-textual-names:sha-256'
NS_HASHES_SHA512  = 'urn:xmpp:hash-function-textual-names:sha-512'

#xmpp_stream_error_conditions = '''
#bad-format --  --  -- The entity has sent XML that cannot be processed.
#bad-namespace-prefix --  --  -- The entity has sent a namespace prefix that is unsupported, or has sent no namespace prefix on an element that requires such a prefix.
#conflict --  --  -- The server is closing the active stream for this entity because a new stream has been initiated that conflicts with the existing stream.
#connection-timeout --  --  -- The entity has not generated any traffic over the stream for some period of time.
#host-gone --  --  -- The value of the 'to' attribute provided by the initiating entity in the stream header corresponds to a hostname that is no longer hosted by the server.
#host-unknown --  --  -- The value of the 'to' attribute provided by the initiating entity in the stream header does not correspond to a hostname that is hosted by the server.
#improper-addressing --  --  -- A stanza sent between two servers lacks a 'to' or 'from' attribute (or the attribute has no value).
#internal-server-error --  --  -- The server has experienced a misconfiguration or an otherwise-undefined internal error that prevents it from servicing the stream.
#invalid-from -- cancel --  -- The JID or hostname provided in a 'from' address does not match an authorized JID or validated domain negotiated between servers via SASL or dialback, or between a client and a server via authentication and resource authorization.
#invalid-id --  --  -- The stream ID or dialback ID is invalid or does not match an ID previously provided.
#invalid-namespace --  --  -- The streams namespace name is something other than "http://etherx.jabber.org/streams" or the dialback namespace name is something other than "jabber:server:dialback".
#invalid-xml --  --  -- The entity has sent invalid XML over the stream to a server that performs validation.
#not-authorized --  --  -- The entity has attempted to send data before the stream has been authenticated, or otherwise is not authorized to perform an action related to stream negotiation.
#policy-violation --  --  -- The entity has violated some local service policy.
#remote-connection-failed --  --  -- The server is unable to properly connect to a remote resource that is required for authentication or authorization.
#resource-constraint --  --  -- The server lacks the system resources necessary to service the stream.
#restricted-xml --  --  -- The entity has attempted to send restricted XML features such as a comment, processing instruction, DTD, entity reference, or unescaped character.
#see-other-host --  --  -- The server will not provide service to the initiating entity but is redirecting traffic to another host.
#system-shutdown --  --  -- The server is being shut down and all active streams are being closed.
#undefined-condition --  --  -- The error condition is not one of those defined by the other conditions in this list.
#unsupported-encoding --  --  -- The initiating entity has encoded the stream in an encoding that is not supported by the server.
#unsupported-stanza-type --  --  -- The initiating entity has sent a first-level child of the stream that is not supported by the server.
#unsupported-version --  --  -- The value of the 'version' attribute provided by the initiating entity in the stream header specifies a version of XMPP that is not supported by the server.
#xml-not-well-formed --  --  -- The initiating entity has sent XML that is not well-formed.'''

#xmpp_stanza_error_conditions = '''
#bad-request -- 400 -- modify -- The sender has sent XML that is malformed or that cannot be processed.
#conflict -- 409 -- cancel -- Access cannot be granted because an existing resource or session exists with the same name or address.
#feature-not-implemented -- 501 -- cancel -- The feature requested is not implemented by the recipient or server and therefore cannot be processed.
#forbidden -- 403 -- auth -- The requesting entity does not possess the required permissions to perform the action.
#gone -- 302 -- modify -- The recipient or server can no longer be contacted at this address.
#internal-server-error -- 500 -- wait -- The server could not process the stanza because of a misconfiguration or an otherwise-undefined internal server error.
#item-not-found -- 404 -- cancel -- The addressed JID or item requested cannot be found.
#jid-malformed -- 400 -- modify -- The value of the 'to' attribute in the sender's stanza does not adhere to the syntax defined in Addressing Scheme.
#not-acceptable -- 406 -- cancel -- The recipient or server understands the request but is refusing to process it because it does not meet criteria defined by the recipient or server.
#not-allowed -- 405 -- cancel -- The recipient or server does not allow any entity to perform the action.
#not-authorized -- 401 -- auth -- The sender must provide proper credentials before being allowed to perform the action, or has provided improper credentials.
#payment-required -- 402 -- auth -- The requesting entity is not authorized to access the requested service because payment is required.
#recipient-unavailable -- 404 -- wait -- The intended recipient is temporarily unavailable.
#redirect -- 302 -- modify -- The recipient or server is redirecting requests for this information to another entity.
#registration-required -- 407 -- auth -- The requesting entity is not authorized to access the requested service because registration is required.
#remote-server-not-found -- 404 -- cancel -- A remote server or service specified as part or all of the JID of the intended recipient does not exist.
#remote-server-timeout -- 504 -- wait -- A remote server or service specified as part or all of the JID of the intended recipient could not be contacted within a reasonable amount of time.
#resource-constraint -- 500 -- wait -- The server or recipient lacks the system resources necessary to service the request.
#service-unavailable -- 503 -- cancel -- The server or recipient does not currently provide the requested service.
#subscription-required -- 407 -- auth -- The requesting entity is not authorized to access the requested service because a subscription is required.
#undefined-condition -- 500 --  -- Undefined Condition
#unexpected-request -- 400 -- wait -- The recipient or server understood the request but was not expecting it at this time (e.g., the request was out of order).'''

#sasl_error_conditions = '''
#aborted --  --  -- The receiving entity acknowledges an <abort/> element sent by the initiating entity; sent in reply to the <abort/> element.
#incorrect-encoding --  --  -- The data provided by the initiating entity could not be processed because the [BASE64]Josefsson, S., The Base16, Base32, and Base64 Data Encodings, July 2003. encoding is incorrect (e.g., because the encoding does not adhere to the definition in Section 3 of [BASE64]Josefsson, S., The Base16, Base32, and Base64 Data Encodings, July 2003.); sent in reply to a <response/> element or an <auth/> element with initial response data.
#invalid-authzid --  --  -- The authzid provided by the initiating entity is invalid, either because it is incorrectly formatted or because the initiating entity does not have permissions to authorize that ID; sent in reply to a <response/> element or an <auth/> element with initial response data.
#invalid-mechanism --  --  -- The initiating entity did not provide a mechanism or requested a mechanism that is not supported by the receiving entity; sent in reply to an <auth/> element.
#mechanism-too-weak --  --  -- The mechanism requested by the initiating entity is weaker than server policy permits for that initiating entity; sent in reply to a <response/> element or an <auth/> element with initial response data.
#not-authorized --  --  -- The authentication failed because the initiating entity did not provide valid credentials (this includes but is not limited to the case of an unknown username); sent in reply to a <response/> element or an <auth/> element with initial response data.
#temporary-auth-failure --  --  -- The authentication failed because of a temporary error condition within the receiving entity; sent in reply to an <auth/> element or <response/> element.'''

#ERRORS, _errorcodes, loc = {}, {}, {}
#for ns, errname, errpool in ((NS_XMPP_STREAMS, 'STREAM',
#xmpp_stream_error_conditions), (NS_STANZAS, 'ERR', xmpp_stanza_error_conditions),
#(NS_SASL, 'SASL', sasl_error_conditions)):
    #for err in errpool.split('\n')[1:]:
        #cond, code, typ, text = err.split(' -- ')
        #name = errname + '_' + ascii_upper(cond).replace('-', '_')
        #locals()[name] = ns + ' ' + cond
        #loc[name] = ns + ' ' + cond
        #ERRORS[ns + ' ' + cond] = [code, typ, text]
        #if code:
            #_errorcodes[code] = cond
#del ns, errname, errpool, err, cond, code, typ, text
#import pprint
#pprint.pprint(ERRORS)
#pprint.pprint(_errorcodes)
#for (k, v) in loc.items():
     #print('%s = \'%s\'' % (k, v))

ERRORS = {
    'urn:ietf:params:xml:ns:xmpp-sasl aborted': ['',
        '',
        'The receiving entity acknowledges an <abort/> element sent by the initiating entity; sent in reply to the <abort/> element.'],
    'urn:ietf:params:xml:ns:xmpp-sasl incorrect-encoding': ['',
        '',
        'The data provided by the initiating entity could not be processed because the [BASE64]Josefsson, S., The Base16, Base32, and Base64 Data Encodings, July 2003. encoding is incorrect (e.g., because the encoding does not adhere to the definition in Section 3 of [BASE64]Josefsson, S., The Base16, Base32, and Base64 Data Encodings, July 2003.); sent in reply to a <response/> element or an <auth/> element with initial response data.'],
    'urn:ietf:params:xml:ns:xmpp-sasl invalid-authzid': ['',
        '',
        'The authzid provided by the initiating entity is invalid, either because it is incorrectly formatted or because the initiating entity does not have permissions to authorize that ID; sent in reply to a <response/> element or an <auth/> element with initial response data.'],
    'urn:ietf:params:xml:ns:xmpp-sasl invalid-mechanism': ['',
        '',
        'The initiating entity did not provide a mechanism or requested a mechanism that is not supported by the receiving entity; sent in reply to an <auth/> element.'],
    'urn:ietf:params:xml:ns:xmpp-sasl mechanism-too-weak': ['',
        '',
        'The mechanism requested by the initiating entity is weaker than server policy permits for that initiating entity; sent in reply to a <response/> element or an <auth/> element with initial response data.'],
    'urn:ietf:params:xml:ns:xmpp-sasl not-authorized': ['',
        '',
        'The authentication failed because the initiating entity did not provide valid credentials (this includes but is not limited to the case of an unknown username); sent in reply to a <response/> element or an <auth/> element with initial response data.'],
    'urn:ietf:params:xml:ns:xmpp-sasl temporary-auth-failure': ['',
        '',
        'The authentication failed because of a temporary error condition within the receiving entity; sent in reply to an <auth/> element or <response/> element.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas bad-request': ['400',
        'modify',
        'The sender has sent XML that is malformed or that cannot be processed.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas conflict': ['409',
        'cancel',
        'Access cannot be granted because an existing resource or session exists with the same name or address.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas feature-not-implemented': ['501',
        'cancel',
        'The feature requested is not implemented by the recipient or server and therefore cannot be processed.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas forbidden': ['403',
        'auth',
        'The requesting entity does not possess the required permissions to perform the action.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas gone': ['302',
        'modify',
        'The recipient or server can no longer be contacted at this address.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas internal-server-error': ['500',
        'wait',
        'The server could not process the stanza because of a misconfiguration or an otherwise-undefined internal server error.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas item-not-found': ['404',
        'cancel',
        'The addressed JID or item requested cannot be found.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas jid-malformed': ['400',
        'modify',
        "The value of the        'to' attribute in the sender's stanza does not adhere to the syntax defined in Addressing Scheme."],
    'urn:ietf:params:xml:ns:xmpp-stanzas not-acceptable': ['406',
        'cancel',
        'The recipient or server understands the request but is refusing to process it because it does not meet criteria defined by the recipient or server.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas not-allowed': ['405',
        'cancel',
        'The recipient or server does not allow any entity to perform the action.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas not-authorized': ['401',
        'auth',
        'The sender must provide proper credentials before being allowed to perform the action, or has provided improper credentials.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas payment-required': ['402',
        'auth',
        'The requesting entity is not authorized to access the requested service because payment is required.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas recipient-unavailable': ['404',
        'wait',
        'The intended recipient is temporarily unavailable.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas redirect': ['302',
        'modify',
        'The recipient or server is redirecting requests for this information to another entity.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas registration-required': ['407',
        'auth',
        'The requesting entity is not authorized to access the requested service because registration is required.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas remote-server-not-found': ['404',
        'cancel',
        'A remote server or service specified as part or all of the JID of the intended recipient does not exist.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas remote-server-timeout': ['504',
        'wait',
        'A remote server or service specified as part or all of the JID of the intended recipient could not be contacted within a reasonable amount of time.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas resource-constraint': ['500',
        'wait',
        'The server or recipient lacks the system resources necessary to service the request.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas service-unavailable': ['503',
        'cancel',
        'The server or recipient does not currently provide the requested service.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas subscription-required': ['407',
        'auth',
        'The requesting entity is not authorized to access the requested service because a subscription is required.'],
    'urn:ietf:params:xml:ns:xmpp-stanzas undefined-condition': ['500',
        '',
        'Undefined Condition'],
    'urn:ietf:params:xml:ns:xmpp-stanzas unexpected-request': ['400',
        'wait',
        'The recipient or server understood the request but was not expecting it at this time (e.g., the request was out of order).'],
    'urn:ietf:params:xml:ns:xmpp-streams bad-format': ['',
        '',
        'The entity has sent XML that cannot be processed.'],
    'urn:ietf:params:xml:ns:xmpp-streams bad-namespace-prefix': ['',
        '',
        'The entity has sent a namespace prefix that is unsupported, or has sent no namespace prefix on an element that requires such a prefix.'],
    'urn:ietf:params:xml:ns:xmpp-streams conflict': ['',
        '',
        'The server is closing the active stream for this entity because a new stream has been initiated that conflicts with the existing stream.'],
    'urn:ietf:params:xml:ns:xmpp-streams connection-timeout': ['',
        '',
        'The entity has not generated any traffic over the stream for some period of time.'],
    'urn:ietf:params:xml:ns:xmpp-streams host-gone': ['',
        '',
        "The value of the        'to' attribute provided by the initiating entity in the stream header corresponds to a hostname that is no longer hosted by the server."],
    'urn:ietf:params:xml:ns:xmpp-streams host-unknown': ['',
        '',
        "The value of the        'to' attribute provided by the initiating entity in the stream header does not correspond to a hostname that is hosted by the server."],
    'urn:ietf:params:xml:ns:xmpp-streams improper-addressing': ['',
        '',
        "A stanza sent between two servers lacks a        'to' or 'from' attribute (or the attribute has no value)."],
    'urn:ietf:params:xml:ns:xmpp-streams internal-server-error': ['',
        '',
        'The server has experienced a misconfiguration or an otherwise-undefined internal error that prevents it from servicing the stream.'],
    'urn:ietf:params:xml:ns:xmpp-streams invalid-from': ['cancel',
        '',
        "The JID or hostname provided in a        'from' address does not match an authorized JID or validated domain negotiated between servers via SASL or dialback, or between a client and a server via authentication and resource authorization."],
    'urn:ietf:params:xml:ns:xmpp-streams invalid-id': ['',
        '',
        'The stream ID or dialback ID is invalid or does not match an ID previously provided.'],
    'urn:ietf:params:xml:ns:xmpp-streams invalid-namespace': ['',
        '',
        'The streams namespace name is something other than        "http://etherx.jabber.org/streams" or the dialback namespace name is something other than "jabber:server:dialback".'],
    'urn:ietf:params:xml:ns:xmpp-streams invalid-xml': ['',
        '',
        'The entity has sent invalid XML over the stream to a server that performs validation.'],
    'urn:ietf:params:xml:ns:xmpp-streams not-authorized': ['',
        '',
        'The entity has attempted to send data before the stream has been authenticated, or otherwise is not authorized to perform an action related to stream negotiation.'],
    'urn:ietf:params:xml:ns:xmpp-streams policy-violation': ['',
        '',
        'The entity has violated some local service policy.'],
    'urn:ietf:params:xml:ns:xmpp-streams remote-connection-failed': ['',
        '',
        'The server is unable to properly connect to a remote resource that is required for authentication or authorization.'],
    'urn:ietf:params:xml:ns:xmpp-streams resource-constraint': ['',
        '',
        'The server lacks the system resources necessary to service the stream.'],
    'urn:ietf:params:xml:ns:xmpp-streams restricted-xml': ['',
        '',
        'The entity has attempted to send restricted XML features such as a comment, processing instruction, DTD, entity reference, or unescaped character.'],
    'urn:ietf:params:xml:ns:xmpp-streams see-other-host': ['',
        '',
        'The server will not provide service to the initiating entity but is redirecting traffic to another host.'],
    'urn:ietf:params:xml:ns:xmpp-streams system-shutdown': ['',
        '',
        'The server is being shut down and all active streams are being closed.'],
    'urn:ietf:params:xml:ns:xmpp-streams undefined-condition': ['',
        '',
        'The error condition is not one of those defined by the other conditions in this list.'],
    'urn:ietf:params:xml:ns:xmpp-streams unsupported-encoding': ['',
        '',
        'The initiating entity has encoded the stream in an encoding that is not supported by the server.'],
    'urn:ietf:params:xml:ns:xmpp-streams unsupported-stanza-type': ['',
        '',
        'The initiating entity has sent a first-level child of the stream that is not supported by the server.'],
    'urn:ietf:params:xml:ns:xmpp-streams unsupported-version': ['',
        '',
        "The value of the        'version' attribute provided by the initiating entity in the stream header specifies a version of XMPP that is not supported by the server."],
    'urn:ietf:params:xml:ns:xmpp-streams xml-not-well-formed': ['',
        '',
        'The initiating entity has sent XML that is not well-formed.']
}

_errorcodes = {
    '302': 'redirect',
    '400': 'unexpected-request',
    '401': 'not-authorized',
    '402': 'payment-required',
    '403': 'forbidden',
    '404': 'remote-server-not-found',
    '405': 'not-allowed',
    '406': 'not-acceptable',
    '407': 'subscription-required',
    '409': 'conflict',
    '500': 'undefined-condition',
    '501': 'feature-not-implemented',
    '503': 'service-unavailable',
    '504': 'remote-server-timeout',
    'cancel': 'invalid-from'
}

STREAM_NOT_AUTHORIZED = 'urn:ietf:params:xml:ns:xmpp-streams not-authorized'
STREAM_REMOTE_CONNECTION_FAILED = 'urn:ietf:params:xml:ns:xmpp-streams remote-connection-failed'
SASL_MECHANISM_TOO_WEAK = 'urn:ietf:params:xml:ns:xmpp-sasl mechanism-too-weak'
STREAM_XML_NOT_WELL_FORMED = 'urn:ietf:params:xml:ns:xmpp-streams xml-not-well-formed'
ERR_JID_MALFORMED = 'urn:ietf:params:xml:ns:xmpp-stanzas jid-malformed'
STREAM_SEE_OTHER_HOST = 'urn:ietf:params:xml:ns:xmpp-streams see-other-host'
STREAM_BAD_NAMESPACE_PREFIX = 'urn:ietf:params:xml:ns:xmpp-streams bad-namespace-prefix'
ERR_SERVICE_UNAVAILABLE = 'urn:ietf:params:xml:ns:xmpp-stanzas service-unavailable'
STREAM_CONNECTION_TIMEOUT = 'urn:ietf:params:xml:ns:xmpp-streams connection-timeout'
STREAM_UNSUPPORTED_VERSION = 'urn:ietf:params:xml:ns:xmpp-streams unsupported-version'
STREAM_IMPROPER_ADDRESSING = 'urn:ietf:params:xml:ns:xmpp-streams improper-addressing'
STREAM_UNDEFINED_CONDITION = 'urn:ietf:params:xml:ns:xmpp-streams undefined-condition'
SASL_NOT_AUTHORIZED = 'urn:ietf:params:xml:ns:xmpp-sasl not-authorized'
ERR_GONE = 'urn:ietf:params:xml:ns:xmpp-stanzas gone'
SASL_TEMPORARY_AUTH_FAILURE = 'urn:ietf:params:xml:ns:xmpp-sasl temporary-auth-failure'
ERR_REMOTE_SERVER_NOT_FOUND = 'urn:ietf:params:xml:ns:xmpp-stanzas remote-server-not-found'
ERR_UNEXPECTED_REQUEST = 'urn:ietf:params:xml:ns:xmpp-stanzas unexpected-request'
ERR_RECIPIENT_UNAVAILABLE = 'urn:ietf:params:xml:ns:xmpp-stanzas recipient-unavailable'
ERR_CONFLICT = 'urn:ietf:params:xml:ns:xmpp-stanzas conflict'
STREAM_SYSTEM_SHUTDOWN = 'urn:ietf:params:xml:ns:xmpp-streams system-shutdown'
STREAM_BAD_FORMAT = 'urn:ietf:params:xml:ns:xmpp-streams bad-format'
ERR_SUBSCRIPTION_REQUIRED = 'urn:ietf:params:xml:ns:xmpp-stanzas subscription-required'
STREAM_INTERNAL_SERVER_ERROR = 'urn:ietf:params:xml:ns:xmpp-streams internal-server-error'
ERR_NOT_AUTHORIZED = 'urn:ietf:params:xml:ns:xmpp-stanzas not-authorized'
SASL_ABORTED = 'urn:ietf:params:xml:ns:xmpp-sasl aborted'
ERR_REGISTRATION_REQUIRED = 'urn:ietf:params:xml:ns:xmpp-stanzas registration-required'
ERR_INTERNAL_SERVER_ERROR = 'urn:ietf:params:xml:ns:xmpp-stanzas internal-server-error'
SASL_INCORRECT_ENCODING = 'urn:ietf:params:xml:ns:xmpp-sasl incorrect-encoding'
STREAM_HOST_GONE = 'urn:ietf:params:xml:ns:xmpp-streams host-gone'
STREAM_POLICY_VIOLATION = 'urn:ietf:params:xml:ns:xmpp-streams policy-violation'
STREAM_INVALID_XML = 'urn:ietf:params:xml:ns:xmpp-streams invalid-xml'
STREAM_CONFLICT = 'urn:ietf:params:xml:ns:xmpp-streams conflict'
STREAM_RESOURCE_CONSTRAINT = 'urn:ietf:params:xml:ns:xmpp-streams resource-constraint'
STREAM_UNSUPPORTED_ENCODING = 'urn:ietf:params:xml:ns:xmpp-streams unsupported-encoding'
ERR_NOT_ALLOWED = 'urn:ietf:params:xml:ns:xmpp-stanzas not-allowed'
ERR_ITEM_NOT_FOUND = 'urn:ietf:params:xml:ns:xmpp-stanzas item-not-found'
ERR_NOT_ACCEPTABLE = 'urn:ietf:params:xml:ns:xmpp-stanzas not-acceptable'
STREAM_INVALID_FROM = 'urn:ietf:params:xml:ns:xmpp-streams invalid-from'
ERR_FEATURE_NOT_IMPLEMENTED = 'urn:ietf:params:xml:ns:xmpp-stanzas feature-not-implemented'
ERR_BAD_REQUEST = 'urn:ietf:params:xml:ns:xmpp-stanzas bad-request'
STREAM_INVALID_ID = 'urn:ietf:params:xml:ns:xmpp-streams invalid-id'
STREAM_HOST_UNKNOWN = 'urn:ietf:params:xml:ns:xmpp-streams host-unknown'
ERR_UNDEFINED_CONDITION = 'urn:ietf:params:xml:ns:xmpp-stanzas undefined-condition'
SASL_INVALID_MECHANISM = 'urn:ietf:params:xml:ns:xmpp-sasl invalid-mechanism'
STREAM_RESTRICTED_XML = 'urn:ietf:params:xml:ns:xmpp-streams restricted-xml'
ERR_RESOURCE_CONSTRAINT = 'urn:ietf:params:xml:ns:xmpp-stanzas resource-constraint'
ERR_REMOTE_SERVER_TIMEOUT = 'urn:ietf:params:xml:ns:xmpp-stanzas remote-server-timeout'
SASL_INVALID_AUTHZID = 'urn:ietf:params:xml:ns:xmpp-sasl invalid-authzid'
ERR_PAYMENT_REQUIRED = 'urn:ietf:params:xml:ns:xmpp-stanzas payment-required'
STREAM_INVALID_NAMESPACE = 'urn:ietf:params:xml:ns:xmpp-streams invalid-namespace'
ERR_REDIRECT = 'urn:ietf:params:xml:ns:xmpp-stanzas redirect'
STREAM_UNSUPPORTED_STANZA_TYPE = 'urn:ietf:params:xml:ns:xmpp-streams unsupported-stanza-type'
ERR_FORBIDDEN = 'urn:ietf:params:xml:ns:xmpp-stanzas forbidden'

def isResultNode(node):
    """
    Return true if the node is a positive reply
    """
    return node and node.getType() == 'result'

def isErrorNode(node):
    """
    Return true if the node is a negative reply
    """
    return node and node.getType() == 'error'

class NodeProcessed(Exception):
    """
    Exception that should be raised by handler when the handling should be
    stopped
    """
    pass

class StreamError(Exception):
    """
    Base exception class for stream errors
    """
    pass

class BadFormat(StreamError):
    pass

class BadNamespacePrefix(StreamError):
    pass

class Conflict(StreamError):
    pass

class ConnectionTimeout(StreamError):
    pass

class HostGone(StreamError):
    pass

class HostUnknown(StreamError):
    pass

class ImproperAddressing(StreamError):
    pass

class InternalServerError(StreamError):
    pass

class InvalidFrom(StreamError):
    pass

class InvalidID(StreamError):
    pass

class InvalidNamespace(StreamError):
    pass

class InvalidXML(StreamError):
    pass

class NotAuthorized(StreamError):
    pass

class PolicyViolation(StreamError):
    pass

class RemoteConnectionFailed(StreamError):
    pass

class ResourceConstraint(StreamError):
    pass

class RestrictedXML(StreamError):
    pass

class SeeOtherHost(StreamError):
    pass

class SystemShutdown(StreamError):
    pass

class UndefinedCondition(StreamError):
    pass

class UnsupportedEncoding(StreamError):
    pass

class UnsupportedStanzaType(StreamError):
    pass

class UnsupportedVersion(StreamError):
    pass

class XMLNotWellFormed(StreamError):
    pass

stream_exceptions = {'bad-format': BadFormat,
                    'bad-namespace-prefix': BadNamespacePrefix,
                    'conflict': Conflict,
                    'connection-timeout': ConnectionTimeout,
                    'host-gone': HostGone,
                    'host-unknown': HostUnknown,
                    'improper-addressing': ImproperAddressing,
                    'internal-server-error': InternalServerError,
                    'invalid-from': InvalidFrom,
                    'invalid-id': InvalidID,
                    'invalid-namespace': InvalidNamespace,
                    'invalid-xml': InvalidXML,
                    'not-authorized': NotAuthorized,
                    'policy-violation': PolicyViolation,
                    'remote-connection-failed': RemoteConnectionFailed,
                    'resource-constraint': ResourceConstraint,
                    'restricted-xml': RestrictedXML,
                    'see-other-host': SeeOtherHost,
                    'system-shutdown': SystemShutdown,
                    'undefined-condition': UndefinedCondition,
                    'unsupported-encoding': UnsupportedEncoding,
                    'unsupported-stanza-type': UnsupportedStanzaType,
                    'unsupported-version': UnsupportedVersion,
                    'xml-not-well-formed': XMLNotWellFormed}

class JID:
    """
    JID can be built from string, modified, compared, serialised into string
    """

    def __init__(self, jid=None, node='', domain='', resource=''):
        """
        JID can be specified as string (jid argument) or as separate parts

        Examples:
        JID('node@domain/resource')
        JID(node='node',domain='domain.org')
        """
        if not jid and not domain:
            raise ValueError('JID must contain at least domain name')
        elif type(jid) == type(self):
            self.node, self.domain = jid.node, jid.domain
            self.resource = jid.resource
        elif domain:
            self.node, self.domain, self.resource = node, domain, resource
        else:
            if jid.find('@') + 1:
                self.node, jid = jid.split('@', 1)
            else:
                self.node = ''
            if jid.find('/')+1:
                self.domain, self.resource = jid.split('/', 1)
            else:
                self.domain, self.resource = jid, ''

    def getNode(self):
        """
        Return the node part of the JID
        """
        return self.node

    def setNode(self, node):
        """
        Set the node part of the JID to new value. Specify None to remove
        the node part
        """
        self.node = node.lower()

    def getDomain(self):
        """
        Return the domain part of the JID
        """
        return self.domain

    def setDomain(self, domain):
        """
        Set the domain part of the JID to new value
        """
        self.domain = domain.lower()

    def getResource(self):
        """
        Return the resource part of the JID
        """
        return self.resource

    def setResource(self, resource):
        """
        Set the resource part of the JID to new value. Specify None to remove the
        resource part
        """
        self.resource = resource

    def getStripped(self):
        """
        Return the bare representation of JID. I.e. string value w/o resource
        """
        return self.__str__(0)

    def __eq__(self, other):
        """
        Compare the JID to another instance or to string for equality
        """
        try:
            other = JID(other)
        except ValueError:
            return 0
        return self.resource == other.resource and \
            self.__str__(0) == other.__str__(0)

    def __ne__(self, other):
        """
        Compare the JID to another instance or to string for non-equality
        """
        return not self.__eq__(other)

    def bareMatch(self, other):
        """
        Compare the node and domain parts of the JID's for equality
        """
        return self.__str__(0) == JID(other).__str__(0)

    def __str__(self, wresource=1):
        """
        Serialise JID into string
        """
        if self.node:
            jid = self.node + '@' + self.domain
        else:
            jid = self.domain
        if wresource and self.resource:
            return jid + '/' + self.resource
        return jid

    def __hash__(self):
        """
        Produce hash of the JID, Allows to use JID objects as keys of the
        dictionary
        """
        return hash(str(self))

class BOSHBody(Node):
    """
    <body> tag that wraps usual XMPP stanzas in XMPP over BOSH
    """

    def __init__(self, attrs={}, payload=[], node=None):
        Node.__init__(self, tag='body', attrs=attrs, payload=payload, node=node)
        self.setNamespace(NS_HTTP_BIND)


class Protocol(Node):
    """
    A "stanza" object class. Contains methods that are common for presences, iqs
    and messages
    """

    def __init__(self, name=None, to=None, typ=None, frm=None, attrs={},
                    payload=[], timestamp=None, xmlns=None, node=None):
        """
        Constructor, name is the name of the stanza
        i.e. 'message' or 'presence'or 'iq'

        to is the value of 'to' attribure, 'typ' - 'type' attribute
        frn - from attribure, attrs - other attributes mapping,
        payload - same meaning as for simplexml payload definition
        timestamp - the time value that needs to be stamped over stanza
        xmlns - namespace of top stanza node
        node - parsed or unparsed stana to be taken as prototype.
        """
        if not attrs:
            attrs = {}
        if to:
            attrs['to'] = to
        if frm:
            attrs['from'] = frm
        if typ:
            attrs['type'] = typ
        Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node)
        if not node and xmlns:
            self.setNamespace(xmlns)
        if self['to']:
            self.setTo(self['to'])
        if self['from']:
            self.setFrom(self['from'])
        if node and type(self) == type(node) and \
        self.__class__ == node.__class__ and 'id' in self.attrs:
            del self.attrs['id']
        self.timestamp = None
        for d in self.getTags('delay', namespace=NS_DELAY2):
            try:
                if d.getAttr('stamp') < self.getTimestamp2():
                    self.setTimestamp(d.getAttr('stamp'))
            except Exception:
                pass
        if not self.timestamp:
            for x in self.getTags('x', namespace=NS_DELAY):
                try:
                    if x.getAttr('stamp') < self.getTimestamp():
                        self.setTimestamp(x.getAttr('stamp'))
                except Exception:
                    pass
        if timestamp is not None:
            self.setTimestamp(timestamp)  # To auto-timestamp stanza just pass timestamp=''

    def getTo(self):
        """
        Return value of the 'to' attribute
        """
        try:
            return self['to']
        except:
            return None

    def getFrom(self):
        """
        Return value of the 'from' attribute
        """
        try:
            return self['from']
        except:
            return None

    def getTimestamp(self):
        """
        Return the timestamp in the 'yyyymmddThhmmss' format
        """
        if self.timestamp:
            return self.timestamp
        return time.strftime('%Y%m%dT%H:%M:%S', time.gmtime())

    def getTimestamp2(self):
        """
        Return the timestamp in the 'yyyymmddThhmmss' format
        """
        if self.timestamp:
            return self.timestamp
        return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())

    def getID(self):
        """
        Return the value of the 'id' attribute
        """
        return self.getAttr('id')

    def setTo(self, val):
        """
        Set the value of the 'to' attribute
        """
        self.setAttr('to', JID(val))

    def getType(self):
        """
        Return the value of the 'type' attribute
        """
        return self.getAttr('type')

    def setFrom(self, val):
        """
        Set the value of the 'from' attribute
        """
        self.setAttr('from', JID(val))

    def setType(self, val):
        """
        Set the value of the 'type' attribute
        """
        self.setAttr('type', val)

    def setID(self, val):
        """
        Set the value of the 'id' attribute
        """
        self.setAttr('id', val)

    def getError(self):
        """
        Return the error-condition (if present) or the textual description
        of the error (otherwise)
        """
        errtag = self.getTag('error')
        if errtag:
            for tag in errtag.getChildren():
                if tag.getName() != 'text':
                    return tag.getName()
            return errtag.getData()

    def getErrorMsg(self):
        """
        Return the textual description of the error (if present)
        or the error condition
        """
        errtag = self.getTag('error')
        if errtag:
            for tag in errtag.getChildren():
                if tag.getName() == 'text':
                    return tag.getData()
            return self.getError()

    def getErrorCode(self):
        """
        Return the error code. Obsolete.
        """
        return self.getTagAttr('error', 'code')

    def getStatusConditions(self):
        """
        Return the status conditions list as defined in XEP-0306.
        """
        conds = []
        condtag = self.getTag('conditions', namespace=NS_CONDITIONS)
        if condtag:
            for tag in condtag.getChildren():
                conds.append(tag.getName())
        return conds

    def setError(self, error, code=None):
        """
        Set the error code. Obsolete. Use error-conditions instead
        """
        if code:
            if str(code) in _errorcodes.keys():
                error = ErrorNode(_errorcodes[str(code)], text=error)
            else:
                error = ErrorNode(ERR_UNDEFINED_CONDITION, code=code,
                    typ='cancel', text=error)
        elif type(error)  == str:
            error=ErrorNode(error)
        self.setType('error')
        self.addChild(node=error)

    def setTimestamp(self, val=None):
        """
        Set the timestamp. timestamp should be the yyyymmddThhmmss string
        """
        if not val:
            val = time.strftime('%Y%m%dT%H:%M:%S', time.gmtime())
        self.timestamp=val
        self.setTag('x', {'stamp': self.timestamp}, namespace=NS_DELAY)

    def getProperties(self):
        """
        Return the list of namespaces to which belongs the direct childs of element
        """
        props = []
        for child in self.getChildren():
            prop = child.getNamespace()
            if prop not in props:
                props.append(prop)
        return props

    def __setitem__(self, item, val):
        """
        Set the item 'item' to the value 'val'
        """
        if item in ['to', 'from']:
            val = JID(val)
        return self.setAttr(item, val)


class Message(Protocol):
    """
    XMPP Message stanza - "push" mechanism
    """

    def __init__(self, to=None, body=None, xhtml=None, typ=None, subject=None,
        attrs={}, frm=None, payload=[], timestamp=None, xmlns=NS_CLIENT,
        node=None):
        """
        You can specify recipient, text of message, type of message any
        additional attributes, sender of the message, any additional payload
        (f.e. jabber:x:delay element) and namespace in one go.

        Alternatively you can pass in the other XML object as the 'node'
        parameted to replicate it as message
        """
        Protocol.__init__(self, 'message', to=to, typ=typ, attrs=attrs, frm=frm,
                payload=payload, timestamp=timestamp, xmlns=xmlns, node=node)
        if body:
            self.setBody(body)
        if xhtml:
            self.setXHTML(xhtml)
        if subject is not None:
            self.setSubject(subject)

    def getBody(self):
        """
        Return text of the message
        """
        return self.getTagData('body')

    def getXHTML(self, xmllang=None):
        """
        Return serialized xhtml-im element text of the message

        TODO: Returning a DOM could make rendering faster.
        """
        xhtml = self.getTag('html')
        if xhtml:
            if xmllang:
                body = xhtml.getTag('body', attrs={'xml:lang': xmllang})
            else:
                body = xhtml.getTag('body')
            return str(body)
        return None

    def getSubject(self):
        """
        Return subject of the message
        """
        return self.getTagData('subject')

    def getThread(self):
        """
        Return thread of the message
        """
        return self.getTagData('thread')

    def setBody(self, val):
        """
        Set the text of the message"""
        self.setTagData('body', val)

    def setXHTML(self, val, xmllang=None):
        """
        Sets the xhtml text of the message (XEP-0071). The parameter is the
        "inner html" to the body.
        """
        try:
            if xmllang:
                dom = NodeBuilder('<body xmlns="%s" xml:lang="%s">%s</body>' \
                    % (NS_XHTML, xmllang, val)).getDom()
            else:
                dom = NodeBuilder('<body xmlns="%s">%s</body>' % (NS_XHTML,
                    val), 0).getDom()
            if self.getTag('html'):
                self.getTag('html').addChild(node=dom)
            else:
                self.setTag('html', namespace=NS_XHTML_IM).addChild(node=dom)
        except Exception as e:
            print("Error" + str(e))
            # FIXME: log. we could not set xhtml (parse error, whatever)

    def setSubject(self, val):
        """
        Set the subject of the message
        """
        self.setTagData('subject', val)

    def setThread(self, val):
        """
        Set the thread of the message
        """
        self.setTagData('thread', val)

    def buildReply(self, text=None):
        """
        Builds and returns another message object with specified text. The to,
        from, thread and type properties of new message are pre-set as reply to
        this message
        """
        m = Message(to=self.getFrom(), frm=self.getTo(), body=text,
            typ=self.getType())
        th = self.getThread()
        if th:
            m.setThread(th)
        return m

    def getStatusCode(self):
        """
        Return the status code of the message (for groupchat config change)
        """
        attrs = []
        for xtag in self.getTags('x'):
            for child in xtag.getTags('status'):
                attrs.append(child.getAttr('code'))
        return attrs

class Presence(Protocol):

    def __init__(self, to=None, typ=None, priority=None, show=None, status=None,
        attrs={}, frm=None, timestamp=None, payload=[], xmlns=NS_CLIENT,
        node=None):
        """
        You can specify recipient, type of message, priority, show and status
        values any additional attributes, sender of the presence, timestamp, any
        additional payload (f.e. jabber:x:delay element) and namespace in one go.
        Alternatively you can pass in the other XML object as the 'node'
        parameted to replicate it as presence
        """
        Protocol.__init__(self, 'presence', to=to, typ=typ, attrs=attrs, frm=frm,
                payload=payload, timestamp=timestamp, xmlns=xmlns, node=node)
        if priority:
            self.setPriority(priority)
        if show:
            self.setShow(show)
        if status:
            self.setStatus(status)

    def getPriority(self):
        """
        Return the priority of the message
        """
        return self.getTagData('priority')

    def getShow(self):
        """
        Return the show value of the message
        """
        return self.getTagData('show')

    def getStatus(self):
        """
        Return the status string of the message
        """
        return self.getTagData('status')

    def setPriority(self, val):
        """
        Set the priority of the message
        """
        self.setTagData('priority', val)

    def setShow(self, val):
        """
        Set the show value of the message
        """
        self.setTagData('show', val)

    def setStatus(self, val):
        """
        Set the status string of the message
        """
        self.setTagData('status', val)

    def _muc_getItemAttr(self, tag, attr):
        for xtag in self.getTags('x'):
            if xtag.getNamespace() not in (NS_MUC_USER, NS_MUC_ADMIN):
                continue
            for child in xtag.getTags(tag):
                return child.getAttr(attr)

    def _muc_getSubTagDataAttr(self, tag, attr):
        for xtag in self.getTags('x'):
            if xtag.getNamespace() not in (NS_MUC_USER, NS_MUC_ADMIN):
                continue
            for child in xtag.getTags('item'):
                for cchild in child.getTags(tag):
                    return cchild.getData(), cchild.getAttr(attr)
        return None, None

    def getRole(self):
        """
        Return the presence role (for groupchat)
        """
        return self._muc_getItemAttr('item', 'role')

    def getAffiliation(self):
        """
        Return the presence affiliation (for groupchat)
        """
        return self._muc_getItemAttr('item', 'affiliation')

    def getNewNick(self):
        """
        Return the status code of the presence (for groupchat)
        """
        return self._muc_getItemAttr('item', 'nick')

    def getJid(self):
        """
        Return the presence jid (for groupchat)
        """
        return self._muc_getItemAttr('item', 'jid')

    def getReason(self):
        """
        Returns the reason of the presence (for groupchat)
        """
        return self._muc_getSubTagDataAttr('reason', '')[0]

    def getActor(self):
        """
        Return the reason of the presence (for groupchat)
        """
        return self._muc_getSubTagDataAttr('actor', 'jid')[1]

    def getStatusCode(self):
        """
        Return the status code of the presence (for groupchat)
        """
        attrs = []
        for xtag in self.getTags('x'):
            for child in xtag.getTags('status'):
                attrs.append(child.getAttr('code'))
        return attrs

class Iq(Protocol):
    """
    XMPP Iq object - get/set dialog mechanism
    """

    def __init__(self, typ=None, queryNS=None, attrs={}, to=None, frm=None,
                    payload=[], xmlns=NS_CLIENT, node=None):
        """
        You can specify type, query namespace any additional attributes,
        recipient of the iq, sender of the iq, any additional payload (f.e.
        jabber:x:data node) and namespace in one go.

        Alternatively you can pass in the other XML object as the 'node'
        parameted to replicate it as an iq
        """
        Protocol.__init__(self, 'iq', to=to, typ=typ, attrs=attrs, frm=frm,
            xmlns=xmlns, node=node)
        if payload:
            self.setQueryPayload(payload)
        if queryNS:
            self.setQueryNS(queryNS)

    def getQuery(self):
        """
        Return the IQ's child element if it exists, None otherwise.
        """
        children = self.getChildren()
        if children and self.getType() != 'error' and \
        children[0].getName() != 'error':
            return children[0]

    def getQueryNS(self):
        """
        Return the namespace of the 'query' child element
        """
        tag = self.getQuery()
        if tag:
            return tag.getNamespace()

    def getQuerynode(self):
        """
        Return the 'node' attribute value of the 'query' child element
        """
        tag = self.getQuery()
        if tag:
            return tag.getAttr('node')

    def getQueryPayload(self):
        """
        Return the 'query' child element payload
        """
        tag = self.getQuery()
        if tag:
            return tag.getPayload()

    def getQueryChildren(self):
        """
        Return the 'query' child element child nodes
        """
        tag = self.getQuery()
        if tag:
            return tag.getChildren()

    def setQuery(self, name=None):
        """
        Change the name of the query node, creating it if needed. Keep the
        existing name if none is given (use 'query' if it's a creation).
        Return the query node.
        """
        query = self.getQuery()
        if query is None:
            query = self.addChild('query')
        if name is not None:
            query.setName(name)
        return query

    def setQueryNS(self, namespace):
        """
        Set the namespace of the 'query' child element
        """
        self.setQuery().setNamespace(namespace)

    def setQueryPayload(self, payload):
        """
        Set the 'query' child element payload
        """
        self.setQuery().setPayload(payload)

    def setQuerynode(self, node):
        """
        Set the 'node' attribute value of the 'query' child element
        """
        self.setQuery().setAttr('node', node)

    def buildReply(self, typ):
        """
        Build and return another Iq object of specified type. The to, from and
        query child node of new Iq are pre-set as reply to this Iq.
        """
        iq = Iq(typ, to=self.getFrom(), frm=self.getTo(),
            attrs={'id': self.getID()})
        iq.setQuery(self.getQuery().getName()).setNamespace(self.getQueryNS())
        return iq

class Hashes(Node):
    """
    Hash elements for various XEPs as defined in XEP-300
    """

    """
    RECOMENDED HASH USE:
    Algorithm     Support
    MD2           MUST NOT
    MD4           MUST NOT
    MD5           MAY
    SHA-1         MUST
    SHA-256       MUST
    SHA-512       SHOULD
    """

    supported = ('md5', 'sha-1', 'sha-256', 'sha-512')

    def __init__(self, nsp=NS_HASHES):
        Node.__init__(self, None, {}, [], None, None, False, None)
        self.setNamespace(nsp)
        self.setName('hash')

    def calculateHash(self, algo, file_string):
        """
        Calculate the hash and add it. It is preferable doing it here
        instead of doing it all over the place in Gajim.
        """
        hl = None
        hash_ = None
        # file_string can be a string or a file
        if type(file_string) == str: # if it is a string
            if algo == 'sha-1':
                hl = hashlib.sha1()
            elif algo == 'md5':
                hl = hashlib.md5()
            elif algo == 'sha-256':
                hl = hashlib.sha256()
            elif algo == 'sha-512':
                hl = hashlib.sha512()
            if hl:
                hl.update(file_string)
                hash_ = hl.hexdigest()
        else: # if it is a file
            if algo == 'sha-1':
                hl = hashlib.sha1()
            elif algo == 'md5':
                hl = hashlib.md5()
            elif algo == 'sha-256':
                hl = hashlib.sha256()
            elif algo == 'sha-512':
                hl = hashlib.sha512()
            if hl:
                for line in file_string:
                    hl.update(line)
                hash_ = hl.hexdigest()
        return hash_

    def addHash(self, hash_, algo):
        self.setAttr('algo', algo)
        self.setData(hash_)

class Acks(Node):
    """
    Acknowledgement elements for Stream Management
    """
    def __init__(self, nsp=NS_STREAM_MGMT):
        Node.__init__(self, None, {}, [], None, None, False, None)
        self.setNamespace(nsp)

    def buildAnswer(self, handled):
        """
        handled is the number of stanzas handled
        """
        self.setName('a')
        self.setAttr('h', handled)

    def buildRequest(self):
        self.setName('r')

    def buildEnable(self, resume=False):
        self.setName('enable')
        if resume:
            self.setAttr('resume', 'true')

    def buildResume(self, handled, previd):
        self.setName('resume')
        self.setAttr('h', handled)
        self.setAttr('previd', previd)

class ErrorNode(Node):
    """
    XMPP-style error element

    In the case of stanza error should be attached to XMPP stanza.
    In the case of stream-level errors should be used separately.
    """

    def __init__(self, name, code=None, typ=None, text=None):
        """
        Mandatory parameter: name - name of error condition.
        Optional parameters: code, typ, text.
        Used for backwards compartibility with older jabber protocol.
        """
        if name in ERRORS:
            cod, type_, txt = ERRORS[name]
            ns = name.split()[0]
        else:
            cod, ns, type_, txt = '500', NS_STANZAS, 'cancel', ''
        if typ:
            type_ = typ
        if code:
            cod = code
        if text:
            txt = text
        Node.__init__(self, 'error', {}, [Node(name)])
        if type_:
            self.setAttr('type', type_)
        if not cod:
            self.setName('stream:error')
        if txt:
            self.addChild(node=Node(ns + ' text', {}, [txt]))
        if cod:
            self.setAttr('code', cod)

class Error(Protocol):
    """
    Used to quickly transform received stanza into error reply
    """

    def __init__(self, node, error, reply=1):
        """
        Create error reply basing on the received 'node' stanza and the 'error'
        error condition

        If the 'node' is not the received stanza but locally created ('to' and
        'from' fields needs not swapping) specify the 'reply' argument as false.
        """
        if reply:
            Protocol.__init__(self, to=node.getFrom(), frm=node.getTo(), node=node)
        else:
            Protocol.__init__(self, node=node)
        self.setError(error)
        if node.getType() == 'error':
            self.__str__ = self.__dupstr__

    def __dupstr__(self, dup1=None, dup2=None):
        """
        Dummy function used as preventor of creating error node in reply to error
        node. I.e. you will not be able to serialise "double" error into string.
        """
        return ''

class DataField(Node):
    """
    This class is used in the DataForm class to describe the single data item

    If you are working with jabber:x:data (XEP-0004, XEP-0068, XEP-0122) then
    you will need to work with instances of this class.
    """

    def __init__(self, name=None, value=None, typ=None, required=0, desc=None,
                    options=[], node=None):
        """
        Create new data field of specified name,value and type

        Also 'required','desc' and 'options' fields can be set. Alternatively
        other XML object can be passed in as the 'node' parameted
        to replicate it as a new datafiled.
        """
        Node.__init__(self, 'field', node=node)
        if name:
            self.setVar(name)
        if isinstance(value, (list, tuple)):
            self.setValues(value)
        elif value:
            self.setValue(value)
        if typ:
            self.setType(typ)
        elif not typ and not node:
            self.setType('text-single')
        if required:
            self.setRequired(required)
        if desc:
            self.setDesc(desc)
        if options:
            self.setOptions(options)

    def setRequired(self, req=1):
        """
        Change the state of the 'required' flag
        """
        if req:
            self.setTag('required')
        else:
            try:
                self.delChild('required')
            except ValueError:
                return

    def isRequired(self):
        """
        Return in this field a required one
        """
        return self.getTag('required')

    def setDesc(self, desc):
        """
        Set the description of this field
        """
        self.setTagData('desc', desc)

    def getDesc(self):
        """
        Return the description of this field
        """
        return self.getTagData('desc')

    def setValue(self, val):
        """
        Set the value of this field
        """
        self.setTagData('value', val)

    def getValue(self):
        return self.getTagData('value')

    def setValues(self, lst):
        """
        Set the values of this field as values-list. Replaces all previous filed
        values! If you need to just add a value - use addValue method
        """
        while self.getTag('value'):
            self.delChild('value')
        for val in lst:
            self.addValue(val)

    def addValue(self, val):
        """
        Add one more value to this field. Used in 'get' iq's or such
        """
        self.addChild('value', {}, [val])

    def getValues(self):
        """
        Return the list of values associated with this field
        """
        ret = []
        for tag in self.getTags('value'):
            ret.append(tag.getData())
        return ret

    def getOptions(self):
        """
        Return label-option pairs list associated with this field
        """
        ret = []
        for tag in self.getTags('option'):
            ret.append([tag.getAttr('label'), tag.getTagData('value')])
        return ret

    def setOptions(self, lst):
        """
        Set label-option pairs list associated with this field
        """
        while self.getTag('option'):
            self.delChild('option')
        for opt in lst:
            self.addOption(opt)

    def addOption(self, opt):
        """
        Add one more label-option pair to this field
        """
        if isinstance(opt, list):
            self.addChild('option', {'label': opt[0]}).setTagData('value',
                opt[1])
        else:
            self.addChild('option').setTagData('value', opt)

    def getType(self):
        """
        Get type of this field
        """
        return self.getAttr('type')

    def setType(self, val):
        """
        Set type of this field
        """
        return self.setAttr('type', val)

    def getVar(self):
        """
        Get 'var' attribute value of this field
        """
        return self.getAttr('var')

    def setVar(self, val):
        """
        Set 'var' attribute value of this field
        """
        return self.setAttr('var', val)

class DataForm(Node):
    """
    Used for manipulating dataforms in XMPP

    Relevant XEPs: 0004, 0068, 0122. Can be used in disco, pub-sub and many
    other applications.
    """
    def __init__(self, typ=None, data=[], title=None, node=None):
        """
        Create new dataform of type 'typ'. 'data' is the list of DataField
        instances that this dataform contains, 'title' - the title string.  You
        can specify the 'node' argument as the other node to be used as base for
        constructing this dataform

        title and instructions is optional and SHOULD NOT contain newlines.
        Several instructions MAY be present.
        'typ' can be one of ('form' | 'submit' | 'cancel' | 'result' )
        'typ' of reply iq can be ( 'result' | 'set' | 'set' | 'result' ) respectively.
        'cancel' form can not contain any fields. All other forms contains AT LEAST one field.
        'title' MAY be included in forms of type "form" and "result"
        """
        Node.__init__(self, 'x', node=node)
        if node:
            newkids = []
            for n in self.getChildren():
                if n.getName() == 'field':
                    newkids.append(DataField(node=n))
                else:
                    newkids.append(n)
            self.kids = newkids
        if typ:
            self.setType(typ)
        self.setNamespace(NS_DATA)
        if title:
            self.setTitle(title)
        if isinstance(data, dict):
            newdata = []
            for name in data.keys():
                newdata.append(DataField(name, data[name]))
            data = newdata
        for child in data:
            if child.__class__.__name__ == 'DataField':
                self.kids.append(child)
            elif isinstance(child, Node):
                self.kids.append(DataField(node=child))
            else: # Must be a string
                self.addInstructions(child)

    def getType(self):
        """
        Return the type of dataform
        """
        return self.getAttr('type')

    def setType(self, typ):
        """
        Set the type of dataform
        """
        self.setAttr('type', typ)

    def getTitle(self):
        """
        Return the title of dataform
        """
        return self.getTagData('title')

    def setTitle(self, text):
        """
        Set the title of dataform
        """
        self.setTagData('title', text)

    def getInstructions(self):
        """
        Return the instructions of dataform
        """
        return self.getTagData('instructions')

    def setInstructions(self, text):
        """
        Set the instructions of dataform
        """
        self.setTagData('instructions', text)

    def addInstructions(self, text):
        """
        Add one more instruction to the dataform
        """
        self.addChild('instructions', {}, [text])

    def getField(self, name):
        """
        Return the datafield object with name 'name' (if exists)
        """
        return self.getTag('field', attrs={'var': name})

    def setField(self, name):
        """
        Create if nessessary or get the existing datafield object with name
        'name' and return it
        """
        f = self.getField(name)
        if f:
            return f
        return self.addChild(node=DataField(name))

    def asDict(self):
        """
        Represent dataform as simple dictionary mapping of datafield names to
        their values
        """
        ret = {}
        for field in self.getTags('field'):
            name = field.getAttr('var')
            typ = field.getType()
            if typ and typ.endswith('-multi'):
                val = []
                for i in field.getTags('value'):
                    val.append(i.getData())
            else:
                val = field.getTagData('value')
            ret[name] = val
        if self.getTag('instructions'):
            ret['instructions'] = self.getInstructions()
        return ret

    def __getitem__(self, name):
        """
        Simple dictionary interface for getting datafields values by their names
        """
        item = self.getField(name)
        if item:
            return item.getValue()
        raise IndexError('No such field')

    def __setitem__(self, name, val):
        """
        Simple dictionary interface for setting datafields values by their names
        """
        return self.setField(name).setValue(val)