Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/flake8.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12"]
python-version: ["3.11", "3.12"]
steps:
- name: Check out repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12"]
python-version: ["3.11", "3.12"]

steps:
- name: Check out repository
Expand Down
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Use an official Python 3.11.4 image as the base
FROM python:3.11.4
# Use an official Python 3.11 image as the base
FROM python:3.11

# Set a working directory within the container
WORKDIR /app
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@

### Dependencies
- Tor (Optional)
- Python 3.10+
- Python 3.11.5+
- pip

The link crawler visits up to 100 distinct pages per crawl, including the starting URL and failed requests. It accepts up to 1 MiB per response and requests uncompressed HTML. Oversized or compressed child pages are recorded as failed.

## Quick start

### Local setup
Expand Down
5 changes: 2 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,9 @@ authors = [
]
description = "TorBot is an OSINT tool for the dark web."
readme = "README.md"
requires-python = ">=3.10"
requires-python = ">=3.11.5"
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Operating System :: OS Independent",
Expand All @@ -37,7 +36,7 @@ dependencies = [
"scikit-learn>=1.5.0",
"scipy>=1.13.0",
"six>=1.16.0",
"soupsieve>=2.8.4",
"soupsieve>=4.1.3",
"termcolor>=2.4.0",
"texttable>=1.7.0",
"threadpoolctl>=3.5.0",
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ setuptools==84.1.0
six==1.16.0
sniffio==1.3.1
socksio==1.0.0
soupsieve==2.9
soupsieve==4.1.3
tabulate==0.9.0
termcolor==2.4.0
texttable==1.7.0
Expand Down
6 changes: 4 additions & 2 deletions src/torbot/modules/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@ def execute_all(
def fetch_html(
client: httpx.Client, link: str, tree: LinkTree, save_html: bool = False
) -> None:
resp = client.get(url=link)
soup = BeautifulSoup(resp.text, "html.parser")
html = tree.root_html if link == tree.root else None
if html is None:
html = client.get(url=link).text
soup = BeautifulSoup(html, "html.parser")

if save_html is False:
print(f"""
Expand Down
138 changes: 74 additions & 64 deletions src/torbot/modules/linktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import logging
import os
import re
from collections import deque
from datetime import datetime, timezone
from time import monotonic
from urllib import parse
Expand All @@ -16,7 +17,7 @@
import validators
from bs4 import BeautifulSoup
from tabulate import tabulate
from treelib import Node, Tree, exceptions
from treelib import Node, Tree

from .color import color
from .config import project_root_directory
Expand Down Expand Up @@ -52,82 +53,91 @@ def __init__(


class LinkTree(Tree):
MAX_PAGES = 100
MAX_RESPONSE_BYTES = 1024 * 1024

def __init__(self, url: str, depth: int, client: httpx.Client) -> None:
super().__init__()
self._url = url
self._depth = depth
self._client = client
self.root_html: str | None = None
self.crawl_failures: list[dict] = []

def load(self) -> None:
from torbot.crawl_result import failed_page

if self.root is not None:
return
self.crawl_started_at = datetime.now(timezone.utc)
self.crawl_started_monotonic = monotonic()
self._append_node(id=self._url, parent_id=None)
self._build_tree(url=self._url, depth=self._depth)

def _append_node(self, id: str, parent_id: str or None) -> None:
"""
Creates a node for a tree using the given ID which corresponds to a URL.
If the parent_id is None, this will be considered a root node.
"""
try:
resp = self._client.get(id)
except Exception as exc:
logging.warning("Skipping URL %s due to request error: %s", id, exc)
raise RequestError(str(exc)) from exc

if not getattr(resp, "text", None):
logging.warning("Skipping URL %s because the response body was empty", id)
raise RequestError("empty response")

soup = BeautifulSoup(resp.text, "html.parser")
title = (
soup.title.text.strip() if soup.title is not None else parse_hostname(id)
)
text = extract_visible_text(soup)
try:
[classification, accuracy] = classify(resp.text)
numbers = parse_phone_numbers(soup)
emails = parse_emails(soup)
pending = deque([(self._url, None, 0)])
# Reserve a slot before enqueueing, including for requests that later fail.
visited = {self._request_key(self._url)}
while pending:
url, parent, depth = pending.popleft()
try:
html, status = self._fetch_page(url)
except RequestError as exc:
if parent is None:
raise
self.crawl_failures.append(failed_page(url, parent, depth, exc))
continue

soup = BeautifulSoup(html, "html.parser")
title = soup.title.text.strip() if soup.title else parse_hostname(url)
classification, accuracy = classify(html)
children = []
if depth < self._depth and len(visited) < self.MAX_PAGES:
children = parse_links(soup)
text = extract_visible_text(soup)
data = LinkNode(
title,
id,
resp.status_code,
classification,
accuracy,
numbers,
emails,
text,
title, url, status, classification, accuracy,
parse_phone_numbers(soup), parse_emails(soup), text,
)
self.create_node(title, identifier=id, parent=parent_id, data=data)
except exceptions.DuplicatedNodeIdError:
logging.debug(f"found a duplicate URL {id}")

def _build_tree(self, url: str, depth: int) -> None:
"""
Builds a tree from the root to the given depth.
"""
if depth > 0:
depth -= 1
try:
resp = self._client.get(url)
except Exception as exc:
logging.warning("Skipping subtree from %s due to request error: %s", url, exc)
return
self.create_node(title, identifier=url, parent=parent, data=data)
if parent is None:
self.root_html = html

children = parse_links(resp.text)
for child in children:
try:
self._append_node(id=child, parent_id=url)
self._build_tree(url=child, depth=depth)
except RequestError as exc:
from torbot.crawl_result import failed_page

parent_depth = self.depth(url)
self.crawl_failures.append(
failed_page(child, url, parent_depth + 1, exc)
)
key = self._request_key(child)
if key in visited:
continue
visited.add(key)
pending.append((child, url, depth + 1))
if len(visited) >= self.MAX_PAGES:
break

@staticmethod
def _request_key(url: str) -> httpx.URL | str:
# HTTPX normalizes host and port. raw_path preserves path escapes and
# query strings while treating an empty HTTP path as "/".
try:
target = httpx.URL(url)
except httpx.InvalidURL:
return url
return target.copy_with(fragment=None, raw_path=target.raw_path)

def _fetch_page(self, url: str) -> tuple[str, int]:
try:
with self._client.stream(
"GET", url, headers={"Accept-Encoding": "identity"}, follow_redirects=False
) as response:
# Reject unsolicited compression before HTTPX can inflate a chunk.
if response.headers.get("Content-Encoding", "identity").lower() != "identity":
raise RequestError("unsupported compressed response")
body = bytearray()
for chunk in response.iter_bytes():
if len(chunk) > self.MAX_RESPONSE_BYTES - len(body):
raise RequestError("response exceeds crawl byte limit")
body.extend(chunk)
if not body:
raise RequestError("empty response")
encoding = response.encoding or "utf-8"
return body.decode(encoding, errors="replace"), response.status_code
except (httpx.HTTPError, httpx.InvalidURL) as exc:
logging.warning("Skipping URL %s due to request error: %s", url, exc)
raise RequestError(str(exc)) from exc

def to_crawl_result(
self,
Expand Down Expand Up @@ -247,14 +257,14 @@ def extract_visible_text(soup: BeautifulSoup, *, limit: int = 50_000) -> str:
return text[:limit]


def parse_links(html: str, base_url: str | None = None) -> list[str]:
def parse_links(html: str | BeautifulSoup, base_url: str | None = None) -> list[str]:
"""
Finds all anchor tags and parses the href attribute.

Relative links are resolved against the page URL when a base URL is provided.
Only absolute http(s) links are returned.
"""
soup = BeautifulSoup(html, "html.parser")
soup = html if isinstance(html, BeautifulSoup) else BeautifulSoup(html, "html.parser")
links = []
for tag in soup.find_all("a"):
href = tag.get("href")
Expand Down
66 changes: 66 additions & 0 deletions tests/test_crawl_limits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import httpx
import pytest

from torbot.modules.linktree import LinkTree, RequestError


def test_page_budget_counts_failures_and_skips_cycles(monkeypatch):
root = "https://example.test"
paths = {
"/": ["/a", "/a#dup", "/missing"],
"/a": ["/#back", "/missing", "/last", "/over-budget"],
"/last": [],
}
requests = []

def respond(request):
path = request.url.path
requests.append(path)
if path == "/missing":
raise httpx.ConnectError("offline")
links = "".join(f'<a href="{root}{p}">link</a>' for p in paths[path])
return httpx.Response(200, text="<title>page</title>" + links)

monkeypatch.setattr(LinkTree, "MAX_PAGES", 4)
with httpx.Client(transport=httpx.MockTransport(respond)) as client:
tree = LinkTree(root, 10, client)
tree.load()
assert requests == ["/", "/a", "/missing", "/last"]
assert tree.size() == 3
assert [p["url"] for p in tree.crawl_failures] == [root + "/missing"]


@pytest.mark.parametrize("mode", ["at_limit", "overflow", "compressed"])
def test_stream_budget_stops_reading_and_closes_response(monkeypatch, mode):
class Body(httpx.SyncByteStream):
closed = False

def __iter__(self):
assert mode != "compressed", "compressed body read"
yield b"1234"
yield b"5678"
if mode == "overflow":
yield b"9"
pytest.fail("continued reading after the byte limit")

def close(self):
self.closed = True

body = Body()

def respond(request):
assert request.headers["Accept-Encoding"] == "identity"
headers = {"Content-Encoding": "gzip"} if mode == "compressed" else {}
return httpx.Response(200, headers=headers, stream=body)

monkeypatch.setattr(LinkTree, "MAX_RESPONSE_BYTES", 8)
with httpx.Client(transport=httpx.MockTransport(respond)) as client:
tree = LinkTree("http://example.test", 0, client)
if mode == "at_limit":
tree.load()
assert tree.get_node(tree.root).data.text == "12345678"
else:
with pytest.raises(RequestError, match="byte limit|compressed"):
tree.load()
assert tree.size() == 0
assert body.closed
3 changes: 2 additions & 1 deletion tests/test_export_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def test_exports_stay_in_output_directory(tmp_path, title):
tree.load()
tree.save()
tree.saveJSON()
fetch_html(client, "http://example.test", tree, save_html=True)
with patch.object(client, "get", side_effect=AssertionError("root fetched twice")):
fetch_html(client, "http://example.test", tree, save_html=True)
files = list(output.iterdir())
assert len(files) == 3
assert {p.suffix for p in files} == {".txt", ".json", ".html"}
Expand Down
12 changes: 7 additions & 5 deletions tests/test_linktree_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
- Saving to JSON and text formats
- Classification and contact extraction integration
"""
from contextlib import contextmanager
import json
import httpx
import tempfile
from pathlib import Path
from unittest.mock import patch
Expand All @@ -33,12 +35,12 @@ def __init__(self, responses: dict[str, FakeResponse]):
self.responses = responses
self.call_count = {}

def get(self, url: str) -> FakeResponse:
@contextmanager
def stream(self, method, url, **kwargs):
assert method == "GET"
self.call_count[url] = self.call_count.get(url, 0) + 1
if url in self.responses:
return self.responses[url]
# Return a minimal response for unknown URLs
return FakeResponse(url, "<html><title>404</title></html>", 404)
result = self.responses.get(url, FakeResponse(url, "<title>404</title>", 404))
yield httpx.Response(result.status_code, text=result.text)


def test_parse_hostname_extracts_domain():
Expand Down