File size: 2,637 Bytes
04782c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Bounded HTTPS GET for public Hugging Face metadata. Python standard library only.

Every request and every redirect must go to https on huggingface.co or a subdomain of huggingface.co or hf.co
(Hugging Face's file storage). Anything else raises OffOrigin before a connection is made to it. Redirects are
followed here, not by urllib: at most MAX_HOPS, and each redirect response is closed without reading its body. A final
body larger than the caller's limit raises TooLarge; at most limit + 1 bytes are read, before any parsing."""
import re, urllib.error, urllib.parse, urllib.request

UA = {"User-Agent": "so-arm-task-clock/0.2"}
REPO_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}/[A-Za-z0-9][A-Za-z0-9_.-]{0,95}")


class OffOrigin(Exception):
    pass


class TooLarge(Exception):
    pass


def allowed(url):
    u = urllib.parse.urlsplit(url)
    h = (u.hostname or "").lower()
    return (u.scheme == "https" and u.port in (None, 443) and u.username is None and u.password is None
            and (h == "huggingface.co" or h.endswith(".huggingface.co") or h.endswith(".hf.co")))


def valid_repo_id(i):
    return bool(REPO_ID.fullmatch(i)) and ".." not in i


MAX_HOPS = 5
REDIRECT = (301, 302, 303, 307, 308)


class TooManyRedirects(Exception):
    pass


class _NoFollow(urllib.request.HTTPRedirectHandler):
    """Hand every 30x back to get() as an HTTPError, before urllib reads the redirect body."""

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


_opener = urllib.request.build_opener(_NoFollow)


def get(url, limit, timeout=40):
    """Return (body bytes, response headers). Raises OffOrigin, TooLarge, TooManyRedirects or urllib.error.HTTPError."""
    for _ in range(MAX_HOPS + 1):
        if not allowed(url):
            raise OffOrigin(url)
        try:
            r = _opener.open(urllib.request.Request(url, headers=UA), timeout=timeout)
        except urllib.error.HTTPError as e:
            if e.code not in REDIRECT:
                raise
            loc = e.headers.get("Location")
            e.close()  # the redirect body is never read
            if not loc:
                raise
            url = urllib.parse.urljoin(url, loc)
            continue
        with r:
            n = r.headers.get("Content-Length")
            if n is not None and n.strip().isdigit() and int(n) > limit:
                raise TooLarge(f"{url}: Content-Length {n} > {limit}")
            b = r.read(limit + 1)
            if len(b) > limit:
                raise TooLarge(f"{url}: body > {limit} bytes")
            return b, r.headers
    raise TooManyRedirects(url)