1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
|
"""
The tool to check the availability or syntax of domain, IP or URL.
::
██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝
██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗
██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝
██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝
Provides an interface for the query.
Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Special thanks:
https://pyfunceble.github.io/#/special-thanks
Contributors:
https://pyfunceble.github.io/#/contributors
Project link:
https://github.com/funilrys/PyFunceble
Project documentation:
https://docs.pyfunceble.com
Project homepage:
https://pyfunceble.github.io/
License:
::
Copyright 2017, 2018, 2019, 2020, 2022, 2023, 2024 Nissar Chababy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# pylint: disable=too-many-lines
import copy
import functools
import ipaddress
import random
import socket
import time
from typing import Dict, List, Optional, Union
import dns.exception
import dns.message
import dns.name
import dns.query
import dns.rdataclass
import dns.rdatatype
import PyFunceble.facility
import PyFunceble.storage
from PyFunceble.helpers.list import ListHelper
from PyFunceble.query.dns.nameserver import Nameservers
from PyFunceble.query.record.dns import DNSQueryToolRecord
class DNSQueryTool:
"""
Provides our query tool.
"""
# pylint: disable=too-many-public-methods
STD_PROTOCOL: str = "UDP"
STD_TIMEOUT: float = 5.0
STD_FOLLOW_NAMESERVER_ORDER: bool = True
STD_TRUST_SERVER: bool = False
STD_DELAY: float = 0.0
SUPPORTED_PROTOCOL: List[str] = ["TCP", "UDP", "HTTPS", "TLS"]
value2rdata_type: Dict[int, str] = {
x.value: x.name for x in dns.rdatatype.RdataType
}
rdata_type2value: Dict[str, int] = {
x.name: x.value for x in dns.rdatatype.RdataType
}
nameservers: Nameservers = Nameservers()
_query_record_type: int = dns.rdatatype.RdataType.ANY
_subject: Optional[str] = None
_follow_nameserver_order: bool = True
_preferred_protocol: str = "UDP"
_query_timeout: float = 5.0
_trust_server: bool = False
_delay: float = 0.0
dns_name: Optional[str] = None
query_message: Optional[dns.message.QueryMessage] = None
lookup_record: Optional[DNSQueryToolRecord] = None
def __init__(
self,
*,
nameservers: Optional[List[str]] = None,
follow_nameserver_order: Optional[bool] = None,
preferred_protocol: Optional[str] = None,
trust_server: Optional[bool] = None,
delay: Optional[bool] = None,
) -> None:
if nameservers is not None:
self.nameservers.set_nameservers(nameservers)
else: # pragma: no cover ## I'm not playing with system resolver.
self.nameservers.guess_and_set_nameservers()
if preferred_protocol is not None:
self.preferred_protocol = preferred_protocol
else:
self.guess_and_set_preferred_protocol()
if follow_nameserver_order is not None:
self.follow_nameserver_order = follow_nameserver_order
else:
self.guess_and_set_follow_nameserver_order()
if trust_server is not None:
self.trust_server = trust_server
else:
self.guess_and_set_trust_server()
if delay is not None:
self.delay = delay
else:
self.guess_and_set_delay()
def prepare_query(func): # pylint: disable=no-self-argument
"""
Prepare the query after running the decorated method.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs) # pylint: disable=not-callable
if self.subject and self.query_record_type:
self.dns_name = self.get_dns_name_from_subject_and_query_type()
if self.dns_name:
self.query_message = dns.message.make_query(
self.dns_name, self.query_record_type
)
else:
self.query_message = None
return result
return wrapper
def update_lookup_record(func): # pylint: disable=no-self-argument
"""
Ensures that a clean record is generated after the execution of
the decorated method.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs) # pylint: disable=not-callable
if self.lookup_record is None or self.subject != self.lookup_record.subject:
self.lookup_record = DNSQueryToolRecord()
self.lookup_record.subject = self.subject
if self.dns_name != self.lookup_record.dns_name:
self.lookup_record.dns_name = self.dns_name
if (
self.get_human_query_record_type()
!= self.lookup_record.query_record_type
):
self.lookup_record.query_record_type = (
self.get_human_query_record_type()
)
if (
self.follow_nameserver_order
!= self.lookup_record.follow_nameserver_order
):
self.lookup_record.follow_nameserver_order = (
self.follow_nameserver_order
)
if self.query_timeout != self.lookup_record.query_timeout:
self.lookup_record.query_timeout = self.query_timeout
if self.preferred_protocol != self.lookup_record.preferred_protocol:
self.lookup_record.preferred_protocol = self.preferred_protocol
return result
return wrapper
def ensure_subject_is_given(func): # pylint: disable=no-self-argument
"""
Ensures that the subject to work with is given before running the
decorated method.
:raise TypeError:
If :code:`self.subject` is not a :py:class:`str`.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not isinstance(self.subject, str):
raise TypeError(
f"<self.subject> should be {str}, {type(self.subject)} given."
)
return func(self, *args, **kwargs) # pylint: disable=not-callable
return wrapper
def update_lookup_record_response(func): # pylint: disable=no-self-argument
"""
Ensures that the response of the decorated method is set as response
in our record.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs) # pylint: disable=not-callable
if result != self.lookup_record.response:
self.lookup_record.response = result
return result
return wrapper
def ignore_if_query_message_is_missing(func): # pylint: disable=no-self-argument
"""
Ignores the call to the decorated method if the query message is
missing. Otherwise, return an empty list.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if self.query_message:
return func(self, *args, **kwargs) # pylint: disable=not-callable
return [] # pragma: no cover ## Safety
return wrapper
@ensure_subject_is_given
def get_dns_name_from_subject_and_query_type(self):
"""
Provides the dns name based on the current subject and query type.
"""
try:
if self.get_human_query_record_type().lower() == "ptr":
try:
return dns.name.from_text(
ipaddress.ip_address(self.subject).reverse_pointer
)
except ValueError:
return dns.name.from_text(self.subject)
return dns.name.from_text(self.subject)
except (
dns.name.LabelTooLong,
dns.name.EmptyLabel,
dns.name.BadEscape,
dns.name.NameTooLong,
):
return None
@property
def subject(self) -> Optional[str]:
"""
Provides the current state of the :code:`_subject` attribute.
"""
return self._subject
@subject.setter
@prepare_query
@update_lookup_record
def subject(self, value: str) -> None:
"""
Sets the subject to work with.
:param value:
The subject to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`str`.
:raise ValueError:
When the given :code:`value` is empty.
"""
if not isinstance(value, str):
raise TypeError(f"<value> should be {str}, {type(value)} given.")
if not value:
raise ValueError("<value> should not be empty.")
self._subject = value
def set_subject(self, value: str) -> "DNSQueryTool":
"""
Sets the subject to work with.
:param value:
The subject to set.
"""
self.subject = value
return self
def set_nameservers(
self, value: List[str]
) -> "DNSQueryTool": # pragma: no cover ## Underlying already tested.
"""
Sets the nameservers to work with.
:raise TypeError:
When the given :code:`value` is not a list of :py:class:`str`.
:raise ValueError:
When the given :code:`value` is empty.
"""
self.nameservers.set_nameservers(value)
@property
def follow_nameserver_order(self) -> bool:
"""
Provides the current state of the :code:`_follow_nameserver_order`
attribute.
"""
return self._follow_nameserver_order
@follow_nameserver_order.setter
@update_lookup_record
def follow_nameserver_order(self, value: bool) -> None:
"""
Updates the :code:`follow_nameserver_order` variable.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`bool`.
"""
if not isinstance(value, bool):
raise TypeError(f"<value> should be {bool}, {type(value)} given.")
self._follow_nameserver_order = value
def set_follow_nameserver_order(self, value: bool) -> "DNSQueryTool":
"""
Updates the :code:`follow_nameserver_order` variable.
:param value:
The value to set.
"""
self.follow_nameserver_order = value
return self
@property
def query_record_type(self) -> int:
"""
Provides the current state of the :code:`_query_record_type` attribute.
"""
return self._query_record_type
@query_record_type.setter
@prepare_query
@update_lookup_record
def query_record_type(self, value: Union[str, int]) -> None:
"""
Sets the DNS record type to query.
:param value:
The value to set. It can be the human version (e.g AAAA) or an
integer as registered in the :code:`value2rdata_type` attribute.
:raise TypeError:
When the given :code:`value` is not a :py:class:`str` nor
:py:class:`int`.
:raise ValueError:
When the given :code:`value` is unknown or unsupported.
"""
if not isinstance(value, (str, int)):
raise TypeError(f"<value> should be {int} or {str}, {type(value)} given.")
if value in self.rdata_type2value:
self._query_record_type = self.rdata_type2value[value]
elif value in self.value2rdata_type:
self._query_record_type = value
else:
raise ValueError(f"<value> ({value!r}) is unknown or unsupported.")
def set_query_record_type(self, value: Union[str, int]) -> "DNSQueryTool":
"""
Sets the DNS record type to query.
:param value:
The value to set. It can be the human version (e.g AAAA) or an
integer as registered in the :code:`value2rdata_type` attribute.
"""
self.query_record_type = value
return self
def get_human_query_record_type(self) -> str:
"""
Provides the currently set record type.
"""
return self.value2rdata_type[self.query_record_type]
@property
def query_timeout(self) -> float:
"""
Provides the current state of the :code:`_query_timeout` attribute.
"""
return self._query_timeout
@query_timeout.setter
@update_lookup_record
def query_timeout(self, value: Union[int, float]) -> None:
"""
Sets the timeout to apply.
:param value:
The timeout to apply.
:raise TypeError:
When the given :code:`value` is not a :py:class:`float`
nor :py:class.`int`.
"""
if not isinstance(value, (float, int)):
raise TypeError(f"<value> should be {float} or {int}, {type(value)} given.")
self._query_timeout = float(value)
def set_timeout(self, value: Union[int, float]) -> "DNSQueryTool":
"""
Sets the timeout to apply.
:param value:
The timeout to apply.
"""
self.query_timeout = value
return self
@property
def trust_server(self) -> Optional[bool]:
"""
Provides the current state of the :code:`trust_server` attribute.
"""
return self._trust_server
@trust_server.setter
def trust_server(self, value: bool) -> None:
"""
Sets the value to apply.
:param value:
The value to apply.
:raise TypeError:
When the given :code:`value` is not a :py:class:`bool`.
"""
if not isinstance(value, bool):
raise TypeError(f"<value> should be {bool}, {type(value)} given.")
self._trust_server = value
def set_trust_server(self, value: bool) -> "DNSQueryTool":
"""
Sets the value to apply.
:param value:
The value to apply.
"""
self.trust_server = value
return self
def guess_and_set_timeout(self) -> "DNSQueryTool":
"""
Try to guess and set the timeout.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
if PyFunceble.storage.CONFIGURATION.lookup.timeout:
self.query_timeout = PyFunceble.storage.CONFIGURATION.lookup.timeout
else:
self.query_timeout = self.STD_TIMEOUT
else:
self.query_timeout = self.STD_TIMEOUT
return self
@property
def preferred_protocol(self) -> Optional[str]:
"""
Provides the current state of the :code:`_preferred_protocol` attribute.
"""
return self._preferred_protocol
@preferred_protocol.setter
def preferred_protocol(self, value: str) -> None:
"""
Sets the preferred protocol.
:param value:
The protocol to use.
:raise TypeError:
When the given :code:`value` is not a :py:class:`str`.
:raise ValueError:
When the given :code:`value` is unknown or unsupported.
"""
if not isinstance(value, str):
raise TypeError(f"<value> should be {str}, {type(value)} given.")
value = value.upper()
if value not in self.SUPPORTED_PROTOCOL:
raise ValueError(
f"<value> {value!r} is unknown or unsupported "
f"(supported: {self.SUPPORTED_PROTOCOL!r})."
)
self._preferred_protocol = self.nameservers.protocol = value
def set_preferred_protocol(self, value: str) -> "DNSQueryTool":
"""
Sets the preferred protocol.
:param value:
The protocol to use.
"""
self.preferred_protocol = value
return self
@property
def delay(self) -> float:
"""
Provides the current state of the :code:`_delay` attribute.
"""
return self._delay
@delay.setter
@update_lookup_record
def delay(self, value: Union[int, float]) -> None:
"""
Sets the delay to apply.
:param value:
The delay to apply.
:raise TypeError:
When the given :code:`value` is not a :py:class:`float`
nor :py:class.`int`.
:raise ValueError:
When the given :code:`value` is not a positive.
"""
if not isinstance(value, (float, int)):
raise TypeError(f"<value> should be {float} or {int}, {type(value)} given.")
if value < 0:
raise ValueError(f"<value> should be positive, {value} given.")
self._delay = float(value)
def set_delay(self, value: Union[int, float]) -> "DNSQueryTool":
"""
Sets the delay to apply.
:param value:
The delay to apply.
"""
self.delay = value
return self
def guess_and_set_preferred_protocol(self) -> "DNSQueryTool":
"""
Try to guess and set the preferred procol.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
if isinstance(PyFunceble.storage.CONFIGURATION.dns.protocol, str):
self.preferred_protocol = PyFunceble.storage.CONFIGURATION.dns.protocol
else:
self.preferred_protocol = self.STD_PROTOCOL
else:
self.preferred_protocol = self.STD_PROTOCOL
return self
def guess_and_set_follow_nameserver_order(self) -> "DNSQueryTool":
"""
Try to guess and authorize the mix of the nameserver before each
query.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
if isinstance(
PyFunceble.storage.CONFIGURATION.dns.follow_server_order, bool
):
self.follow_nameserver_order = (
PyFunceble.storage.CONFIGURATION.dns.follow_server_order
)
else:
self.follow_nameserver_order = self.STD_FOLLOW_NAMESERVER_ORDER
else:
self.follow_nameserver_order = self.STD_FOLLOW_NAMESERVER_ORDER
return self
def guess_and_set_trust_server(self) -> "DNSQueryTool":
"""
Try to guess and set the trust flag.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
if isinstance(PyFunceble.storage.CONFIGURATION.dns.trust_server, bool):
self.trust_server = PyFunceble.storage.CONFIGURATION.dns.trust_server
else:
self.trust_server = self.STD_TRUST_SERVER
else:
self.trust_server = self.STD_TRUST_SERVER
return self
def guess_and_set_delay(self) -> "DNSQueryTool":
"""
Try to guess and set the delay to apply.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
if PyFunceble.storage.CONFIGURATION.dns.delay:
self.delay = PyFunceble.storage.CONFIGURATION.dns.delay
else:
self.delay = self.STD_DELAY
else:
self.delay = self.STD_DELAY
def guess_all_settings(
self,
) -> "DNSQueryTool": # pragma: no cover ## Method themselves are more important
"""
Try to guess all settings.
"""
to_ignore = ["guess_all_settings"]
for method in dir(self):
if method in to_ignore or not method.startswith("guess_"):
continue
getattr(self, method)()
return self
def get_lookup_record(
self,
) -> Optional[DNSQueryToolRecord]:
"""
Provides the current query record.
"""
return self.lookup_record
def _get_result_from_response(
self, response: dns.message.Message
) -> List[str]: # pragma: no cover ## This just reads upstream result
"""
Given a response, we return the best possible result.
"""
result = []
rrset = response.get_rrset(
response.answer,
self.dns_name,
dns.rdataclass.RdataClass.IN,
self.query_record_type,
)
if rrset:
result.extend([x.to_text() for x in rrset])
PyFunceble.facility.Logger.debug("Result from response:\r%r", result)
return result
def _mix_order(
self, data: Union[dict, List[str]]
) -> Union[dict, List[str]]: # pragma: no cover ## Just a shuffle :-)
"""
Given a dataset, we mix its order.
"""
dataset = copy.deepcopy(data)
if not self.follow_nameserver_order:
if isinstance(dataset, list):
random.shuffle(dataset)
return dataset
if isinstance(dataset, dict):
temp = list(dataset.items())
random.shuffle(temp)
return dict(temp)
PyFunceble.facility.Logger.debug("Mixed data:\n%r", dataset)
return dataset
@ensure_subject_is_given
@ignore_if_query_message_is_missing
@update_lookup_record_response
def tcp(
self,
) -> Optional[List[str]]:
"""
Request the chosen record through the TCP protocol.
"""
self.lookup_record.used_protocol = "TCP"
result = []
for nameserver, port in self._mix_order(
self.nameservers.get_nameserver_ports()
).items():
PyFunceble.facility.Logger.debug(
"Started to query information of %r from %r", self.subject, nameserver
)
try:
response = dns.query.tcp(
self.query_message,
nameserver,
port=port,
timeout=self.query_timeout,
)
local_result = self._get_result_from_response(response)
if local_result:
result.extend(local_result)
self.lookup_record.nameserver = nameserver
self.lookup_record.port = port
PyFunceble.facility.Logger.debug(
"Successfully queried information of %r from %r.",
self.subject,
nameserver,
)
if not self.trust_server: # pragma: no cover: Per case.
break
if self.trust_server: # pragma: no cover: Per case.
break
except (dns.exception.Timeout, socket.error):
# Example: Resource temporarily unavailable.
pass
except dns.query.UnexpectedSource:
# Example: got a response from XXX instead of XXX.
pass
except dns.query.BadResponse:
# Example: A DNS query response does not respond to the question
# asked.
pass
except ValueError:
# Example: Input is malformed.
break
PyFunceble.facility.Logger.debug(
"Unsuccessfully queried information of %r from %r. Sleeping %fs.",
self.subject,
nameserver,
self.delay,
)
time.sleep(self.delay)
return ListHelper(result).remove_duplicates().subject
@ensure_subject_is_given
@ignore_if_query_message_is_missing
@update_lookup_record_response
def udp(
self,
) -> Optional[List[str]]:
"""
Request the chosen record through the UTP protocol.
"""
self.lookup_record.used_protocol = "UDP"
result = []
for nameserver, port in self._mix_order(
self.nameservers.get_nameserver_ports()
).items():
PyFunceble.facility.Logger.debug(
"Started to query information of %r from %r", self.subject, nameserver
)
try:
response = dns.query.udp(
self.query_message,
nameserver,
port=port,
timeout=self.query_timeout,
)
local_result = self._get_result_from_response(response)
if local_result:
result.extend(local_result)
self.lookup_record.nameserver = nameserver
self.lookup_record.port = port
PyFunceble.facility.Logger.debug(
"Successfully queried information of %r from %r.",
self.subject,
nameserver,
)
if not self.trust_server: # pragma: no cover: Per case.
break
if self.trust_server: # pragma: no cover: Per case.
break
except (dns.exception.Timeout, socket.error):
# Example: Resource temporarily unavailable.
pass
except dns.query.UnexpectedSource:
# Example: got a response from XXX instead of XXX.
pass
except dns.query.BadResponse:
# Example: A DNS query response does not respond to the question
# asked.
pass
except ValueError:
# Example: Input is malformed.
break
PyFunceble.facility.Logger.debug(
"Unsuccessfully queried information of %r from %r. Sleeping %fs.",
self.subject,
nameserver,
self.delay,
)
time.sleep(self.delay)
return ListHelper(result).remove_duplicates().subject
@ensure_subject_is_given
@ignore_if_query_message_is_missing
@update_lookup_record_response
def https(
self,
) -> Optional[List[str]]:
"""
Request the chosen record through the https protocol.
"""
self.lookup_record.used_protocol = "HTTPS"
result = []
for nameserver in self._mix_order(self.nameservers.get_nameservers()):
PyFunceble.facility.Logger.debug(
"Started to query information of %r from %r", self.subject, nameserver
)
try:
response = dns.query.https(
self.query_message, nameserver, timeout=self.query_timeout
)
local_result = self._get_result_from_response(response)
if local_result:
result.extend(local_result)
self.lookup_record.nameserver = nameserver
PyFunceble.facility.Logger.debug(
"Successfully queried information of %r from %r.",
self.subject,
nameserver,
)
if not self.trust_server: # pragma: no cover: Per case.
break
if self.trust_server: # pragma: no cover: Per case.
break
except (dns.exception.Timeout, socket.error):
# Example: Resource temporarily unavailable.
pass
except dns.query.UnexpectedSource:
# Example: got a response from XXX instead of XXX.
pass
except dns.query.BadResponse:
# Example: A DNS query response does not respond to the question
# asked.
pass
except ValueError:
# Example: Input is malformed.
break
PyFunceble.facility.Logger.debug(
"Unsuccessfully queried information of %r from %r. Sleeping %fs.",
self.subject,
nameserver,
self.delay,
)
time.sleep(self.delay)
return ListHelper(result).remove_duplicates().subject
@ensure_subject_is_given
@ignore_if_query_message_is_missing
@update_lookup_record_response
def tls(
self,
) -> Optional[List[str]]:
"""
Request the chosen record through the TLS protocol.
"""
self.lookup_record.used_protocol = "TLS"
result = []
for nameserver, port in self._mix_order(
self.nameservers.get_nameserver_ports()
).items():
PyFunceble.facility.Logger.debug(
"Started to query information of %r from %r", self.subject, nameserver
)
if port == 53:
# Default port for nameserver class is 53. So we ensure we
# overwrite with our own default.
port = 853
try:
response = dns.query.tls(
self.query_message,
nameserver,
port=port,
timeout=self.query_timeout,
)
local_result = self._get_result_from_response(response)
if local_result:
result.extend(local_result)
self.lookup_record.nameserver = nameserver
self.lookup_record.port = port
PyFunceble.facility.Logger.debug(
"Successfully queried information of %r from %r.",
self.subject,
nameserver,
)
if not self.trust_server: # pragma: no cover: Per case.
break
if self.trust_server: # pragma: no cover: Per case.
break
except (dns.exception.Timeout, socket.error):
# Example: Resource temporarily unavailable.
pass
except dns.query.UnexpectedSource:
# Example: got a response from XXX instead of XXX.
pass
except dns.query.BadResponse:
# Example: A DNS query response does not respond to the question
# asked.
pass
except ValueError:
# Example: Input is malformed.
break
PyFunceble.facility.Logger.debug(
"Unsuccessfully queried information of %r from %r. Sleeping %fs.",
self.subject,
nameserver,
self.delay,
)
time.sleep(self.delay)
return ListHelper(result).remove_duplicates().subject
def query(
self,
) -> Optional[List[str]]:
"""
Process the query based on the preferred protocol.
"""
return getattr(self, self.preferred_protocol.lower())()
|