����JFIFXX�����    $.' ",#(7),01444'9=82<.342  2!!22222222222222222222222222222222222222222222222222����"��4�� ���,�PG"Z_�4�˷����kjز�Z�,F+��_z�,�© �����zh6�٨�ic�fu���#ډb���_�N�?��wQ���5-�~�I���8����TK<5o�Iv-�����k�_U_�����~b�M��d����Ӝ�U�Hh��?]��E�w��Q���k�{��_}qFW7HTՑ��Y��F�?_�'ϔ��_�Ջt��=||I ��6�έ"�����D���/[�k�9���Y�8ds|\���Ҿp6�Ҵ���]��.����6�z<�v��@]�i%��$j��~�g��J>��no����pM[me�i$[����s�o�ᘨ�˸ nɜG-�ĨU�ycP�3.DB�li�;��hj���x7Z^�N�h������N3u{�:j�x�힞��#M&��jL P@_���� P��&��o8������9�����@Sz6�t7#O�ߋ �s}Yf�T���lmr����Z)'N��k�۞p����w\�Tȯ?�8`�O��i{wﭹW�[�r�� ��Q4F�׊���3m&L�=��h3����z~��#�\�l :�F,j@�� ʱ�wQT����8�"kJO���6�֚l����}���R�>ډK���]��y����&����p�}b��;N�1�m�r$�|��7�>e�@B�TM*-iH��g�D�)� E�m�|�ؘbҗ�a��Ҿ����t4���o���G��*oCN�rP���Q��@z,|?W[0�����:�n,jWiE��W��$~/�hp\��?��{(�0���+�Y8rΟ�+����>S-S����VN;�}�s?.����� w�9��˟<���Mq4�Wv'��{)0�1mB��V����W[�����8�/<� �%���wT^�5���b��)iM� pg�N�&ݝ��VO~�q���u���9� ����!��J27����$O-���! �:�%H��� ـ����y�ΠM=t{!S�� oK8������t<����è:a������[�����ա�H���~��w��Qz`�po�^ ����Q��n� �,uu�C�$ ^���,������8�#��:�6��e�|~���!�3�3.�\0��q��o�4`.|� ����y�Q�`~;�d�ׯ,��O�Zw�������`73�v�܋�<���Ȏ�� ـ4k��5�K�a�u�=9Yd��$>x�A�&�� j0� ���vF��� Y�|�y��� ~�6�@c��1vOp�Ig����4��l�OD���L����� R���c���j�_�uX6��3?nk��Wy�f;^*B� ��@�~a�`��Eu������+���6�L��.ü>��}y���}_�O�6�͐�:�YrG�X��kG�����l^w���~㒶sy��Iu�!� W ��X��N�7BV��O��!X�2����wvG�R�f�T#�����t�/?���%8�^�W�aT��G�cL�M���I��(J����1~�8�?aT ���]����AS�E��(��*E}� 2��#I/�׍qz��^t�̔���b�Yz4x���t�){ OH��+(E��A&�N�������XT��o��"�XC��'���)}�J�z�p� ��~5�}�^����+�6����w��c��Q�|Lp�d�H��}�(�.|����k��c4^�"�����Z?ȕ ��a<�L�!039C� �Eu�C�F�Ew�ç ;�n?�*o���B�8�bʝ���'#Rqf���M}7����]����s2tcS{�\icTx;�\��7K���P���ʇ Z O-��~��c>"��?�������P��E��O�8��@�8��G��Q�g�a�Վ���󁶠�䧘��_%#r�>�1�z�a��eb��qcPѵ��n���#L��� =��׀t� L�7�`��V���A{�C:�g���e@�w1 Xp3�c3�ġ����p��M"'-�@n4���fG��B3�DJ�8[Jo�ߐ���gK)ƛ��$���� ���8�3�����+���� �����6�ʻ���� ���S�kI�*KZlT _`���?��K����QK�d����B`�s}�>���`��*�>��,*@J�d�oF*����弝��O}�k��s��]��y�ߘ��c1G�V���<=�7��7����6�q�PT��tXԀ�!9*4�4Tހ3XΛex�46���Y��D ����� �BdemDa����\�_l,��G�/���֌7���Y�](�xTt^%�GE�����4�}bT���ڹ�����;Y)���B�Q��u��>J/J �⮶.�XԄ��j�ݳ�+E��d ��r�5�_D�1 ��o�� �B�x�΢�#���<��W�����8���R6�@g�M�.��� dr�D��>(otU��@x=��~v���2� ӣ�d�oBd��3�eO�6�㣷�����ݜ6��6Y��Qz`��S��{���\P�~z m5{J/L��1������<�e�ͅPu�b�]�ϔ���'������f�b� Zpw��c`"��i���BD@:)ִ�:�]��hv�E�w���T�l��P���"Ju�}��وV J��G6��. J/�Qgl߭�e�����@�z�Zev2u�)]կ�����7x���s�M�-<ɯ�c��r�v�����@��$�ޮ}lk���a���'����>x��O\�ZFu>�����ck#��&:��`�$�ai�>2Δ����l���oF[h��lE�ܺ�Πk:)���`�� $[6�����9�����kOw�\|���8}������ބ:��񶐕��I�A1/�=�2[�,�!��.}gN#�u����b��� ~��݊��}34q����d�E��Lc��$��"�[q�U�硬g^��%B �z���r�pJ�ru%v\h1Y�ne`ǥ:g���pQM~�^�Xi� ��`S�:V29.�P���V�?B�k�� AEvw%�_�9C�Q����wKekPؠ�\�;Io d�{ ߞo�c1eP����\� `����E=���@K<�Y���eڼ�J���w����{av�F�'�M�@/J��+9p���|]�����Iw &`��8���&M�hg��[�{��Xj��%��Ӓ�$��(����ʹN���<>�I���RY���K2�NPlL�ɀ)��&e����B+ь����( � �JTx���_?EZ� }@ 6�U���뙢ط�z��dWI�n` D����噥�[��uV��"�G&Ú����2g�}&m��?ċ�"����Om#��������� ��{�ON��"S�X��Ne��ysQ���@Fn��Vg���dX�~nj�]J�<�K]:��FW��b�������62�=��5f����JKw��bf�X�55��~J �%^����:�-�QIE��P��v�nZum� z � ~ə ���� ���ة����;�f��\v���g�8�1��f24;�V���ǔ�)����9���1\��c��v�/'Ƞ�w�������$�4�R-��t���� e�6�/�ġ �̕Ecy�J���u�B���<�W�ַ~�w[B1L۲�-JS΂�{���΃������A��20�c#��@ 0!1@AP"#2Q`$3V�%45a6�FRUq��� ����^7ׅ,$n�������+��F�`��2X'��0vM��p�L=������5��8������u�p~���.�`r�����\���O��,ư�0oS ��_�M�����l���4�kv\JSd���x���SW�<��Ae�IX����������$I���w�:S���y���›R��9�Q[���,�5�;�@]�%���u�@ *ro�lbI �� ��+���%m:�͇ZV�����u�̉����θau<�fc�.����{�4Ա� �Q����*�Sm��8\ujqs]{kN���)qO�y�_*dJ�b�7���yQqI&9�ԌK!�M}�R�;������S�T���1���i[U�ɵz�]��U)V�S6���3$K{�ߊ<�(� E]Զ[ǼENg�����'�\?#)Dkf��J���o��v���'�%ƞ�&K�u�!��b�35LX�Ϸ��63$K�a�;�9>,R��W��3�3� d�JeTYE.Mϧ��-�o�j3+y��y^�c�������VO�9NV\nd�1 ��!͕_)a�v;����թ�M�lWR1��)El��P;��yوÏ�u 3�k�5Pr6<�⒲l�!˞*��u־�n�!�l:����UNW ��%��Chx8vL'��X�@��*��)���̮��ˍ��� ���D-M�+J�U�kvK����+�x8��cY������?�Ԡ��~3mo��|�u@[XeY�C�\Kp�x8�oC�C�&����N�~3-H���� ��MX�s�u<`���~"WL��$8ξ��3���a�)|:@�m�\���^�`�@ҷ)�5p+��6���p�%i)P M���ngc�����#0Aruz���RL+xSS?���ʮ}()#�t��mˇ!��0}}y����<�e� �-ή�Ԩ��X������ MF���ԙ~l L.3���}�V뽺�v�����멬��Nl�)�2����^�Iq��a��M��qG��T�����c3#������3U�Ǎ���}��לS�|qa��ڃ�+���-��2�f����/��bz��ڐ�� �ݼ[2�ç����k�X�2�* �Z�d���J�G����M*9W���s{��w���T��x��y,�in�O�v��]���n����P�$�JB@=4�OTI�n��e�22a\����q�d���%�$��(���:���: /*�K[PR�fr\nڙdN���F�n�$�4�[�� U�zƶ����� �mʋ���,�ao�u 3�z� �x��Kn����\[��VFmbE;�_U��&V�Gg�]L�۪&#n%�$ɯ�dG���D�TI=�%+AB�Ru#��b4�1�»x�cs�YzڙJG��f��Il��d�eF'T� iA��T���uC�$����Y��H?����[!G`}���ͪ� �纤Hv\������j�Ex�K���!���OiƸ�Yj�+u-<���'q����uN�*�r\��+�]���<�wOZ.fp�ێ��,-*)V?j-kÊ#�`�r��dV����(�ݽBk�����G�ƛk�QmUڗe��Z���f}|����8�8��a���i��3'J�����~G_�^���d�8w������ R�`(�~�.��u���l�s+g�bv���W���lGc}��u���afE~1�Ue������Z�0�8�=e�� f@/�jqEKQQ�J��oN��J���W5~M>$6�Lt�;$ʳ{���^��6�{����v6���ķܰg�V�cnn �~z�x�«�,2�u�?cE+Ș�H؎�%�Za�)���X>uW�Tz�Nyo����s���FQƤ��$��*�&�LLXL)�1�" L��eO��ɟ�9=���:t��Z���c��Ž���Y?�ӭV�wv�~,Y��r�ۗ�|�y��GaF�����C�����.�+� ���v1���fήJ�����]�S��T��B��n5sW}y�$��~z�'�c ��8 ��� ,! �p��VN�S��N�N�q��y8z˱�A��4��*��'������2n<�s���^ǧ˭P�Jޮɏ�U�G�L�J�*#��<�V��t7�8����TĜ>��i}K%,���)[��z�21z ?�N�i�n1?T�I�R#��m-�����������������1����lA�`��fT5+��ܐ�c�q՝��ʐ��,���3�f2U�եmab��#ŠdQ�y>\��)�SLY����w#��.���ʑ�f��� ,"+�w�~�N�'�c�O�3F�������N<���)j��&��,-� �љ���֊�_�zS���TǦ����w�>��?�������n��U仆�V���e�����0���$�C�d���rP �m�׈e�Xm�Vu� �L��.�bֹ��� �[Դaզ���*��\y�8�Է:�Ez\�0�Kq�C b��̘��cө���Q��=0Y��s�N��S.���3.���O�o:���#���v7�[#߫ ��5�܎�L���Er4���9n��COWlG�^��0k�%<���ZB���aB_���������'=��{i�v�l�$�uC���mƎҝ{�c㱼�y]���W�i ��ߧc��m�H� m�"�"�����;Y�ߝ�Z�Ǔ�����:S#��|}�y�,/k�Ld� TA�(�AI$+I3��;Y*���Z��}|��ӧO��d�v��..#:n��f>�>���ȶI�TX��� 8��y����"d�R�|�)0���=���n4��6ⲑ�+��r<�O�܂~zh�z����7ܓ�HH�Ga롏���nCo�>������a ���~]���R���̲c?�6(�q�;5%� |�uj�~z8R=X��I�V=�|{v�Gj\gc��q����z�؋%M�ߍ����1y��#��@f^���^�>N�����#x#۹��6�Y~�?�dfPO��{��P�4��V��u1E1J �*|���%���JN��`eWu�zk M6���q t[�� ��g�G���v��WIG��u_ft����5�j�"�Y�:T��ɐ���*�;� e5���4����q$C��2d�}���� _S�L#m�Yp��O�.�C�;��c����Hi#֩%+) �Ӎ��ƲV���SYź��g |���tj��3�8���r|���V��1#;.SQ�A[���S������#���`n�+���$��$I �P\[�@�s��(�ED�z���P��])8�G#��0B��[ى��X�II�q<��9�~[Z멜�Z�⊔IWU&A>�P~�#��dp<�?����7���c��'~���5 ��+$���lx@�M�dm��n<=e�dyX��?{�|Aef ,|n3�<~z�ƃ�uۧ�����P��Y,�ӥQ�*g�#먙R�\���;T��i,��[9Qi歉����c>]9�� ��"�c��P�� �Md?٥��If�ت�u��k��/����F��9�c*9��Ǎ:�ØF���z�n*�@|I�ށ9����N3{'��[�'ͬ�Ҳ4��#}��!�V� Fu��,�,mTIk���v C�7v���B�6k�T9��1�*l� '~��ƞF��lU��'�M ����][ΩũJ_�{�i�I�n��$���L�� j��O�dx�����kza۪��#�E��Cl����x˘�o�����V���ɞ�ljr��)�/,�߬h�L��#��^��L�ф�,íMƁe�̩�NB�L�����iL����q�}��(��q��6IçJ$�W�E$��:������=#����(�K�B����zђ <��K(�N�۫K�w��^O{!����)�H���>x�������lx�?>Պ�+�>�W���,Ly!_�D���Ō�l���Q�!�[ �S����J��1��Ɛ�Y}��b,+�Lo�x�ɓ)����=�y�oh�@�꥟/��I��ѭ=��P�y9��� �ۍYӘ�e+�p�Jnϱ?V\SO%�(�t� ���=?MR�[Ș�����d�/ ��n�l��B�7j� ��!�;ӥ�/�[-���A�>�dN�sLj ��,ɪv��=1c�.SQ�O3�U���ƀ�ܽ�E����������̻��9G�ϷD�7(�}��Ävӌ\�y�_0[w ���<΍>����a_��[0+�L��F.�޺��f�>oN�T����q;���y\��bՃ��y�jH�<|q-eɏ�_?_9+P���Hp$�����[ux�K w�Mw��N�ی'$Y2�=��q���KB��P��~������Yul:�[<����F1�2�O���5=d����]Y�sw:���Ϯ���E��j,_Q��X��z`H1,#II ��d�wr��P˂@�ZJV����y$�\y�{}��^~���[:N����ߌ�U�������O��d�����ؾe��${p>G��3c���Ė�lʌ�� ת��[��`ϱ�-W����dg�I��ig2��� ��}s ��ؤ(%#sS@���~���3�X�nRG�~\jc3�v��ӍL��M[JB�T��s3}��j�Nʖ��W����;7��ç?=X�F=-�=����q�ߚ���#���='�c��7���ڑW�I(O+=:uxq�������������e2�zi+�kuG�R��������0�&e�n���iT^J����~\jy���p'dtG��s����O��3����9* �b#Ɋ�� p������[Bws�T�>d4�ۧs���nv�n���U���_�~,�v����ƜJ1��s�� �QIz��)�(lv8M���U=�;����56��G���s#�K���MP�=��LvyGd��}�VwWBF�'�à �?MH�U�g2�� ����!�p�7Q��j��ڴ����=��j�u��� Jn�A s���uM������e��Ɔ�Ҕ�!)'��8Ϣ�ٔ��ޝ(��Vp���צ֖d=�IC�J�Ǡ{q������kԭ�߸���i��@K����u�|�p=..�*+����x�����z[Aqġ#s2a�Ɗ���RR�)*HRsi�~�a &f��M��P����-K�L@��Z��Xy�'x�{}��Zm+���:�)�) IJ�-i�u���� ���ܒH��'�L(7�y�GӜq���� j��� 6ߌg1�g�o���,kر���tY�?W,���p���e���f�OQS��!K�۟cҒA�|ս�j�>��=⬒��˧L[�� �߿2JaB~R��u�:��Q�] �0H~���]�7��Ƽ�I���(}��cq '�ήET���q�?f�ab���ӥvr� �)o��-Q��_'����ᴎo��K������;��V���o��%���~OK ����*��b�f:���-ťIR��`B�5!RB@���ï�� �u �̯e\�_U�_������� g�ES��3�������QT��a����x����U<~�c?�*�#]�MW,[8O�a�x��]�1bC|踤�P��lw5V%�)�{t�<��d��5���0i�XSU��m:��Z�┵�i�"��1�^B�-��P�hJ��&)O��*�D��c�W��vM��)����}���P��ܗ-q����\mmζZ-l@�}��a��E�6��F�@��&Sg@���ݚ�M����� ȹ 4����#p�\H����dYDo�H���"��\��..R�B�H�z_�/5˘����6��KhJR��P�mƶi�m���3�,#c�co��q�a)*Pt����R�m�k�7x�D�E�\Y�閣_X�<���~�)���c[[�BP����6�Yq���S��0����%_����;��Àv�~�| VS؇ ��'O0��F0��\���U�-�d@�����7�SJ*z��3n��y��P����O���������m�~�P�3|Y��ʉr#�C�<�G~�.,! ���bqx���h~0=��!ǫ�jy����l�O,�[B��~��|9��ٱ����Xly�#�i�B��g%�S��������tˋ���e���ې��\[d�t)��.+u�|1 ������#�~Oj����hS�%��i.�~X���I�H�m��0n���c�1uE�q��cF�RF�o���7� �O�ꮧ� ���ۛ{��ʛi5�rw?׌#Qn�TW��~?y$��m\�\o����%W� ?=>S�N@�� �Ʈ���R����N�)�r"C�:��:����� �����#��qb��Y�. �6[��2K����2u�Ǧ�HYR��Q�MV��� �G�$��Q+.>�����nNH��q�^��� ����q��mM��V��D�+�-�#*�U�̒ ���p욳��u:�������IB���m���PV@O���r[b= �� ��1U�E��_Nm�yKbN�O���U�}�the�`�|6֮P>�\2�P�V���I�D�i�P�O;�9�r�mAHG�W�S]��J*�_�G��+kP�2����Ka�Z���H�'K�x�W�MZ%�O�YD�Rc+o��?�q��Ghm��d�S�oh�\�D�|:W������UA�Qc yT�q������~^�H��/��#p�CZ���T�I�1�ӏT����4��"�ČZ�����}��`w�#�*,ʹ�� ��0�i��課�Om�*�da��^gJ݅{���l�e9uF#T�ֲ��̲�ٞC"�q���ߍ ոޑ�o#�XZTp����@ o�8��(jd��xw�]�,f���`~�|,s��^����f�1���t��|��m�򸄭/ctr��5s��7�9Q�4�H1꠲BB@l9@���C�����+�wp�xu�£Yc�9��?`@#�o�mH�s2��)�=��2�.�l����jg�9$�Y�S�%*L������R�Y������7Z���,*=�䷘$�������arm�o�ϰ���UW.|�r�uf����IGw�t����Zwo��~5 ��YյhO+=8fF�)�W�7�L9lM�̘·Y���֘YLf�큹�pRF���99.A �"wz��=E\Z���'a� 2��Ǚ�#;�'}�G���*��l��^"q��+2FQ� hj��kŦ��${���ޮ-�T�٭cf�|�3#~�RJ����t��$b�(R��(����r���dx� >U b�&9,>���%E\� Ά�e�$��'�q't��*�א���ެ�b��-|d���SB�O�O��$�R+�H�)�܎�K��1m`;�J�2�Y~9��O�g8=vqD`K[�F)k�[���1m޼c��n���]s�k�z$@��)!I �x՝"v��9=�ZA=`Ɠi �:�E��)`7��vI��}d�YI�_ �o�:ob���o ���3Q��&D&�2=�� �Ά��;>�h����y.*ⅥS������Ӭ�+q&����j|UƧ����}���J0��WW< ۋS�)jQR�j���Ư��rN)�Gű�4Ѷ(�S)Ǣ�8��i��W52���No˓� ۍ%�5brOn�L�;�n��\G����=�^U�dI���8$�&���h��'���+�(������cȁ߫k�l��S^���cƗjԌE�ꭔ��gF���Ȓ��@���}O���*;e�v�WV���YJ\�]X'5��ղ�k�F��b 6R�o՜m��i N�i����>J����?��lPm�U��}>_Z&�KK��q�r��I�D�Չ~�q�3fL�:S�e>���E���-G���{L�6p�e,8��������QI��h��a�Xa��U�A'���ʂ���s�+טIjP�-��y�8ۈZ?J$��W�P� ��R�s�]��|�l(�ԓ��sƊi��o(��S0��Y� 8�T97.�����WiL��c�~�dxc�E|�2!�X�K�Ƙਫ਼�$((�6�~|d9u+�qd�^3�89��Y�6L�.I�����?���iI�q���9�)O/뚅����O���X��X�V��ZF[�یgQ�L��K1���RҖr@v�#��X�l��F���Нy�S�8�7�kF!A��sM���^rkp�jP�DyS$N���q��nxҍ!U�f�!eh�i�2�m���`�Y�I�9r�6� �TF���C}/�y�^���Η���5d�'��9A-��J��>{�_l+�`��A���[�'��յ�ϛ#w:݅�%��X�}�&�PSt�Q�"�-��\縵�/����$Ɨh�Xb�*�y��BS����;W�ջ_mc�����vt?2}1�;qS�d�d~u:2k5�2�R�~�z+|HE!)�Ǟl��7`��0�<�,�2*���Hl-��x�^����'_TV�gZA�'j� ^�2Ϊ��N7t�����?w�� �x1��f��Iz�C-Ȗ��K�^q�;���-W�DvT�7��8�Z�������� hK�(P:��Q- �8�n�Z���܃e貾�<�1�YT<�,�����"�6{/ �?�͟��|1�:�#g��W�>$����d��J��d�B��=��jf[��%rE^��il:��B���x���Sּ�1հ��,�=��*�7 fcG��#q� �eh?��2�7�����,�!7x��6�n�LC�4x��},Geǝ�tC.��vS �F�43��zz\��;QYC,6����~;RYS/6���|2���5���v��T��i����������mlv��������&� �nRh^ejR�LG�f���? �ۉҬܦƩ��|��Ȱ����>3����!v��i�ʯ�>�v��オ�X3e���_1z�Kȗ\<������!�8���V��]��?b�k41�Re��T�q��mz��TiOʦ�Z��Xq���L������q"+���2ۨ��8}�&N7XU7Ap�d�X��~�׿��&4e�o�F��� �H����O���č�c�� 懴�6���͉��+)��v;j��ݷ�� �UV�� i��� j���Y9GdÒJ1��詞�����V?h��l����l�cGs�ځ�������y�Ac�����\V3�? �� ܙg�>qH�S,�E�W�[�㺨�uch�⍸�O�}���a��>�q�6�n6����N6�q������N ! 1AQaq�0@����"2BRb�#Pr���3C`��Scst���$4D���%Td�� ?���N����a��3��m���C���w��������xA�m�q�m���m������$����4n淿t'��C"w��zU=D�\R+w�p+Y�T�&�պ@��ƃ��3ޯ?�Aﶂ��aŘ���@-�����Q�=���9D��ռ�ѻ@��M�V��P��܅�G5�f�Y<�u=,EC)�<�Fy'�"�&�չ�X~f��l�KԆV��?�� �W�N����=(� �;���{�r����ٌ�Y���h{�١������jW����P���Tc�����X�K�r��}���w�R��%��?���E��m�� �Y�q|����\lEE4���r���}�lsI�Y������f�$�=�d�yO����p�����yBj8jU�o�/�S��?�U��*������ˍ�0������u�q�m [�?f����a�� )Q�>����6#������� ?����0UQ����,IX���(6ڵ[�DI�MNލ�c&���υ�j\��X�R|,4��� j������T�hA�e��^���d���b<����n�� �즇�=!���3�^�`j�h�ȓr��jẕ�c�,ٞX����-����a�ﶔ���#�$��]w�O��Ӫ�1y%��L�Y<�wg#�ǝ�̗`�x�xa�t�w��»1���o7o5��>�m뭛C���Uƃߜ}�C���y1Xνm�F8�jI���]����H���ۺиE@I�i;r�8ӭ����V�F�Շ| ��&?�3|x�B�MuS�Ge�=Ӕ�#BE5G�����Y!z��_e��q�р/W>|-�Ci߇�t�1ޯќd�R3�u��g�=0 5��[?�#͏��q�cf���H��{ ?u�=?�?ǯ���}Z��z���hmΔ�BFTW�����<�q�(v� ��!��z���iW]*�J�V�z��gX֧A�q�&��/w���u�gYӘa���; �i=����g:��?2�dž6�ى�k�4�>�Pxs����}������G�9��3 ���)gG�R<>r h�$��'nc�h�P��Bj��J�ҧH� -��N1���N��?��~��}-q!=��_2hc�M��l�vY%UE�@|�v����M2�.Y[|y�"Eï��K�ZF,�ɯ?,q�?v�M 80jx�"�;�9vk�����+ ֧�� �ȺU��?�%�vcV��mA�6��Qg^M����A}�3�nl� QRN�l8�kkn�'�����(��M�7m9و�q���%ޟ���*h$Zk"��$�9��: �?U8�Sl��,,|ɒ��xH(ѷ����Gn�/Q�4�P��G�%��Ա8�N��!� �&�7�;���eKM7�4��9R/%����l�c>�x;������>��C�:�����t��h?aKX�bhe�ᜋ^�$�Iհ �hr7%F$�E��Fd���t��5���+�(M6�t����Ü�UU|zW�=a�Ts�Tg������dqP�Q����b'�m���1{|Y����X�N��b �P~��F^F:����k6�"�j!�� �I�r�`��1&�-$�Bevk:y���#yw��I0��x��=D�4��tU���P�ZH��ڠ底taP��6����b>�xa����Q�#� WeF��ŮNj�p�J* mQ�N����*I�-*�ȩ�F�g�3 �5��V�ʊ�ɮ�a��5F���O@{���NX��?����H�]3��1�Ri_u��������ѕ�� ����0��� F��~��:60�p�͈�S��qX#a�5>���`�o&+�<2�D����: �������ڝ�$�nP���*)�N�|y�Ej�F�5ټ�e���ihy�Z �>���k�bH�a�v��h�-#���!�Po=@k̆IEN��@��}Ll?j�O������߭�ʞ���Q|A07x���wt!xf���I2?Z��<ץ�T���cU�j��]��陎Ltl �}5�ϓ��$�,��O�mˊ�;�@O��jE��j(�ا,��LX���LO���Ц�90�O �.����a��nA���7������j4 ��W��_ٓ���zW�jcB������y՗+EM�)d���N�g6�y1_x��p�$Lv:��9�"z��p���ʙ$��^��JԼ*�ϭ����o���=x�Lj�6�J��u82�A�H�3$�ٕ@�=Vv�]�'�qEz�;I˼��)��=��ɯ���x �/�W(V���p�����$ �m�������u�����񶤑Oqˎ�T����r��㠚x�sr�GC��byp�G��1ߠ�w e�8�$⿄����/�M{*}��W�]˷.�CK\�ުx���/$�WPw���r� |i���&�}�{�X� �>��$-��l���?-z���g����lΆ���(F���h�vS*���b���߲ڡn,|)mrH[���a�3�ר�[1��3o_�U�3�TC�$��(�=�)0�kgP���� ��u�^=��4 �WYCҸ:��vQ�ר�X�à��tk�m,�t*��^�,�}D*� �"(�I��9R����>`�`��[~Q]�#af��i6l��8���6�:,s�s�N6�j"�A4���IuQ��6E,�GnH��zS�HO�uk�5$�I�4��ؤ�Q9�@��C����wp�BGv[]�u�Ov���0I4���\��y�����Q�Ѹ��~>Z��8�T��a��q�ޣ;z��a���/��S��I:�ܫ_�|������>=Z����8:�S��U�I�J��"IY���8%b8���H��:�QO�6�;7�I�S��J��ҌAά3��>c���E+&jf$eC+�z�;��V����� �r���ʺ������my�e���aQ�f&��6�ND��.:��NT�vm�<- u���ǝ\MvZY�N�NT��-A�>jr!S��n�O 1�3�Ns�%�3D@���`������ܟ 1�^c<���� �a�ɽ�̲�Xë#�w�|y�cW�=�9I*H8�p�^(4���՗�k��arOcW�tO�\�ƍR��8����'�K���I�Q�����?5�>[�}��yU�ײ -h��=��% q�ThG�2�)���"ו3]�!kB��*p�FDl�A���,�eEi�H�f�Ps�����5�H:�Փ~�H�0Dت�D�I����h�F3�������c��2���E��9�H��5�zԑ�ʚ�i�X�=:m�xg�hd(�v����׊�9iS��O��d@0ڽ���:�p�5�h-��t�&���X�q�ӕ,��ie�|���7A�2���O%P��E��htj��Y1��w�Ѓ!����  ���� ࢽ��My�7�\�a�@�ţ�J �4�Ȼ�F�@o�̒?4�wx��)��]�P��~�����u�����5�����7X ��9��^ܩ�U;Iꭆ 5 �������eK2�7(�{|��Y׎ �V��\"���Z�1� Z�����}��(�Ǝ"�1S���_�vE30>���p;� ΝD��%x�W�?W?v����o�^V�i�d��r[��/&>�~`�9Wh��y�;���R��� ;;ɮT��?����r$�g1�K����A��C��c��K��l:�'��3 c�ﳯ*"t8�~l��)���m��+U,z��`(�>yJ�?����h>��]��v��ЍG*�{`��;y]��I�T� ;c��NU�fo¾h���/$���|NS���1�S�"�H��V���T���4��uhǜ�]�v;���5�͠x��'C\�SBpl���h}�N����� A�Bx���%��ޭ�l��/����T��w�ʽ]D�=����K���ž�r㻠l4�S�O?=�k �M:� ��c�C�a�#ha���)�ѐxc�s���gP�iG��{+���x���Q���I= �� z��ԫ+ �8"�k�ñ�j=|����c ��y��CF��/��*9ж�h{ �?4�o� ��k�m�Q�N�x��;�Y��4膚�a�w?�6�>e]�����Q�r�:����g�,i"�����ԩA�*M�<�G��b�if��l^M��5� �Ҩ�{����6J��ZJ�����P�*�����Y���ݛu�_4�9�I8�7���������,^ToR���m4�H��?�N�S�ѕw��/S��甍�@�9H�S�T��t�ƻ���ʒU��*{Xs�@����f�����֒Li�K{H�w^���������Ϥm�tq���s� ���ք��f:��o~s��g�r��ט� �S�ѱC�e]�x���a��) ���(b-$(�j>�7q�B?ӕ�F��hV25r[7 Y� }L�R��}����*sg+��x�r�2�U=�*'WS��ZDW]�WǞ�<��叓���{�$�9Ou4��y�90-�1�'*D`�c�^o?(�9��u���ݐ��'PI&� f�Jݮ�������:wS����jfP1F:X �H�9dԯ���˝[�_54 �}*;@�ܨ�� ð�yn�T���?�ןd�#���4rG�ͨ��H�1�|-#���Mr�S3��G�3�����)�.᧏3v�z֑��r����$G"�`j �1t��x0<Ɔ�Wh6�y�6��,œ�Ga��gA����y��b��)��h�D��ß�_�m��ü �gG;��e�v��ݝ�nQ� ��C����-�*��o���y�a��M��I�>�<���]obD��"�:���G�A��-\%LT�8���c�)��+y76���o�Q�#*{�(F�⽕�y����=���rW�\p���۩�c���A���^e6��K������ʐ�cVf5$�'->���ՉN"���F�"�UQ@�f��Gb~��#�&�M=��8�ט�JNu9��D��[̤�s�o�~������ G��9T�tW^g5y$b��Y'��س�Ǵ�=��U-2 #�MC�t(�i� �lj�@Q 5�̣i�*�O����s�x�K�f��}\��M{E�V�{�υ��Ƈ�����);�H����I��fe�Lȣr�2��>��W�I�Ȃ6������i��k�� �5�YOxȺ����>��Y�f5'��|��H+��98pj�n�.O�y�������jY��~��i�w'������l�;�s�2��Y��:'lg�ꥴ)o#'Sa�a�K��Z� �m��}�`169�n���"���x��I ��*+� }F<��cГ���F�P�������ֹ*�PqX�x۩��,� ��N�� �4<-����%����:��7����W���u�`����� $�?�I��&����o��o��`v�>��P��"��l���4��5'�Z�gE���8���?��[�X�7(��.Q�-��*���ތL@̲����v��.5���[��=�t\+�CNܛ��,g�SQnH����}*F�G16���&:�t��4ُ"A��̣��$�b �|����#rs��a�����T�� ]�<�j��BS�('$�ɻ� �wP;�/�n��?�ݜ��x�F��yUn�~mL*-�������Xf�wd^�a�}��f�,=t�׵i�.2/wpN�Ep8�OР���•��R�FJ� 55TZ��T �ɭ�<��]��/�0�r�@�f��V��V����Nz�G��^���7hZi����k��3�,kN�e|�vg�1{9]_i��X5y7� 8e]�U����'�-2,���e"����]ot�I��Y_��n�(JҼ��1�O ]bXc���Nu�No��pS���Q_���_�?i�~�x h5d'�(qw52] ��'ޤ�q��o1�R!���`ywy�A4u���h<קy���\[~�4�\ X�Wt/� 6�����n�F�a8��f���z �3$�t(���q��q�x��^�XWeN'p<-v�!�{�(>ӽDP7��ո0�y)�e$ٕv�Ih'Q�EA�m*�H��RI��=:��� ���4牢) �%_iN�ݧ�l]� �Nt���G��H�L��� ɱ�g<���1V�,�J~�ٹ�"K��Q�� 9�HS�9�?@��k����r�;we݁�]I�!{ �@�G�[�"��`���J:�n]�{�cA�E����V��ʆ���#��U9�6����j�#Y�m\��q�e4h�B�7��C�������d<�?J����1g:ٳ���=Y���D�p�ц� ׈ǔ��1�]26؜oS�'��9�V�FVu�P�h�9�xc�oq�X��p�o�5��Ա5$�9W�V(�[Ak�aY錎qf;�'�[�|���b�6�Ck��)��#a#a˙��8���=äh�4��2��C��4tm^ �n'c���]GQ$[Wҿ��i���vN�{Fu ��1�gx��1┷���N�m��{j-,��x�� Ūm�ЧS�[�s���Gna���䑴�� x�p 8<������97�Q���ϴ�v�aϚG��Rt�Һ׈�f^\r��WH�JU�7Z���y)�vg=����n��4�_)y��D'y�6�]�c�5̪�\� �PF�k����&�c;��cq�$~T�7j ���nç]�<�g ":�to�t}�159�<�/�8������m�b�K#g'I'.W�����6��I/��>v��\�MN��g���m�A�yQL�4u�Lj�j9��#44�t��l^�}L����n��R��!��t��±]��r��h6ٍ>�yҏ�N��fU�� ���� Fm@�8}�/u��jb9������he:A�y�ծw��GpΧh�5����l}�3p468��)U��d��c����;Us/�֔�YX�1�O2��uq�s��`hwg�r~�{ R��mhN��؎*q 42�*th��>�#���E����#��Hv�O����q�}�����6�e��\�,Wk�#���X��b>��p}�դ��3���T5��†��6��[��@�P�y*n��|'f�֧>�lư΂�̺����SU�'*�q�p�_S�����M�� '��c�6�����m�� ySʨ;M��r���Ƌ�m�Kxo,���Gm�P��A�G�:��i��w�9�}M(�^�V��$ǒ�ѽ�9���|���� �a����J�SQ�a���r�B;����}���ٻ֢�2�%U���c�#�g���N�a�ݕ�'�v�[�OY'��3L�3�;,p�]@�S��{ls��X�'���c�jw�k'a�.��}�}&�� �dP�*�bK=ɍ!����;3n�gΊU�ߴmt�'*{,=SzfD� A��ko~�G�aoq�_mi}#�m�������P�Xhύ����mxǍ�΂���巿zf��Q���c���|kc�����?���W��Y�$���_Lv����l߶��c���`?����l�j�ݲˏ!V��6����U�Ђ(A���4y)H���p�Z_�x��>���e��R��$�/�`^'3qˏ�-&Q�=?��CFVR �D�fV�9��{�8g�������n�h�(P"��6�[�D���< E�����~0<@�`�G�6����Hг�cc�� �c�K.5��D��d�B���`?�XQ��2��ٿyqo&+�1^� DW�0�ꊩ���G�#��Q�nL3��c���������/��x ��1�1[y�x�პCW��C�c�UĨ80�m�e�4.{�m��u���I=��f�����0QRls9���f���������9���~f�����Ǩ��a�"@�8���ȁ�Q����#c�ic������G��$���G���r/$W�(��W���V�"��m�7�[m�A�m����bo��D� j����۳� l���^�k�h׽����� ��#� iXn�v��eT�k�a�^Y�4�BN��ĕ��0 !01@Q"2AaPq3BR������?���@4�Q�����T3,���㺠�W�[=JK�Ϟ���2�r^7��vc�:�9 �E�ߴ�w�S#d���Ix��u��:��Hp��9E!�� V 2;73|F��9Y���*ʬ�F��D����u&���y؟��^EA��A��(ɩ���^��GV:ݜDy�`��Jr29ܾ�㝉��[���E;Fzx��YG��U�e�Y�C���� ����v-tx����I�sם�Ę�q��Eb�+P\ :>�i�C'�;�����k|z�رn�y]�#ǿb��Q��������w�����(�r|ӹs��[�D��2v-%��@;�8<a���[\o[ϧw��I!��*0�krs)�[�J9^��ʜ��p1)� "��/_>��o��<1����A�E�y^�C��`�x1'ܣn�p��s`l���fQ��):�l����b>�Me�jH^?�kl3(�z:���1ŠK&?Q�~�{�ٺ�h�y���/�[��V�|6��}�KbX����mn[-��7�5q�94�������dm���c^���h� X��5��<�eޘ>G���-�}�دB�ޟ� ��|�rt�M��V+�]�c?�-#ڛ��^ǂ}���Lkr���O��u�>�-D�ry� D?:ޞ�U��ǜ�7�V��?瓮�"�#���r��չģVR;�n���/_� ؉v�ݶe5d�b9��/O��009�G���5n�W����JpA�*�r9�>�1��.[t���s�F���nQ� V 77R�]�ɫ8����_0<՜�IF�u(v��4��F�k�3��E)��N:��yڮe��P�`�1}�$WS��J�SQ�N�j�ٺ��޵�#l���ј(�5=��5�lǏmoW�v-�1����v,W�mn��߀$x�<����v�j(����c]��@#��1������Ǔ���o'��u+����;G�#�޸��v-lη��/(`i⣍Pm^���ԯ̾9Z��F��������n��1��� ��]�[��)�'������:�֪�W��FC����� �B9،!?���]��V��A�Վ�M��b�w��G F>_DȬ0¤�#�QR�[V��kz���m�w�"��9ZG�7'[��=�Q����j8R?�zf�\a�=��O�U����*oB�A�|G���2�54 �p��.w7� �� ��&������ξxGHp� B%��$g�����t�Џ򤵍z���HN�u�Я�-�'4��0��;_��3 !01"@AQa2Pq#3BR������?��ʩca��en��^��8���<�u#��m*08r��y�N"�<�Ѳ0��@\�p��� �����Kv�D��J8�Fҽ� �f�Y��-m�ybX�NP����}�!*8t(�OqѢ��Q�wW�K��ZD��Δ^e��!� ��B�K��p~�����e*l}z#9ң�k���q#�Ft�o��S�R����-�w�!�S���Ӥß|M�l޶V��!eˈ�8Y���c�ЮM2��tk���� ������J�fS����Ö*i/2�����n]�k�\���|4yX�8��U�P.���Ы[���l��@"�t�<������5�lF���vU�����W��W��;�b�cД^6[#7@vU�xgZv��F�6��Q,K�v��� �+Ъ��n��Ǣ��Ft���8��0��c�@�!�Zq s�v�t�;#](B��-�nῃ~���3g������5�J�%���O������n�kB�ĺ�.r��+���#�N$?�q�/�s�6��p��a����a��J/��M�8��6�ܰ"�*������ɗud"\w���aT(����[��F��U՛����RT�b���n�*��6���O��SJ�.�ij<�v�MT��R\c��5l�sZB>F��<7�;EA��{��E���Ö��1U/�#��d1�a�n.1ě����0�ʾR�h��|�R��Ao�3�m3 ��%�� ���28Q� ��y��φ���H�To�7�lW>����#i`�q���c����a��� �m,B�-j����݋�'mR1Ήt�>��V��p���s�0IbI�C.���1R�ea�����]H�6����������4B>��o��](��$B���m�����a�!=��?�B� K�Ǿ+�Ծ"�n���K��*��+��[T#�{E�J�S����Q�����s�5�:�U�\wĐ�f�3����܆&�)����I���Ԇw��E T�lrTf6Q|R�h:��[K�� �z��c֧�G�C��%\��_�a�84��HcO�bi��ؖV��7H �)*ģK~Xhչ0��4?�0��� �E<���}3���#���u�?�� ��|g�S�6ꊤ�|�I#Hڛ� �ա��w�X��9��7���Ŀ%�SL��y6č��|�F�a 8���b��$�sק�h���b9RAu7�˨p�Č�_\*w��묦��F ����4D~�f����|(�"m���NK��i�S�>�$d7SlA��/�²����SL��|6N�}���S�˯���g��]6��; �#�.��<���q'Q�1|KQ$�����񛩶"�$r�b:���N8�w@��8$�� �AjfG|~�9F ���Y��ʺ��Bwؒ������M:I岎�G��`s�YV5����6��A �b:�W���G�q%l�����F��H���7�������Fsv7��k�� 403WebShell
403Webshell
Server IP : 54.89.25.11  /  Your IP : 216.73.216.255
Web Server : Apache/2.4.7 (Ubuntu)
System : Linux ip-172-31-88-18 3.13.0-74-generic #118-Ubuntu SMP Thu Dec 17 22:52:10 UTC 2015 x86_64
User : www-data ( 33)
PHP Version : 5.5.9-1ubuntu4.24
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /proc/self/root/usr/lib/python2.7/dist-packages/twisted/names/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /proc/self/root/usr/lib/python2.7/dist-packages/twisted/names/dns.py
# -*- test-case-name: twisted.names.test.test_dns -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
DNS protocol implementation.

Future Plans:
    - Get rid of some toplevels, maybe.
"""

from __future__ import division, absolute_import

__all__ = [
    'IEncodable', 'IRecord',

    'A', 'A6', 'AAAA', 'AFSDB', 'CNAME', 'DNAME', 'HINFO',
    'MAILA', 'MAILB', 'MB', 'MD', 'MF', 'MG', 'MINFO', 'MR', 'MX',
    'NAPTR', 'NS', 'NULL', 'OPT', 'PTR', 'RP', 'SOA', 'SPF', 'SRV', 'TXT',
    'WKS',

    'ANY', 'CH', 'CS', 'HS', 'IN',

    'ALL_RECORDS', 'AXFR', 'IXFR',

    'EFORMAT', 'ENAME', 'ENOTIMP', 'EREFUSED', 'ESERVER',

    'Record_A', 'Record_A6', 'Record_AAAA', 'Record_AFSDB', 'Record_CNAME',
    'Record_DNAME', 'Record_HINFO', 'Record_MB', 'Record_MD', 'Record_MF',
    'Record_MG', 'Record_MINFO', 'Record_MR', 'Record_MX', 'Record_NAPTR',
    'Record_NS', 'Record_NULL', 'Record_PTR', 'Record_RP', 'Record_SOA',
    'Record_SPF', 'Record_SRV', 'Record_TXT', 'Record_WKS', 'UnknownRecord',

    'QUERY_CLASSES', 'QUERY_TYPES', 'REV_CLASSES', 'REV_TYPES', 'EXT_QUERIES',

    'Charstr', 'Message', 'Name', 'Query', 'RRHeader', 'SimpleRecord',
    'DNSDatagramProtocol', 'DNSMixin', 'DNSProtocol',

    'OK', 'OP_INVERSE', 'OP_NOTIFY', 'OP_QUERY', 'OP_STATUS', 'OP_UPDATE',
    'PORT',

    'AuthoritativeDomainError', 'DNSQueryTimeoutError', 'DomainError',
    ]


# System imports
import struct, random, socket
from itertools import chain

from io import BytesIO

AF_INET6 = socket.AF_INET6

from zope.interface import implementer, Interface, Attribute


# Twisted imports
from twisted.internet import protocol, defer
from twisted.internet.error import CannotListenError
from twisted.python import log, failure
from twisted.python import util as tputil
from twisted.python import randbytes
from twisted.python.compat import _PY3, unicode, comparable, cmp, nativeString


if _PY3:
    def _ord2bytes(ordinal):
        """
        Construct a bytes object representing a single byte with the given
        ordinal value.

        @type ordinal: C{int}
        @rtype: C{bytes}
        """
        return bytes([ordinal])


    def _nicebytes(bytes):
        """
        Represent a mostly textful bytes object in a way suitable for presentation
        to an end user.

        @param bytes: The bytes to represent.
        @rtype: C{str}
        """
        return repr(bytes)[1:]


    def _nicebyteslist(list):
        """
        Represent a list of mostly textful bytes objects in a way suitable for
        presentation to an end user.

        @param list: The list of bytes to represent.
        @rtype: C{str}
        """
        return '[%s]' % (
            ', '.join([_nicebytes(b) for b in list]),)
else:
    _ord2bytes = chr
    _nicebytes = _nicebyteslist = repr



def randomSource():
    """
    Wrapper around L{randbytes.secureRandom} to return 2 random chars.
    """
    return struct.unpack('H', randbytes.secureRandom(2, fallback=True))[0]


PORT = 53

(A, NS, MD, MF, CNAME, SOA, MB, MG, MR, NULL, WKS, PTR, HINFO, MINFO, MX, TXT,
 RP, AFSDB) = range(1, 19)
AAAA = 28
SRV = 33
NAPTR = 35
A6 = 38
DNAME = 39
OPT = 41
SPF = 99

QUERY_TYPES = {
    A: 'A',
    NS: 'NS',
    MD: 'MD',
    MF: 'MF',
    CNAME: 'CNAME',
    SOA: 'SOA',
    MB: 'MB',
    MG: 'MG',
    MR: 'MR',
    NULL: 'NULL',
    WKS: 'WKS',
    PTR: 'PTR',
    HINFO: 'HINFO',
    MINFO: 'MINFO',
    MX: 'MX',
    TXT: 'TXT',
    RP: 'RP',
    AFSDB: 'AFSDB',

    # 19 through 27?  Eh, I'll get to 'em.

    AAAA: 'AAAA',
    SRV: 'SRV',
    NAPTR: 'NAPTR',
    A6: 'A6',
    DNAME: 'DNAME',
    OPT: 'OPT',
    SPF: 'SPF'
}

IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = range(251, 256)

# "Extended" queries (Hey, half of these are deprecated, good job)
EXT_QUERIES = {
    IXFR: 'IXFR',
    AXFR: 'AXFR',
    MAILB: 'MAILB',
    MAILA: 'MAILA',
    ALL_RECORDS: 'ALL_RECORDS'
}

REV_TYPES = dict([
    (v, k) for (k, v) in chain(QUERY_TYPES.items(), EXT_QUERIES.items())
])

IN, CS, CH, HS = range(1, 5)
ANY = 255

QUERY_CLASSES = {
    IN: 'IN',
    CS: 'CS',
    CH: 'CH',
    HS: 'HS',
    ANY: 'ANY'
}
REV_CLASSES = dict([
    (v, k) for (k, v) in QUERY_CLASSES.items()
])


# Opcodes
OP_QUERY, OP_INVERSE, OP_STATUS = range(3)
OP_NOTIFY = 4 # RFC 1996
OP_UPDATE = 5 # RFC 2136


# Response Codes
OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = range(6)

class IRecord(Interface):
    """
    An single entry in a zone of authority.
    """

    TYPE = Attribute("An indicator of what kind of record this is.")


# Backwards compatibility aliases - these should be deprecated or something I
# suppose. -exarkun
from twisted.names.error import DomainError, AuthoritativeDomainError
from twisted.names.error import DNSQueryTimeoutError



def _nameToLabels(name):
    """
    Split a domain name into its constituent labels.

    @type name: C{str}
    @param name: A fully qualified domain name (with or without a
        trailing dot).

    @return: A L{list} of labels ending with an empty label
        representing the DNS root zone.
    """
    if name in (b'', b'.'):
        return [b'']
    labels = name.split(b'.')
    if labels[-1] != b'':
        labels.append(b'')
    return labels



def _isSubdomainOf(descendantName, ancestorName):
    """
    Test whether C{descendantName} is equal to or is a I{subdomain} of
    C{ancestorName}.

    The names are compared case-insensitively.

    The names are treated as byte strings containing one or more
    DNS labels separated by B{.}.

    C{descendantName} is considered equal if its sequence of labels
    exactly matches the labels of C{ancestorName}.

    C{descendantName} is considered a I{subdomain} if its sequence of
    labels ends with the labels of C{ancestorName}.

    @type descendantName: C{bytes}
    @param descendantName: The DNS subdomain name.

    @type ancestorName: C{bytes}
    @param ancestorName: The DNS parent or ancestor domain name.

    @return: C{True} if C{descendantName} is equal to or if it is a
        subdomain of C{ancestorName}. Otherwise returns C{False}.
    """
    descendantLabels = _nameToLabels(descendantName.lower())
    ancestorLabels = _nameToLabels(ancestorName.lower())
    return descendantLabels[-len(ancestorLabels):] == ancestorLabels



def str2time(s):
    """
    Parse a string description of an interval into an integer number of seconds.

    @param s: An interval definition constructed as an interval duration
        followed by an interval unit.  An interval duration is a base ten
        representation of an integer.  An interval unit is one of the following
        letters: S (seconds), M (minutes), H (hours), D (days), W (weeks), or Y
        (years).  For example: C{"3S"} indicates an interval of three seconds;
        C{"5D"} indicates an interval of five days.  Alternatively, C{s} may be
        any non-string and it will be returned unmodified.
    @type s: text string (C{str}) for parsing; anything else for passthrough.

    @return: an C{int} giving the interval represented by the string C{s}, or
        whatever C{s} is if it is not a string.
    """
    suffixes = (
        ('S', 1), ('M', 60), ('H', 60 * 60), ('D', 60 * 60 * 24),
        ('W', 60 * 60 * 24 * 7), ('Y', 60 * 60 * 24 * 365)
    )
    if isinstance(s, str):
        s = s.upper().strip()
        for (suff, mult) in suffixes:
            if s.endswith(suff):
                return int(float(s[:-1]) * mult)
        try:
            s = int(s)
        except ValueError:
            raise ValueError("Invalid time interval specifier: " + s)
    return s


def readPrecisely(file, l):
    buff = file.read(l)
    if len(buff) < l:
        raise EOFError
    return buff


class IEncodable(Interface):
    """
    Interface for something which can be encoded to and decoded
    from a file object.
    """

    def encode(strio, compDict = None):
        """
        Write a representation of this object to the given
        file object.

        @type strio: File-like object
        @param strio: The stream to which to write bytes

        @type compDict: C{dict} or C{None}
        @param compDict: A dictionary of backreference addresses that have
        have already been written to this stream and that may be used for
        compression.
        """

    def decode(strio, length = None):
        """
        Reconstruct an object from data read from the given
        file object.

        @type strio: File-like object
        @param strio: The stream from which bytes may be read

        @type length: C{int} or C{None}
        @param length: The number of bytes in this RDATA field.  Most
        implementations can ignore this value.  Only in the case of
        records similar to TXT where the total length is in no way
        encoded in the data is it necessary.
        """



@implementer(IEncodable)
class Charstr(object):

    def __init__(self, string=b''):
        if not isinstance(string, bytes):
            raise ValueError("%r is not a byte string" % (string,))
        self.string = string


    def encode(self, strio, compDict=None):
        """
        Encode this Character string into the appropriate byte format.

        @type strio: file
        @param strio: The byte representation of this Charstr will be written
            to this file.
        """
        string = self.string
        ind = len(string)
        strio.write(_ord2bytes(ind))
        strio.write(string)


    def decode(self, strio, length=None):
        """
        Decode a byte string into this Charstr.

        @type strio: file
        @param strio: Bytes will be read from this file until the full string
            is decoded.

        @raise EOFError: Raised when there are not enough bytes available from
            C{strio}.
        """
        self.string = b''
        l = ord(readPrecisely(strio, 1))
        self.string = readPrecisely(strio, l)


    def __eq__(self, other):
        if isinstance(other, Charstr):
            return self.string == other.string
        return NotImplemented


    def __ne__(self, other):
        if isinstance(other, Charstr):
            return self.string != other.string
        return NotImplemented


    def __hash__(self):
        return hash(self.string)


    def __str__(self):
        """
        Represent this L{Charstr} instance by its string value.
        """
        return nativeString(self.string)



@implementer(IEncodable)
class Name:
    """
    A name in the domain name system, made up of multiple labels.  For example,
    I{twistedmatrix.com}.

    @ivar name: A byte string giving the name.
    @type name: C{bytes}
    """
    def __init__(self, name=b''):
        if isinstance(name, unicode):
            name = name.encode('idna')
        if not isinstance(name, bytes):
            raise TypeError("%r is not a byte string" % (name,))
        self.name = name


    def encode(self, strio, compDict=None):
        """
        Encode this Name into the appropriate byte format.

        @type strio: file
        @param strio: The byte representation of this Name will be written to
        this file.

        @type compDict: dict
        @param compDict: dictionary of Names that have already been encoded
        and whose addresses may be backreferenced by this Name (for the purpose
        of reducing the message size).
        """
        name = self.name
        while name:
            if compDict is not None:
                if name in compDict:
                    strio.write(
                        struct.pack("!H", 0xc000 | compDict[name]))
                    return
                else:
                    compDict[name] = strio.tell() + Message.headerSize
            ind = name.find(b'.')
            if ind > 0:
                label, name = name[:ind], name[ind + 1:]
            else:
                # This is the last label, end the loop after handling it.
                label = name
                name = None
                ind = len(label)
            strio.write(_ord2bytes(ind))
            strio.write(label)
        strio.write(b'\x00')


    def decode(self, strio, length=None):
        """
        Decode a byte string into this Name.

        @type strio: file
        @param strio: Bytes will be read from this file until the full Name
        is decoded.

        @raise EOFError: Raised when there are not enough bytes available
        from C{strio}.

        @raise ValueError: Raised when the name cannot be decoded (for example,
            because it contains a loop).
        """
        visited = set()
        self.name = b''
        off = 0
        while 1:
            l = ord(readPrecisely(strio, 1))
            if l == 0:
                if off > 0:
                    strio.seek(off)
                return
            if (l >> 6) == 3:
                new_off = ((l&63) << 8
                            | ord(readPrecisely(strio, 1)))
                if new_off in visited:
                    raise ValueError("Compression loop in encoded name")
                visited.add(new_off)
                if off == 0:
                    off = strio.tell()
                strio.seek(new_off)
                continue
            label = readPrecisely(strio, l)
            if self.name == b'':
                self.name = label
            else:
                self.name = self.name + b'.' + label

    def __eq__(self, other):
        if isinstance(other, Name):
            return self.name == other.name
        return NotImplemented


    def __ne__(self, other):
        if isinstance(other, Name):
            return self.name != other.name
        return NotImplemented


    def __hash__(self):
        return hash(self.name)


    def __str__(self):
        """
        Represent this L{Name} instance by its string name.
        """
        return nativeString(self.name)



@comparable
@implementer(IEncodable)
class Query:
    """
    Represent a single DNS query.

    @ivar name: The name about which this query is requesting information.
    @ivar type: The query type.
    @ivar cls: The query class.
    """
    name = None
    type = None
    cls = None

    def __init__(self, name=b'', type=A, cls=IN):
        """
        @type name: C{bytes}
        @param name: The name about which to request information.

        @type type: C{int}
        @param type: The query type.

        @type cls: C{int}
        @param cls: The query class.
        """
        self.name = Name(name)
        self.type = type
        self.cls = cls


    def encode(self, strio, compDict=None):
        self.name.encode(strio, compDict)
        strio.write(struct.pack("!HH", self.type, self.cls))


    def decode(self, strio, length = None):
        self.name.decode(strio)
        buff = readPrecisely(strio, 4)
        self.type, self.cls = struct.unpack("!HH", buff)


    def __hash__(self):
        return hash((str(self.name).lower(), self.type, self.cls))


    def __cmp__(self, other):
        if isinstance(other, Query):
            return cmp(
                (str(self.name).lower(), self.type, self.cls),
                (str(other.name).lower(), other.type, other.cls))
        return NotImplemented


    def __str__(self):
        t = QUERY_TYPES.get(self.type, EXT_QUERIES.get(self.type, 'UNKNOWN (%d)' % self.type))
        c = QUERY_CLASSES.get(self.cls, 'UNKNOWN (%d)' % self.cls)
        return '<Query %s %s %s>' % (self.name, t, c)


    def __repr__(self):
        return 'Query(%r, %r, %r)' % (str(self.name), self.type, self.cls)



@implementer(IEncodable)
class _OPTHeader(tputil.FancyStrMixin, tputil.FancyEqMixin, object):
    """
    An OPT record header.

    @ivar name: The DNS name associated with this record. Since this
        is a pseudo record, the name is always an L{Name} instance
        with value b'', which represents the DNS root zone. This
        attribute is a readonly property.

    @ivar type: The DNS record type. This is a fixed value of 41
        (C{dns.OPT} for OPT Record. This attribute is a readonly
        property.

    @see: L{_OPTHeader.__init__} for documentation of other public
        instance attributes.

    @see: L{https://tools.ietf.org/html/rfc6891#section-6.1.2}

    @since: 13.2
    """
    showAttributes = (
        ('name', lambda n: nativeString(n.name)), 'type', 'udpPayloadSize',
        'extendedRCODE', 'version', 'dnssecOK', 'options')

    compareAttributes = (
        'name', 'type', 'udpPayloadSize', 'extendedRCODE', 'version',
        'dnssecOK', 'options')

    def __init__(self, udpPayloadSize=4096, extendedRCODE=0, version=0,
                 dnssecOK=False, options=None):
        """
        @type udpPayloadSize: L{int}
        @param payload: The number of octets of the largest UDP
            payload that can be reassembled and delivered in the
            requestor's network stack.

        @type extendedRCODE: L{int}
        @param extendedRCODE: Forms the upper 8 bits of extended
            12-bit RCODE (together with the 4 bits defined in
            [RFC1035].  Note that EXTENDED-RCODE value 0 indicates
            that an unextended RCODE is in use (values 0 through 15).

        @type version: L{int}
        @param version: Indicates the implementation level of the
            setter.  Full conformance with this specification is
            indicated by version C{0}.

        @type dnssecOK: L{bool}
        @param dnssecOK: DNSSEC OK bit as defined by [RFC3225].

        @type options: L{list}
        @param options: A L{list} of 0 or more L{_OPTVariableOption}
            instances.
        """
        self.udpPayloadSize = udpPayloadSize
        self.extendedRCODE = extendedRCODE
        self.version = version
        self.dnssecOK = dnssecOK

        if options is None:
            options = []
        self.options = options


    @property
    def name(self):
        """
        A readonly property for accessing the C{name} attribute of
        this record.

        @return: The DNS name associated with this record. Since this
            is a pseudo record, the name is always an L{Name} instance
            with value b'', which represents the DNS root zone.
        """
        return Name(b'')


    @property
    def type(self):
        """
        A readonly property for accessing the C{type} attribute of
        this record.

        @return: The DNS record type. This is a fixed value of 41
            (C{dns.OPT} for OPT Record.
        """
        return OPT


    def encode(self, strio, compDict=None):
        """
        Encode this L{_OPTHeader} instance to bytes.

        @type strio: L{file}
        @param strio: the byte representation of this L{_OPTHeader}
            will be written to this file.

        @type compDict: L{dict} or L{None}
        @param compDict: A dictionary of backreference addresses that
            have have already been written to this stream and that may
            be used for DNS name compression.
        """
        b = BytesIO()
        for o in self.options:
            o.encode(b)
        optionBytes = b.getvalue()

        RRHeader(
            name=self.name.name,
            type=self.type,
            cls=self.udpPayloadSize,
            ttl=(
                self.extendedRCODE << 24
                | self.version << 16
                | self.dnssecOK << 15),
            payload=UnknownRecord(optionBytes)
        ).encode(strio, compDict)


    def decode(self, strio, length=None):
        """
        Decode bytes into an L{_OPTHeader} instance.

        @type strio: L{file}
        @param strio: Bytes will be read from this file until the full
            L{_OPTHeader} is decoded.

        @type length: L{int} or L{None}
        @param length: Not used.
        """

        h = RRHeader()
        h.decode(strio, length)
        h.payload = UnknownRecord(readPrecisely(strio, h.rdlength))

        newOptHeader = self.fromRRHeader(h)

        for attrName in self.compareAttributes:
            if attrName not in ('name', 'type'):
                setattr(self, attrName, getattr(newOptHeader, attrName))


    @classmethod
    def fromRRHeader(cls, rrHeader):
        """
        A classmethod for constructing a new L{_OPTHeader} from the
        attributes and payload of an existing L{RRHeader} instance.

        @type rrHeader: L{RRHeader}
        @param rrHeader: An L{RRHeader} instance containing an
            L{UnknownRecord} payload.

        @return: An instance of L{_OPTHeader}.
        @rtype: L{_OPTHeader}
        """
        options = None
        if rrHeader.payload is not None:
            options = []
            optionsBytes = BytesIO(rrHeader.payload.data)
            optionsBytesLength = len(rrHeader.payload.data)
            while optionsBytes.tell() < optionsBytesLength:
                o = _OPTVariableOption()
                o.decode(optionsBytes)
                options.append(o)

        # Decode variable options if present
        return cls(
            udpPayloadSize=rrHeader.cls,
            extendedRCODE=rrHeader.ttl >> 24,
            version=rrHeader.ttl >> 16 & 0xff,
            dnssecOK=(rrHeader.ttl & 0xffff) >> 15,
            options=options
            )



@implementer(IEncodable)
class _OPTVariableOption(tputil.FancyStrMixin, tputil.FancyEqMixin, object):
    """
    A class to represent OPT record variable options.

    @see: L{_OPTVariableOption.__init__} for documentation of public
        instance attributes.

    @see: L{https://tools.ietf.org/html/rfc6891#section-6.1.2}

    @since: 13.2
    """
    showAttributes = ('code', ('data', nativeString))
    compareAttributes = ('code', 'data')

    _fmt = '!HH'

    def __init__(self, code=0, data=b''):
        """
        @type code: L{int}
        @param code: The option code

        @type data: L{bytes}
        @param data: The option data
        """
        self.code = code
        self.data = data


    def encode(self, strio, compDict=None):
        """
        Encode this L{_OPTVariableOption} to bytes.

        @type strio: L{file}
        @param strio: the byte representation of this
            L{_OPTVariableOption} will be written to this file.

        @type compDict: L{dict} or L{None}
        @param compDict: A dictionary of backreference addresses that
            have have already been written to this stream and that may
            be used for DNS name compression.
        """
        strio.write(
            struct.pack(self._fmt, self.code, len(self.data)) + self.data)


    def decode(self, strio, length=None):
        """
        Decode bytes into an L{_OPTVariableOption} instance.

        @type strio: L{file}
        @param strio: Bytes will be read from this file until the full
            L{_OPTVariableOption} is decoded.

        @type length: L{int} or L{None}
        @param length: Not used.
        """
        l = struct.calcsize(self._fmt)
        buff = readPrecisely(strio, l)
        self.code, length = struct.unpack(self._fmt, buff)
        self.data = readPrecisely(strio, length)



@implementer(IEncodable)
class RRHeader(tputil.FancyEqMixin):
    """
    A resource record header.

    @cvar fmt: C{str} specifying the byte format of an RR.

    @ivar name: The name about which this reply contains information.
    @ivar type: The query type of the original request.
    @ivar cls: The query class of the original request.
    @ivar ttl: The time-to-live for this record.
    @ivar payload: An object that implements the IEncodable interface

    @ivar auth: A C{bool} indicating whether this C{RRHeader} was parsed from an
        authoritative message.
    """
    compareAttributes = ('name', 'type', 'cls', 'ttl', 'payload', 'auth')

    fmt = "!HHIH"

    name = None
    type = None
    cls = None
    ttl = None
    payload = None
    rdlength = None

    cachedResponse = None

    def __init__(self, name=b'', type=A, cls=IN, ttl=0, payload=None, auth=False):
        """
        @type name: C{bytes}
        @param name: The name about which this reply contains information.

        @type type: C{int}
        @param type: The query type.

        @type cls: C{int}
        @param cls: The query class.

        @type ttl: C{int}
        @param ttl: Time to live for this record.

        @type payload: An object implementing C{IEncodable}
        @param payload: A Query Type specific data object.

        @raises ValueError: if the ttl is negative.
        """
        assert (payload is None) or isinstance(payload, UnknownRecord) or (payload.TYPE == type)

        if ttl < 0:
            raise ValueError("TTL cannot be negative")

        self.name = Name(name)
        self.type = type
        self.cls = cls
        self.ttl = ttl
        self.payload = payload
        self.auth = auth


    def encode(self, strio, compDict=None):
        self.name.encode(strio, compDict)
        strio.write(struct.pack(self.fmt, self.type, self.cls, self.ttl, 0))
        if self.payload:
            prefix = strio.tell()
            self.payload.encode(strio, compDict)
            aft = strio.tell()
            strio.seek(prefix - 2, 0)
            strio.write(struct.pack('!H', aft - prefix))
            strio.seek(aft, 0)


    def decode(self, strio, length = None):
        self.name.decode(strio)
        l = struct.calcsize(self.fmt)
        buff = readPrecisely(strio, l)
        r = struct.unpack(self.fmt, buff)
        self.type, self.cls, self.ttl, self.rdlength = r


    def isAuthoritative(self):
        return self.auth


    def __str__(self):
        t = QUERY_TYPES.get(self.type, EXT_QUERIES.get(self.type, 'UNKNOWN (%d)' % self.type))
        c = QUERY_CLASSES.get(self.cls, 'UNKNOWN (%d)' % self.cls)
        return '<RR name=%s type=%s class=%s ttl=%ds auth=%s>' % (self.name, t, c, self.ttl, self.auth and 'True' or 'False')


    __repr__ = __str__



@implementer(IEncodable, IRecord)
class SimpleRecord(tputil.FancyStrMixin, tputil.FancyEqMixin):
    """
    A Resource Record which consists of a single RFC 1035 domain-name.

    @type name: L{Name}
    @ivar name: The name associated with this record.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.
    """
    showAttributes = (('name', 'name', '%s'), 'ttl')
    compareAttributes = ('name', 'ttl')

    TYPE = None
    name = None

    def __init__(self, name=b'', ttl=None):
        self.name = Name(name)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        self.name.encode(strio, compDict)


    def decode(self, strio, length = None):
        self.name = Name()
        self.name.decode(strio)


    def __hash__(self):
        return hash(self.name)


# Kinds of RRs - oh my!
class Record_NS(SimpleRecord):
    """
    An authoritative nameserver.
    """
    TYPE = NS
    fancybasename = 'NS'



class Record_MD(SimpleRecord):
    """
    A mail destination.

    This record type is obsolete.

    @see: L{Record_MX}
    """
    TYPE = MD
    fancybasename = 'MD'



class Record_MF(SimpleRecord):
    """
    A mail forwarder.

    This record type is obsolete.

    @see: L{Record_MX}
    """
    TYPE = MF
    fancybasename = 'MF'



class Record_CNAME(SimpleRecord):
    """
    The canonical name for an alias.
    """
    TYPE = CNAME
    fancybasename = 'CNAME'



class Record_MB(SimpleRecord):
    """
    A mailbox domain name.

    This is an experimental record type.
    """
    TYPE = MB
    fancybasename = 'MB'



class Record_MG(SimpleRecord):
    """
    A mail group member.

    This is an experimental record type.
    """
    TYPE = MG
    fancybasename = 'MG'



class Record_MR(SimpleRecord):
    """
    A mail rename domain name.

    This is an experimental record type.
    """
    TYPE = MR
    fancybasename = 'MR'



class Record_PTR(SimpleRecord):
    """
    A domain name pointer.
    """
    TYPE = PTR
    fancybasename = 'PTR'



class Record_DNAME(SimpleRecord):
    """
    A non-terminal DNS name redirection.

    This record type provides the capability to map an entire subtree of the
    DNS name space to another domain.  It differs from the CNAME record which
    maps a single node of the name space.

    @see: U{http://www.faqs.org/rfcs/rfc2672.html}
    @see: U{http://www.faqs.org/rfcs/rfc3363.html}
    """
    TYPE = DNAME
    fancybasename = 'DNAME'



@implementer(IEncodable, IRecord)
class Record_A(tputil.FancyEqMixin):
    """
    An IPv4 host address.

    @type address: C{str}
    @ivar address: The packed network-order representation of the IPv4 address
        associated with this record.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.
    """
    compareAttributes = ('address', 'ttl')

    TYPE = A
    address = None

    def __init__(self, address='0.0.0.0', ttl=None):
        address = socket.inet_aton(address)
        self.address = address
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        strio.write(self.address)


    def decode(self, strio, length = None):
        self.address = readPrecisely(strio, 4)


    def __hash__(self):
        return hash(self.address)


    def __str__(self):
        return '<A address=%s ttl=%s>' % (self.dottedQuad(), self.ttl)
    __repr__ = __str__


    def dottedQuad(self):
        return socket.inet_ntoa(self.address)



@implementer(IEncodable, IRecord)
class Record_SOA(tputil.FancyEqMixin, tputil.FancyStrMixin):
    """
    Marks the start of a zone of authority.

    This record describes parameters which are shared by all records within a
    particular zone.

    @type mname: L{Name}
    @ivar mname: The domain-name of the name server that was the original or
        primary source of data for this zone.

    @type rname: L{Name}
    @ivar rname: A domain-name which specifies the mailbox of the person
        responsible for this zone.

    @type serial: C{int}
    @ivar serial: The unsigned 32 bit version number of the original copy of
        the zone.  Zone transfers preserve this value.  This value wraps and
        should be compared using sequence space arithmetic.

    @type refresh: C{int}
    @ivar refresh: A 32 bit time interval before the zone should be refreshed.

    @type minimum: C{int}
    @ivar minimum: The unsigned 32 bit minimum TTL field that should be
        exported with any RR from this zone.

    @type expire: C{int}
    @ivar expire: A 32 bit time value that specifies the upper limit on the
        time interval that can elapse before the zone is no longer
        authoritative.

    @type retry: C{int}
    @ivar retry: A 32 bit time interval that should elapse before a failed
        refresh should be retried.

    @type ttl: C{int}
    @ivar ttl: The default TTL to use for records served from this zone.
    """
    fancybasename = 'SOA'
    compareAttributes = ('serial', 'mname', 'rname', 'refresh', 'expire', 'retry', 'minimum', 'ttl')
    showAttributes = (('mname', 'mname', '%s'), ('rname', 'rname', '%s'), 'serial', 'refresh', 'retry', 'expire', 'minimum', 'ttl')

    TYPE = SOA

    def __init__(self, mname=b'', rname=b'', serial=0, refresh=0, retry=0,
                 expire=0, minimum=0, ttl=None):
        self.mname, self.rname = Name(mname), Name(rname)
        self.serial, self.refresh = str2time(serial), str2time(refresh)
        self.minimum, self.expire = str2time(minimum), str2time(expire)
        self.retry = str2time(retry)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        self.mname.encode(strio, compDict)
        self.rname.encode(strio, compDict)
        strio.write(
            struct.pack(
                '!LlllL',
                self.serial, self.refresh, self.retry, self.expire,
                self.minimum
            )
        )


    def decode(self, strio, length = None):
        self.mname, self.rname = Name(), Name()
        self.mname.decode(strio)
        self.rname.decode(strio)
        r = struct.unpack('!LlllL', readPrecisely(strio, 20))
        self.serial, self.refresh, self.retry, self.expire, self.minimum = r


    def __hash__(self):
        return hash((
            self.serial, self.mname, self.rname,
            self.refresh, self.expire, self.retry
        ))



@implementer(IEncodable, IRecord)
class Record_NULL(tputil.FancyStrMixin, tputil.FancyEqMixin):
    """
    A null record.

    This is an experimental record type.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.
    """
    fancybasename = 'NULL'
    showAttributes = (('payload', _nicebytes), 'ttl')
    compareAttributes = ('payload', 'ttl')

    TYPE = NULL

    def __init__(self, payload=None, ttl=None):
        self.payload = payload
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        strio.write(self.payload)


    def decode(self, strio, length = None):
        self.payload = readPrecisely(strio, length)


    def __hash__(self):
        return hash(self.payload)



@implementer(IEncodable, IRecord)
class Record_WKS(tputil.FancyEqMixin, tputil.FancyStrMixin):
    """
    A well known service description.

    This record type is obsolete.  See L{Record_SRV}.

    @type address: C{str}
    @ivar address: The packed network-order representation of the IPv4 address
        associated with this record.

    @type protocol: C{int}
    @ivar protocol: The 8 bit IP protocol number for which this service map is
        relevant.

    @type map: C{str}
    @ivar map: A bitvector indicating the services available at the specified
        address.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.
    """
    fancybasename = "WKS"
    compareAttributes = ('address', 'protocol', 'map', 'ttl')
    showAttributes = [('_address', 'address', '%s'), 'protocol', 'ttl']

    TYPE = WKS

    _address = property(lambda self: socket.inet_ntoa(self.address))

    def __init__(self, address='0.0.0.0', protocol=0, map='', ttl=None):
        self.address = socket.inet_aton(address)
        self.protocol, self.map = protocol, map
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        strio.write(self.address)
        strio.write(struct.pack('!B', self.protocol))
        strio.write(self.map)


    def decode(self, strio, length = None):
        self.address = readPrecisely(strio, 4)
        self.protocol = struct.unpack('!B', readPrecisely(strio, 1))[0]
        self.map = readPrecisely(strio, length - 5)


    def __hash__(self):
        return hash((self.address, self.protocol, self.map))



@implementer(IEncodable, IRecord)
class Record_AAAA(tputil.FancyEqMixin, tputil.FancyStrMixin):
    """
    An IPv6 host address.

    @type address: C{str}
    @ivar address: The packed network-order representation of the IPv6 address
        associated with this record.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.

    @see: U{http://www.faqs.org/rfcs/rfc1886.html}
    """
    TYPE = AAAA

    fancybasename = 'AAAA'
    showAttributes = (('_address', 'address', '%s'), 'ttl')
    compareAttributes = ('address', 'ttl')

    _address = property(lambda self: socket.inet_ntop(AF_INET6, self.address))

    def __init__(self, address='::', ttl=None):
        self.address = socket.inet_pton(AF_INET6, address)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        strio.write(self.address)


    def decode(self, strio, length = None):
        self.address = readPrecisely(strio, 16)


    def __hash__(self):
        return hash(self.address)



@implementer(IEncodable, IRecord)
class Record_A6(tputil.FancyStrMixin, tputil.FancyEqMixin):
    """
    An IPv6 address.

    This is an experimental record type.

    @type prefixLen: C{int}
    @ivar prefixLen: The length of the suffix.

    @type suffix: C{str}
    @ivar suffix: An IPv6 address suffix in network order.

    @type prefix: L{Name}
    @ivar prefix: If specified, a name which will be used as a prefix for other
        A6 records.

    @type bytes: C{int}
    @ivar bytes: The length of the prefix.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.

    @see: U{http://www.faqs.org/rfcs/rfc2874.html}
    @see: U{http://www.faqs.org/rfcs/rfc3363.html}
    @see: U{http://www.faqs.org/rfcs/rfc3364.html}
    """
    TYPE = A6

    fancybasename = 'A6'
    showAttributes = (('_suffix', 'suffix', '%s'), ('prefix', 'prefix', '%s'), 'ttl')
    compareAttributes = ('prefixLen', 'prefix', 'suffix', 'ttl')

    _suffix = property(lambda self: socket.inet_ntop(AF_INET6, self.suffix))

    def __init__(self, prefixLen=0, suffix='::', prefix=b'', ttl=None):
        self.prefixLen = prefixLen
        self.suffix = socket.inet_pton(AF_INET6, suffix)
        self.prefix = Name(prefix)
        self.bytes = int((128 - self.prefixLen) / 8.0)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        strio.write(struct.pack('!B', self.prefixLen))
        if self.bytes:
            strio.write(self.suffix[-self.bytes:])
        if self.prefixLen:
            # This may not be compressed
            self.prefix.encode(strio, None)


    def decode(self, strio, length = None):
        self.prefixLen = struct.unpack('!B', readPrecisely(strio, 1))[0]
        self.bytes = int((128 - self.prefixLen) / 8.0)
        if self.bytes:
            self.suffix = b'\x00' * (16 - self.bytes) + readPrecisely(strio, self.bytes)
        if self.prefixLen:
            self.prefix.decode(strio)


    def __eq__(self, other):
        if isinstance(other, Record_A6):
            return (self.prefixLen == other.prefixLen and
                    self.suffix[-self.bytes:] == other.suffix[-self.bytes:] and
                    self.prefix == other.prefix and
                    self.ttl == other.ttl)
        return NotImplemented


    def __hash__(self):
        return hash((self.prefixLen, self.suffix[-self.bytes:], self.prefix))


    def __str__(self):
        return '<A6 %s %s (%d) ttl=%s>' % (
            self.prefix,
            socket.inet_ntop(AF_INET6, self.suffix),
            self.prefixLen, self.ttl
        )



@implementer(IEncodable, IRecord)
class Record_SRV(tputil.FancyEqMixin, tputil.FancyStrMixin):
    """
    The location of the server(s) for a specific protocol and domain.

    This is an experimental record type.

    @type priority: C{int}
    @ivar priority: The priority of this target host.  A client MUST attempt to
        contact the target host with the lowest-numbered priority it can reach;
        target hosts with the same priority SHOULD be tried in an order defined
        by the weight field.

    @type weight: C{int}
    @ivar weight: Specifies a relative weight for entries with the same
        priority. Larger weights SHOULD be given a proportionately higher
        probability of being selected.

    @type port: C{int}
    @ivar port: The port on this target host of this service.

    @type target: L{Name}
    @ivar target: The domain name of the target host.  There MUST be one or
        more address records for this name, the name MUST NOT be an alias (in
        the sense of RFC 1034 or RFC 2181).  Implementors are urged, but not
        required, to return the address record(s) in the Additional Data
        section.  Unless and until permitted by future standards action, name
        compression is not to be used for this field.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.

    @see: U{http://www.faqs.org/rfcs/rfc2782.html}
    """
    TYPE = SRV

    fancybasename = 'SRV'
    compareAttributes = ('priority', 'weight', 'target', 'port', 'ttl')
    showAttributes = ('priority', 'weight', ('target', 'target', '%s'), 'port', 'ttl')

    def __init__(self, priority=0, weight=0, port=0, target=b'', ttl=None):
        self.priority = int(priority)
        self.weight = int(weight)
        self.port = int(port)
        self.target = Name(target)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        strio.write(struct.pack('!HHH', self.priority, self.weight, self.port))
        # This can't be compressed
        self.target.encode(strio, None)


    def decode(self, strio, length = None):
        r = struct.unpack('!HHH', readPrecisely(strio, struct.calcsize('!HHH')))
        self.priority, self.weight, self.port = r
        self.target = Name()
        self.target.decode(strio)


    def __hash__(self):
        return hash((self.priority, self.weight, self.port, self.target))



@implementer(IEncodable, IRecord)
class Record_NAPTR(tputil.FancyEqMixin, tputil.FancyStrMixin):
    """
    The location of the server(s) for a specific protocol and domain.

    @type order: C{int}
    @ivar order: An integer specifying the order in which the NAPTR records
        MUST be processed to ensure the correct ordering of rules.  Low numbers
        are processed before high numbers.

    @type preference: C{int}
    @ivar preference: An integer that specifies the order in which NAPTR
        records with equal "order" values SHOULD be processed, low numbers
        being processed before high numbers.

    @type flag: L{Charstr}
    @ivar flag: A <character-string> containing flags to control aspects of the
        rewriting and interpretation of the fields in the record.  Flags
        are single characters from the set [A-Z0-9].  The case of the alphabetic
        characters is not significant.

        At this time only four flags, "S", "A", "U", and "P", are defined.

    @type service: L{Charstr}
    @ivar service: Specifies the service(s) available down this rewrite path.
        It may also specify the particular protocol that is used to talk with a
        service.  A protocol MUST be specified if the flags field states that
        the NAPTR is terminal.

    @type regexp: L{Charstr}
    @ivar regexp: A STRING containing a substitution expression that is applied
        to the original string held by the client in order to construct the
        next domain name to lookup.

    @type replacement: L{Name}
    @ivar replacement: The next NAME to query for NAPTR, SRV, or address
        records depending on the value of the flags field.  This MUST be a
        fully qualified domain-name.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.

    @see: U{http://www.faqs.org/rfcs/rfc2915.html}
    """
    TYPE = NAPTR

    compareAttributes = ('order', 'preference', 'flags', 'service', 'regexp',
                         'replacement')
    fancybasename = 'NAPTR'

    showAttributes = ('order', 'preference', ('flags', 'flags', '%s'),
                      ('service', 'service', '%s'), ('regexp', 'regexp', '%s'),
                      ('replacement', 'replacement', '%s'), 'ttl')

    def __init__(self, order=0, preference=0, flags=b'', service=b'', regexp=b'',
                 replacement=b'', ttl=None):
        self.order = int(order)
        self.preference = int(preference)
        self.flags = Charstr(flags)
        self.service = Charstr(service)
        self.regexp = Charstr(regexp)
        self.replacement = Name(replacement)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict=None):
        strio.write(struct.pack('!HH', self.order, self.preference))
        # This can't be compressed
        self.flags.encode(strio, None)
        self.service.encode(strio, None)
        self.regexp.encode(strio, None)
        self.replacement.encode(strio, None)


    def decode(self, strio, length=None):
        r = struct.unpack('!HH', readPrecisely(strio, struct.calcsize('!HH')))
        self.order, self.preference = r
        self.flags = Charstr()
        self.service = Charstr()
        self.regexp = Charstr()
        self.replacement = Name()
        self.flags.decode(strio)
        self.service.decode(strio)
        self.regexp.decode(strio)
        self.replacement.decode(strio)


    def __hash__(self):
        return hash((
            self.order, self.preference, self.flags,
            self.service, self.regexp, self.replacement))



@implementer(IEncodable, IRecord)
class Record_AFSDB(tputil.FancyStrMixin, tputil.FancyEqMixin):
    """
    Map from a domain name to the name of an AFS cell database server.

    @type subtype: C{int}
    @ivar subtype: In the case of subtype 1, the host has an AFS version 3.0
        Volume Location Server for the named AFS cell.  In the case of subtype
        2, the host has an authenticated name server holding the cell-root
        directory node for the named DCE/NCA cell.

    @type hostname: L{Name}
    @ivar hostname: The domain name of a host that has a server for the cell
        named by this record.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.

    @see: U{http://www.faqs.org/rfcs/rfc1183.html}
    """
    TYPE = AFSDB

    fancybasename = 'AFSDB'
    compareAttributes = ('subtype', 'hostname', 'ttl')
    showAttributes = ('subtype', ('hostname', 'hostname', '%s'), 'ttl')

    def __init__(self, subtype=0, hostname=b'', ttl=None):
        self.subtype = int(subtype)
        self.hostname = Name(hostname)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        strio.write(struct.pack('!H', self.subtype))
        self.hostname.encode(strio, compDict)


    def decode(self, strio, length = None):
        r = struct.unpack('!H', readPrecisely(strio, struct.calcsize('!H')))
        self.subtype, = r
        self.hostname.decode(strio)


    def __hash__(self):
        return hash((self.subtype, self.hostname))



@implementer(IEncodable, IRecord)
class Record_RP(tputil.FancyEqMixin, tputil.FancyStrMixin):
    """
    The responsible person for a domain.

    @type mbox: L{Name}
    @ivar mbox: A domain name that specifies the mailbox for the responsible
        person.

    @type txt: L{Name}
    @ivar txt: A domain name for which TXT RR's exist (indirection through
        which allows information sharing about the contents of this RP record).

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.

    @see: U{http://www.faqs.org/rfcs/rfc1183.html}
    """
    TYPE = RP

    fancybasename = 'RP'
    compareAttributes = ('mbox', 'txt', 'ttl')
    showAttributes = (('mbox', 'mbox', '%s'), ('txt', 'txt', '%s'), 'ttl')

    def __init__(self, mbox=b'', txt=b'', ttl=None):
        self.mbox = Name(mbox)
        self.txt = Name(txt)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        self.mbox.encode(strio, compDict)
        self.txt.encode(strio, compDict)


    def decode(self, strio, length = None):
        self.mbox = Name()
        self.txt = Name()
        self.mbox.decode(strio)
        self.txt.decode(strio)


    def __hash__(self):
        return hash((self.mbox, self.txt))



@implementer(IEncodable, IRecord)
class Record_HINFO(tputil.FancyStrMixin, tputil.FancyEqMixin):
    """
    Host information.

    @type cpu: C{str}
    @ivar cpu: Specifies the CPU type.

    @type os: C{str}
    @ivar os: Specifies the OS.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.
    """
    TYPE = HINFO

    fancybasename = 'HINFO'
    showAttributes = (('cpu', _nicebytes), ('os', _nicebytes), 'ttl')
    compareAttributes = ('cpu', 'os', 'ttl')

    def __init__(self, cpu='', os='', ttl=None):
        self.cpu, self.os = cpu, os
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        strio.write(struct.pack('!B', len(self.cpu)) + self.cpu)
        strio.write(struct.pack('!B', len(self.os)) + self.os)


    def decode(self, strio, length = None):
        cpu = struct.unpack('!B', readPrecisely(strio, 1))[0]
        self.cpu = readPrecisely(strio, cpu)
        os = struct.unpack('!B', readPrecisely(strio, 1))[0]
        self.os = readPrecisely(strio, os)


    def __eq__(self, other):
        if isinstance(other, Record_HINFO):
            return (self.os.lower() == other.os.lower() and
                    self.cpu.lower() == other.cpu.lower() and
                    self.ttl == other.ttl)
        return NotImplemented


    def __hash__(self):
        return hash((self.os.lower(), self.cpu.lower()))



@implementer(IEncodable, IRecord)
class Record_MINFO(tputil.FancyEqMixin, tputil.FancyStrMixin):
    """
    Mailbox or mail list information.

    This is an experimental record type.

    @type rmailbx: L{Name}
    @ivar rmailbx: A domain-name which specifies a mailbox which is responsible
        for the mailing list or mailbox.  If this domain name names the root,
        the owner of the MINFO RR is responsible for itself.

    @type emailbx: L{Name}
    @ivar emailbx: A domain-name which specifies a mailbox which is to receive
        error messages related to the mailing list or mailbox specified by the
        owner of the MINFO record.  If this domain name names the root, errors
        should be returned to the sender of the message.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.
    """
    TYPE = MINFO

    rmailbx = None
    emailbx = None

    fancybasename = 'MINFO'
    compareAttributes = ('rmailbx', 'emailbx', 'ttl')
    showAttributes = (('rmailbx', 'responsibility', '%s'),
                      ('emailbx', 'errors', '%s'),
                      'ttl')

    def __init__(self, rmailbx=b'', emailbx=b'', ttl=None):
        self.rmailbx, self.emailbx = Name(rmailbx), Name(emailbx)
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict = None):
        self.rmailbx.encode(strio, compDict)
        self.emailbx.encode(strio, compDict)


    def decode(self, strio, length = None):
        self.rmailbx, self.emailbx = Name(), Name()
        self.rmailbx.decode(strio)
        self.emailbx.decode(strio)


    def __hash__(self):
        return hash((self.rmailbx, self.emailbx))



@implementer(IEncodable, IRecord)
class Record_MX(tputil.FancyStrMixin, tputil.FancyEqMixin):
    """
    Mail exchange.

    @type preference: C{int}
    @ivar preference: Specifies the preference given to this RR among others at
        the same owner.  Lower values are preferred.

    @type name: L{Name}
    @ivar name: A domain-name which specifies a host willing to act as a mail
        exchange.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be
        cached.
    """
    TYPE = MX

    fancybasename = 'MX'
    compareAttributes = ('preference', 'name', 'ttl')
    showAttributes = ('preference', ('name', 'name', '%s'), 'ttl')

    def __init__(self, preference=0, name=b'', ttl=None, **kwargs):
        self.preference, self.name = int(preference), Name(kwargs.get('exchange', name))
        self.ttl = str2time(ttl)

    def encode(self, strio, compDict = None):
        strio.write(struct.pack('!H', self.preference))
        self.name.encode(strio, compDict)


    def decode(self, strio, length = None):
        self.preference = struct.unpack('!H', readPrecisely(strio, 2))[0]
        self.name = Name()
        self.name.decode(strio)

    def __hash__(self):
        return hash((self.preference, self.name))



@implementer(IEncodable, IRecord)
class Record_TXT(tputil.FancyEqMixin, tputil.FancyStrMixin):
    """
    Freeform text.

    @type data: C{list} of C{bytes}
    @ivar data: Freeform text which makes up this record.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be cached.
    """
    TYPE = TXT

    fancybasename = 'TXT'
    showAttributes = (('data', _nicebyteslist), 'ttl')
    compareAttributes = ('data', 'ttl')

    def __init__(self, *data, **kw):
        self.data = list(data)
        # arg man python sucks so bad
        self.ttl = str2time(kw.get('ttl', None))


    def encode(self, strio, compDict=None):
        for d in self.data:
            strio.write(struct.pack('!B', len(d)) + d)


    def decode(self, strio, length=None):
        soFar = 0
        self.data = []
        while soFar < length:
            L = struct.unpack('!B', readPrecisely(strio, 1))[0]
            self.data.append(readPrecisely(strio, L))
            soFar += L + 1
        if soFar != length:
            log.msg(
                "Decoded %d bytes in %s record, but rdlength is %d" % (
                    soFar, self.fancybasename, length
                )
            )


    def __hash__(self):
        return hash(tuple(self.data))



@implementer(IEncodable, IRecord)
class UnknownRecord(tputil.FancyEqMixin, tputil.FancyStrMixin, object):
    """
    Encapsulate the wire data for unknown record types so that they can
    pass through the system unchanged.

    @type data: C{bytes}
    @ivar data: Wire data which makes up this record.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be cached.

    @since: 11.1
    """
    fancybasename = 'UNKNOWN'
    compareAttributes = ('data', 'ttl')
    showAttributes = (('data', _nicebytes), 'ttl')

    def __init__(self, data=b'', ttl=None):
        self.data = data
        self.ttl = str2time(ttl)


    def encode(self, strio, compDict=None):
        """
        Write the raw bytes corresponding to this record's payload to the
        stream.
        """
        strio.write(self.data)


    def decode(self, strio, length=None):
        """
        Load the bytes which are part of this record from the stream and store
        them unparsed and unmodified.
        """
        if length is None:
            raise Exception('must know length for unknown record types')
        self.data = readPrecisely(strio, length)


    def __hash__(self):
        return hash((self.data, self.ttl))



class Record_SPF(Record_TXT):
    """
    Structurally, freeform text. Semantically, a policy definition, formatted
    as defined in U{rfc 4408<http://www.faqs.org/rfcs/rfc4408.html>}.

    @type data: C{list} of C{str}
    @ivar data: Freeform text which makes up this record.

    @type ttl: C{int}
    @ivar ttl: The maximum number of seconds which this record should be cached.
    """
    TYPE = SPF
    fancybasename = 'SPF'



class Message:
    """
    L{Message} contains all the information represented by a single
    DNS request or response.

    @ivar id: See L{__init__}
    @ivar answer: See L{__init__}
    @ivar opCode: See L{__init__}
    @ivar recDes: See L{__init__}
    @ivar recAv: See L{__init__}
    @ivar auth: See L{__init__}
    @ivar rCode: See L{__init__}
    @ivar trunc: See L{__init__}
    @ivar maxSize: See L{__init__}
    @ivar authenticData: See L{__init__}
    @ivar checkingDisabled: See L{__init__}

    @ivar queries: The queries which are being asked of or answered by
        DNS server.
    @type queries: L{list} of L{Query}

    @ivar answers: Records containing the answers to C{queries} if
        this is a response message.
    @type answers: L{list} of L{RRHeader}

    @ivar authority: Records containing information about the
        authoritative DNS servers for the names in C{queries}.
    @type authority: L{list} of L{RRHeader}

    @ivar additional: Records containing IP addresses of host names
        in C{answers} and C{authority}.
    @type additional: L{list} of L{RRHeader}
    """
    headerFmt = "!H2B4H"
    headerSize = struct.calcsize(headerFmt)

    # Question, answer, additional, and nameserver lists
    queries = answers = add = ns = None

    def __init__(self, id=0, answer=0, opCode=0, recDes=0, recAv=0,
                       auth=0, rCode=OK, trunc=0, maxSize=512,
                       authenticData=0, checkingDisabled=0):
        """
        @param id: A 16 bit identifier assigned by the program that
            generates any kind of query.  This identifier is copied to
            the corresponding reply and can be used by the requester
            to match up replies to outstanding queries.
        @type id: L{int}

        @param answer: A one bit field that specifies whether this
            message is a query (0), or a response (1).
        @type answer: L{int}

        @param opCode: A four bit field that specifies kind of query in
            this message.  This value is set by the originator of a query
            and copied into the response.
        @type opCode: L{int}

        @param recDes: Recursion Desired - this bit may be set in a
            query and is copied into the response.  If RD is set, it
            directs the name server to pursue the query recursively.
            Recursive query support is optional.
        @type recDes: L{int}

        @param recAv: Recursion Available - this bit is set or cleared
            in a response and denotes whether recursive query support
            is available in the name server.
        @type recAv: L{int}

        @param auth: Authoritative Answer - this bit is valid in
            responses and specifies that the responding name server
            is an authority for the domain name in question section.
        @type auth: L{int}

        @ivar rCode: A response code, used to indicate success or failure in a
            message which is a response from a server to a client request.
        @type rCode: C{0 <= int < 16}

        @param trunc: A flag indicating that this message was
            truncated due to length greater than that permitted on the
            transmission channel.
        @type trunc: L{int}

        @param maxSize: The requestor's UDP payload size is the number
            of octets of the largest UDP payload that can be
            reassembled and delivered in the requestor's network
            stack.
        @type maxSize: L{int}

        @param authenticData: A flag indicating in a response that all
            the data included in the answer and authority portion of
            the response has been authenticated by the server
            according to the policies of that server.
            See U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}.
        @type authenticData: L{int}

        @param checkingDisabled: A flag indicating in a query that
            pending (non-authenticated) data is acceptable to the
            resolver sending the query.
            See U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}.
        @type authenticData: L{int}
        """
        self.maxSize = maxSize
        self.id = id
        self.answer = answer
        self.opCode = opCode
        self.auth = auth
        self.trunc = trunc
        self.recDes = recDes
        self.recAv = recAv
        self.rCode = rCode
        self.authenticData = authenticData
        self.checkingDisabled = checkingDisabled

        self.queries = []
        self.answers = []
        self.authority = []
        self.additional = []


    def addQuery(self, name, type=ALL_RECORDS, cls=IN):
        """
        Add another query to this Message.

        @type name: C{bytes}
        @param name: The name to query.

        @type type: C{int}
        @param type: Query type

        @type cls: C{int}
        @param cls: Query class
        """
        self.queries.append(Query(name, type, cls))


    def encode(self, strio):
        compDict = {}
        body_tmp = BytesIO()
        for q in self.queries:
            q.encode(body_tmp, compDict)
        for q in self.answers:
            q.encode(body_tmp, compDict)
        for q in self.authority:
            q.encode(body_tmp, compDict)
        for q in self.additional:
            q.encode(body_tmp, compDict)
        body = body_tmp.getvalue()
        size = len(body) + self.headerSize
        if self.maxSize and size > self.maxSize:
            self.trunc = 1
            body = body[:self.maxSize - self.headerSize]
        byte3 = (( ( self.answer & 1 ) << 7 )
                 | ((self.opCode & 0xf ) << 3 )
                 | ((self.auth & 1 ) << 2 )
                 | ((self.trunc & 1 ) << 1 )
                 | ( self.recDes & 1 ) )
        byte4 = ( ( (self.recAv & 1 ) << 7 )
                  | ((self.authenticData & 1) << 5)
                  | ((self.checkingDisabled & 1) << 4)
                  | (self.rCode & 0xf ) )

        strio.write(struct.pack(self.headerFmt, self.id, byte3, byte4,
                                len(self.queries), len(self.answers),
                                len(self.authority), len(self.additional)))
        strio.write(body)


    def decode(self, strio, length=None):
        self.maxSize = 0
        header = readPrecisely(strio, self.headerSize)
        r = struct.unpack(self.headerFmt, header)
        self.id, byte3, byte4, nqueries, nans, nns, nadd = r
        self.answer = ( byte3 >> 7 ) & 1
        self.opCode = ( byte3 >> 3 ) & 0xf
        self.auth = ( byte3 >> 2 ) & 1
        self.trunc = ( byte3 >> 1 ) & 1
        self.recDes = byte3 & 1
        self.recAv = ( byte4 >> 7 ) & 1
        self.authenticData = ( byte4 >> 5 ) & 1
        self.checkingDisabled = ( byte4 >> 4 ) & 1
        self.rCode = byte4 & 0xf

        self.queries = []
        for i in range(nqueries):
            q = Query()
            try:
                q.decode(strio)
            except EOFError:
                return
            self.queries.append(q)

        items = (
            (self.answers, nans),
            (self.authority, nns),
            (self.additional, nadd))

        for (l, n) in items:
            self.parseRecords(l, n, strio)


    def parseRecords(self, list, num, strio):
        for i in range(num):
            header = RRHeader(auth=self.auth)
            try:
                header.decode(strio)
            except EOFError:
                return
            t = self.lookupRecordType(header.type)
            if not t:
                continue
            header.payload = t(ttl=header.ttl)
            try:
                header.payload.decode(strio, header.rdlength)
            except EOFError:
                return
            list.append(header)


    # Create a mapping from record types to their corresponding Record_*
    # classes.  This relies on the global state which has been created so
    # far in initializing this module (so don't define Record classes after
    # this).
    _recordTypes = {}
    for name in globals():
        if name.startswith('Record_'):
            _recordTypes[globals()[name].TYPE] = globals()[name]

    # Clear the iteration variable out of the class namespace so it
    # doesn't become an attribute.
    del name


    def lookupRecordType(self, type):
        """
        Retrieve the L{IRecord} implementation for the given record type.

        @param type: A record type, such as L{A} or L{NS}.
        @type type: C{int}

        @return: An object which implements L{IRecord} or C{None} if none
            can be found for the given type.
        @rtype: L{types.ClassType}
        """
        return self._recordTypes.get(type, UnknownRecord)


    def toStr(self):
        """
        Encode this L{Message} into a byte string in the format described by RFC
        1035.

        @rtype: C{bytes}
        """
        strio = BytesIO()
        self.encode(strio)
        return strio.getvalue()


    def fromStr(self, str):
        """
        Decode a byte string in the format described by RFC 1035 into this
        L{Message}.

        @param str: L{bytes}
        """
        strio = BytesIO(str)
        self.decode(strio)



class DNSMixin(object):
    """
    DNS protocol mixin shared by UDP and TCP implementations.

    @ivar _reactor: A L{IReactorTime} and L{IReactorUDP} provider which will
        be used to issue DNS queries and manage request timeouts.
    """
    id = None
    liveMessages = None

    def __init__(self, controller, reactor=None):
        self.controller = controller
        self.id = random.randrange(2 ** 10, 2 ** 15)
        if reactor is None:
            from twisted.internet import reactor
        self._reactor = reactor


    def pickID(self):
        """
        Return a unique ID for queries.
        """
        while True:
            id = randomSource()
            if id not in self.liveMessages:
                return id


    def callLater(self, period, func, *args):
        """
        Wrapper around reactor.callLater, mainly for test purpose.
        """
        return self._reactor.callLater(period, func, *args)


    def _query(self, queries, timeout, id, writeMessage):
        """
        Send out a message with the given queries.

        @type queries: C{list} of C{Query} instances
        @param queries: The queries to transmit

        @type timeout: C{int} or C{float}
        @param timeout: How long to wait before giving up

        @type id: C{int}
        @param id: Unique key for this request

        @type writeMessage: C{callable}
        @param writeMessage: One-parameter callback which writes the message

        @rtype: C{Deferred}
        @return: a C{Deferred} which will be fired with the result of the
            query, or errbacked with any errors that could happen (exceptions
            during writing of the query, timeout errors, ...).
        """
        m = Message(id, recDes=1)
        m.queries = queries

        try:
            writeMessage(m)
        except:
            return defer.fail()

        resultDeferred = defer.Deferred()
        cancelCall = self.callLater(timeout, self._clearFailed, resultDeferred, id)
        self.liveMessages[id] = (resultDeferred, cancelCall)

        return resultDeferred

    def _clearFailed(self, deferred, id):
        """
        Clean the Deferred after a timeout.
        """
        try:
            del self.liveMessages[id]
        except KeyError:
            pass
        deferred.errback(failure.Failure(DNSQueryTimeoutError(id)))


class DNSDatagramProtocol(DNSMixin, protocol.DatagramProtocol):
    """
    DNS protocol over UDP.
    """
    resends = None

    def stopProtocol(self):
        """
        Stop protocol: reset state variables.
        """
        self.liveMessages = {}
        self.resends = {}
        self.transport = None

    def startProtocol(self):
        """
        Upon start, reset internal state.
        """
        self.liveMessages = {}
        self.resends = {}

    def writeMessage(self, message, address):
        """
        Send a message holding DNS queries.

        @type message: L{Message}
        """
        self.transport.write(message.toStr(), address)

    def startListening(self):
        self._reactor.listenUDP(0, self, maxPacketSize=512)

    def datagramReceived(self, data, addr):
        """
        Read a datagram, extract the message in it and trigger the associated
        Deferred.
        """
        m = Message()
        try:
            m.fromStr(data)
        except EOFError:
            log.msg("Truncated packet (%d bytes) from %s" % (len(data), addr))
            return
        except:
            # Nothing should trigger this, but since we're potentially
            # invoking a lot of different decoding methods, we might as well
            # be extra cautious.  Anything that triggers this is itself
            # buggy.
            log.err(failure.Failure(), "Unexpected decoding error")
            return

        if m.id in self.liveMessages:
            d, canceller = self.liveMessages[m.id]
            del self.liveMessages[m.id]
            canceller.cancel()
            # XXX we shouldn't need this hack of catching exception on callback()
            try:
                d.callback(m)
            except:
                log.err()
        else:
            if m.id not in self.resends:
                self.controller.messageReceived(m, self, addr)


    def removeResend(self, id):
        """
        Mark message ID as no longer having duplication suppression.
        """
        try:
            del self.resends[id]
        except KeyError:
            pass

    def query(self, address, queries, timeout=10, id=None):
        """
        Send out a message with the given queries.

        @type address: C{tuple} of C{str} and C{int}
        @param address: The address to which to send the query

        @type queries: C{list} of C{Query} instances
        @param queries: The queries to transmit

        @rtype: C{Deferred}
        """
        if not self.transport:
            # XXX transport might not get created automatically, use callLater?
            try:
                self.startListening()
            except CannotListenError:
                return defer.fail()

        if id is None:
            id = self.pickID()
        else:
            self.resends[id] = 1

        def writeMessage(m):
            self.writeMessage(m, address)

        return self._query(queries, timeout, id, writeMessage)


class DNSProtocol(DNSMixin, protocol.Protocol):
    """
    DNS protocol over TCP.
    """
    length = None
    buffer = b''

    def writeMessage(self, message):
        """
        Send a message holding DNS queries.

        @type message: L{Message}
        """
        s = message.toStr()
        self.transport.write(struct.pack('!H', len(s)) + s)

    def connectionMade(self):
        """
        Connection is made: reset internal state, and notify the controller.
        """
        self.liveMessages = {}
        self.controller.connectionMade(self)


    def connectionLost(self, reason):
        """
        Notify the controller that this protocol is no longer
        connected.
        """
        self.controller.connectionLost(self)


    def dataReceived(self, data):
        self.buffer += data

        while self.buffer:
            if self.length is None and len(self.buffer) >= 2:
                self.length = struct.unpack('!H', self.buffer[:2])[0]
                self.buffer = self.buffer[2:]

            if len(self.buffer) >= self.length:
                myChunk = self.buffer[:self.length]
                m = Message()
                m.fromStr(myChunk)

                try:
                    d, canceller = self.liveMessages[m.id]
                except KeyError:
                    self.controller.messageReceived(m, self)
                else:
                    del self.liveMessages[m.id]
                    canceller.cancel()
                    # XXX we shouldn't need this hack
                    try:
                        d.callback(m)
                    except:
                        log.err()

                self.buffer = self.buffer[self.length:]
                self.length = None
            else:
                break


    def query(self, queries, timeout=60):
        """
        Send out a message with the given queries.

        @type queries: C{list} of C{Query} instances
        @param queries: The queries to transmit

        @rtype: C{Deferred}
        """
        id = self.pickID()
        return self._query(queries, timeout, id, self.writeMessage)

Youez - 2016 - github.com/yon3zu
LinuXploit