ii-assistent/hunter/network.py

80 lines
2.4 KiB
Python

import ipaddress
import socket
from urllib.parse import urlsplit, urlunsplit
import urllib3
from bs4 import BeautifulSoup
MAX_BYTES = 2_000_000
def public_url(url):
parts = urlsplit(url.strip())
if (
parts.scheme not in ("http", "https")
or not parts.hostname
or parts.username
or parts.password
):
raise ValueError("invalid_url")
if parts.port not in (None, 80, 443):
raise ValueError("invalid_port")
addresses = socket.getaddrinfo(
parts.hostname,
parts.port or (443 if parts.scheme == "https" else 80),
type=socket.SOCK_STREAM,
)
ips = {row[4][0] for row in addresses}
if not ips or any(not ipaddress.ip_address(ip).is_global for ip in ips):
raise ValueError("private_address")
return urlunsplit((parts.scheme, parts.netloc, parts.path or "/", parts.query, "")), sorted(
ips
)[0]
def fetch(url):
# Pin the validated IP on the actual connection: avoids DNS rebinding.
clean, ip = public_url(url)
parts = urlsplit(clean)
common = dict(
port=parts.port or (443 if parts.scheme == "https" else 80),
timeout=urllib3.Timeout(connect=8, read=15),
retries=False,
)
if parts.scheme == "https":
pool = urllib3.HTTPSConnectionPool(
ip, server_hostname=parts.hostname, assert_hostname=parts.hostname, **common
)
else:
pool = urllib3.HTTPConnectionPool(ip, **common)
try:
response = pool.request(
"GET",
urlunsplit(("", "", parts.path, parts.query, "")),
headers={
"Host": parts.netloc,
"User-Agent": "AITrendHunter/1.0 RSSReader",
"Accept": "application/rss+xml, application/atom+xml, text/xml, text/html",
},
redirect=False,
preload_content=False,
)
try:
if response.status != 200:
raise ValueError("source_unavailable")
body = response.read(MAX_BYTES + 1)
if len(body) > MAX_BYTES:
raise ValueError("source_too_large")
return body
finally:
response.close()
finally:
pool.close()
def text(html, limit=800):
soup = BeautifulSoup(html, "html.parser")
for node in soup(["script", "style", "nav", "footer", "header", "noscript"]):
node.decompose()
return " ".join(soup.stripped_strings)[:limit]