1- """Bounded HTTP image retrieval with validated, pinned public addresses."""
1+ """Bounded HTTPS image retrieval with validated, pinned public addresses."""
22
33from __future__ import annotations
44
1111import time
1212from urllib .parse import quote , urljoin , urlsplit
1313
14+ from tensorfold import __version__
15+
16+ MEDIA_TYPES = {"image/jpeg" : "JPEG" , "image/png" : "PNG" , "image/webp" : "WEBP" } # a declared type, its format
1417_DNS_SLOTS = threading .BoundedSemaphore (4 )
1518_REDIRECTS = {301 , 302 , 303 , 307 , 308 }
1619_SPECIAL_V4 = (ipaddress .ip_network ("192.0.0.0/24" ), ipaddress .ip_network ("168.63.129.16/32" ))
@@ -79,22 +82,22 @@ def _url(value: str, max_url_chars: int) -> tuple[str, str, int, str]:
7982 raise ImageInputError ("image URL is too long or contains whitespace/control characters" )
8083 try :
8184 parsed = urlsplit (value )
82- if parsed .scheme not in ( "http" , " https") or not parsed .hostname :
85+ if parsed .scheme != " https" or not parsed .hostname or parsed . fragment :
8386 raise ValueError
8487 if parsed .username is not None or parsed .password is not None or "\\ " in value :
8588 raise ValueError
8689 host = parsed .hostname .encode ("idna" ).decode ("ascii" )
87- port = parsed .port if parsed .port is not None else ( 443 if parsed . scheme == "https" else 80 )
88- if "%" in host or not 1 <= port <= 65535 :
90+ port = parsed .port if parsed .port is not None else 443
91+ if "%" in host or port != 443 :
8992 raise ValueError
9093 except (ValueError , UnicodeError ):
91- raise ImageInputError ("image URL must be an HTTP(S) URL without credentials" ) from None
94+ raise ImageInputError ("image URL must be HTTPS on port 443, without credentials or a fragment " ) from None
9295 if host .rstrip ("." ).lower () in {"localhost" , "metadata.google.internal" , "instance-data" }:
9396 raise ImageInputError ("image URLs must use public internet hosts" )
9497 target = quote (parsed .path or "/" , safe = "/%:@!$&'()*+,;=-._~" )
9598 if parsed .query :
9699 target += "?" + quote (parsed .query , safe = "/%?:@!$&'()*+,;=-._~" )
97- return parsed . scheme , host , port , target
100+ return host , port , target
98101
99102
100103def _close_socket (sock : socket .socket ) -> None :
@@ -105,8 +108,8 @@ def _close_socket(sock: socket.socket) -> None:
105108 sock .close ()
106109
107110
108- def _request (scheme : str , host : str , port : int , target : str , addresses : list [tuple ],
109- max_bytes : int , deadline : float ) -> tuple [bytes | None , str | None ]:
111+ def _request (host : str , port : int , target : str , addresses : list [tuple ],
112+ max_bytes : int , deadline : float ) -> tuple [bytes | None , str | None , str | None ]:
110113 """A watchdog bounds slow headers and TLS handshakes, not just individual reads."""
111114 timeout = _remaining (deadline )
112115 family , kind , protocol , _ , address = addresses [0 ]
@@ -119,25 +122,28 @@ def _request(scheme: str, host: str, port: int, target: str, addresses: list[tup
119122 timer .start ()
120123 sock .settimeout (_remaining (deadline ))
121124 sock .connect (address )
122- if scheme == "https" :
123- context = ssl .create_default_context ()
124- sock = context .wrap_socket (sock , server_hostname = host , do_handshake_on_connect = False )
125- live_socket [0 ] = sock
126- sock .settimeout (_remaining (deadline ))
127- sock .do_handshake ()
125+ context = ssl .create_default_context () # TLS verified for the host, on the address checked for it
126+ sock = context .wrap_socket (sock , server_hostname = host , do_handshake_on_connect = False )
127+ live_socket [0 ] = sock
128+ sock .settimeout (_remaining (deadline ))
129+ sock .do_handshake ()
128130 connection .sock = sock
129- connection .request ("GET" , target , headers = {"Accept" : "image/*" , "Accept-Encoding" : "identity" })
131+ connection .request ("GET" , target , headers = {"Accept" : ", " .join (MEDIA_TYPES ), "Accept-Encoding" : "identity" ,
132+ "User-Agent" : f"TensorFold/{ __version__ } " })
130133 response = connection .getresponse ()
131134 _remaining (deadline )
132135 if response .status in _REDIRECTS :
133136 location = response .getheader ("Location" )
134137 if not location :
135138 raise ImageInputError ("image redirect has no destination" )
136- return None , location
139+ return None , location , None
137140 if response .status != 200 :
138141 raise ImageInputError (f"image download returned HTTP { response .status } " )
139142 if response .getheader ("Content-Encoding" , "identity" ).lower () != "identity" :
140143 raise ImageInputError ("compressed HTTP image responses are unsupported" )
144+ media = response .getheader ("Content-Type" , "" ).split (";" , 1 )[0 ].strip ().lower ()
145+ if media not in MEDIA_TYPES :
146+ raise ImageInputError ("image URL content type must be JPEG, PNG or WebP" )
141147 length = response .getheader ("Content-Length" )
142148 if length is not None :
143149 if not length .isascii () or not length .isdecimal () or int (length ) > max_bytes :
@@ -152,23 +158,23 @@ def _request(scheme: str, host: str, port: int, target: str, addresses: list[tup
152158 if len (data ) > max_bytes :
153159 raise ImageInputError ("image response exceeds the encoded byte limit" )
154160 _remaining (deadline )
155- return bytes (data ), None
161+ return bytes (data ), None , media
156162 finally :
157163 timer .cancel ()
158164 connection .close ()
159165 _close_socket (sock )
160166
161167
162168def fetch_image (url : str , * , max_bytes : int , deadline : float , max_redirects : int ,
163- max_url_chars : int ) -> bytes :
169+ max_url_chars : int ) -> tuple [ bytes , str ] :
164170 """Resolve and validate each redirect, then connect directly to its checked address."""
165171 try :
166172 for redirect in range (max_redirects + 1 ):
167- scheme , host , port , target = _url (url , max_url_chars )
173+ host , port , target = _url (url , max_url_chars )
168174 addresses = _resolve (host , port , deadline )
169- data , location = _request (scheme , host , port , target , addresses , max_bytes , deadline )
175+ data , location , media = _request (host , port , target , addresses , max_bytes , deadline )
170176 if location is None :
171- return data
177+ return data , media
172178 if redirect == max_redirects :
173179 raise ImageInputError ("image download has too many redirects" )
174180 url = urljoin (url , location )
0 commit comments