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
|
"""
The tool to check the availability or syntax of domain, IP or URL.
::
██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝
██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗
██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝
██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝
Provides the base of all our adapter.
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.
"""
from typing import Optional
import requests.adapters
import requests.models
import PyFunceble.storage
from PyFunceble.checker.syntax.ip import IPSyntaxChecker
from PyFunceble.query.dns.query_tool import DNSQueryTool
class RequestAdapterBase(requests.adapters.HTTPAdapter):
"""
Extends the built-in HTTP adapater and acts as a base for all our own
adapter.
"""
resolving_cache: dict = {}
resolving_use_cache: bool = False
timeout: float = 5.0
proxy_pattern: dict = {}
def __init__(self, *args, **kwargs):
if "timeout" in kwargs:
self.timeout = float(kwargs["timeout"])
del kwargs["timeout"]
if "max_retries" in kwargs:
kwargs["max_retries"] = requests.adapters.Retry(
total=kwargs["max_retries"], respect_retry_after_header=False
)
if "dns_query_tool" in kwargs:
self.dns_query_tool = kwargs["dns_query_tool"]
del kwargs["dns_query_tool"]
else:
self.dns_query_tool = DNSQueryTool()
if "proxy_pattern" in kwargs:
self.proxy_pattern = kwargs["proxy_pattern"]
del kwargs["proxy_pattern"]
else:
self.proxy_pattern = {}
super().__init__(*args, **kwargs)
@staticmethod
def fake_response() -> requests.models.Response:
"""
Provides the fake response that is provided when we couldn't resolve the
given domain.
"""
raise PyFunceble.factory.Requester.exceptions.ConnectionError(
"Could not resolve."
)
@staticmethod
def extract_extension(subject: str) -> Optional[str]:
"""
Provides the extension of the given subject.
.. versionchanged:: 4.1.1.dev
Handle the case that the given subject does not have a `.` (point).
:param str subject:
The subject to get extract the extension from.
:raise TypeError:
When the given :code:`subject` is not a :py:class:`str`.
:raise ValueError:
When the given :code:`subject` is an empty :py:class:`str`.
"""
if not subject or "." not in subject:
return None
if subject.endswith("."):
# Absolute needs a little correction.
last_point = subject[:-1].rfind(".")
else:
last_point = subject.rindex(".")
extension = subject[last_point + 1 :]
if extension.endswith("."):
return extension[:-1]
return extension
def fetch_proxy_from_pattern(self, subject: str) -> dict:
"""
Provides the proxy settings to use for the given subject.
.. versionchanged:: 4.1.1.dev
Handle the case that the given subject has no extension/TLD.
:param str subject:
The subject to work with.
:raise TypeError:
When the given :code:`subject` is not a :py:class:`str`.
:raise ValueError:
When the given :code:`subject` is an empty :py:class:`str`.
"""
def correct_input(pattern_input: dict) -> dict:
result = {}
if "http" in pattern_input and pattern_input["http"]:
result["http"] = pattern_input["http"]
if "https" in pattern_input and pattern_input["https"]:
result["https"] = pattern_input["https"]
if "http" in result and "https" not in result:
result["https"] = result["http"]
if "https" in result and "http" not in result:
result["http"] = result["https"]
return result
extension = self.extract_extension(subject)
proxies = {}
if extension and "rules" in self.proxy_pattern:
for rule in self.proxy_pattern["rules"]:
local_proxy = {}
if "http" in rule and rule["http"]:
local_proxy["http"] = rule["http"]
if "https" in rule and rule["https"]:
local_proxy["https"] = rule["https"]
if not local_proxy:
continue
if "tld" in rule and extension in rule["tld"]:
proxies = correct_input(local_proxy)
break
if not proxies and "global" in self.proxy_pattern:
proxies = correct_input(self.proxy_pattern["global"])
return proxies
def resolve_with_cache(self, hostname: str) -> Optional[str]:
"""
Try to resolve using an internal cache.
"""
if hostname not in self.resolving_cache:
self.resolving_cache[hostname] = self.resolve_without_cache(hostname)
return self.resolving_cache[hostname]
def resolve_without_cache(self, hostname: str) -> Optional[str]:
"""
Resolves the IP of the given hostname.
:param hostname:
The hostname to get resolve.
"""
def get_last_cname(subject: str, recursion_depth: int = 60) -> Optional[str]:
"""
Given a subject, this function tries to query the CNAME until there
is none.
:param subject:
The first subject.
"""
last_cname_result = []
last_cname_new_subject = subject
depth = 0
while depth < recursion_depth:
local_last_cname_result = (
self.dns_query_tool.set_query_record_type("CNAME")
.set_subject(last_cname_new_subject)
.query()
)
depth += 1
if any(x in last_cname_result for x in local_last_cname_result):
break
last_cname_result.extend(local_last_cname_result)
if local_last_cname_result:
last_cname_new_subject = local_last_cname_result[0]
else:
break
try:
return last_cname_result[-1]
except IndexError:
return None
result = set()
if not IPSyntaxChecker(hostname).is_valid():
last_cname = get_last_cname(hostname)
if last_cname:
result.update(
self.dns_query_tool.set_query_record_type("A")
.set_subject(last_cname)
.query()
)
else:
result.update(
self.dns_query_tool.set_query_record_type("A")
.set_subject(hostname)
.query()
)
else:
result.add(hostname)
if result:
return result.pop()
return None
def resolve(self, hostname: str) -> Optional[str]:
"""
Resolves with the prefered method.
"""
if hostname:
if self.resolving_use_cache:
return self.resolve_with_cache(hostname)
return self.resolve_without_cache(hostname)
return None
|