Debian Codegraph @

DisplayCAL/network.py

raw
1 """Network utilities: hostname resolution, address retrieval, and custom sockets.
2
3 It also includes HTTP redirect handlers for logging or preventing redirections.
4 """
5
6 from __future__ import annotations
7
8 import errno
9 import os
10 import socket
11 import sys
12 import urllib.error
13 import urllib.request
14 from typing import TYPE_CHECKING, BinaryIO
15
16 from DisplayCAL import localization as lang
17 from DisplayCAL.util_str import safe_str
18
19 if TYPE_CHECKING:
20 from types import TracebackType
21
22 if sys.version_info >= (3, 11):
23 from typing import Self
24 else:
25 from typing_extensions import Self
26
27
28 DNS_SERVER_IP_ADDR = "8.8.8.8"
29 """Google's public DNS server IP address."""
30 DNS_SERVER_PORT = 53
31 """Port number for DNS server."""
32
33
34 def get_network_addr() -> str:
35 """Try to get the local machine's network address."""
36 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
37 # Opening a connection on a UDP socket does nothing except give the socket
38 # the network address of the (local) machine. We use Google's DNS server
39 # as remote address, but could use any valid non-local address (doesn't
40 # matter if it is actually reachable)
41 try:
42 s.connect((DNS_SERVER_IP_ADDR, DNS_SERVER_PORT))
43 return s.getsockname()[0] # Return network address
44 finally:
45 s.close()
46
47
48 def get_valid_host(hostname: None | str = None) -> tuple[str, str]:
49 """Try to verify the hostname by resolving to an IPv4 address.
50
51 Both hostname with and without .local suffix will be tried if necessary.
52
53 Returns:
54 tuple[str, str]: A tuple of hostname, addr
55 """
56 if hostname is None:
57 hostname = socket.gethostname()
58 hostnames = [hostname]
59 if hostname.endswith(".local"):
60 hostnames.insert(0, os.path.splitext(hostname)[0])
61 elif "." not in hostname:
62 hostnames.insert(0, f"{hostname}.local")
63
64 while hostnames:
65 hostname = hostnames.pop()
66 try:
67 addr = socket.gethostbyname(hostname)
68 except OSError as e:
69 if not hostnames:
70 raise e
71 else:
72 return hostname, addr
73 return None, None
74
75
76 class LoggingHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
77 """Like urllib2.HTTPRedirectHandler, but logs redirections.
78
79 Args:
80 req (urllib.request.Request): The request object.
81 fp (file-like object): The file-like object containing the response.
82 code (int): The HTTP status code.
83 msg (str): The HTTP status message.
84 headers (dict): The response headers.
85 """
86
87 # maximum number of redirections to any single URL
88 # this is needed because of the state that cookies introduce
89 max_repeats = 4
90 # maximum total number of redirections (regardless of URL) before
91 # assuming we're in a loop
92 max_redirections = 10
93
94 def http_error_302(
95 self,
96 req: urllib.request.Request,
97 fp: BinaryIO,
98 code: int,
99 msg: str,
100 headers: dict,
101 ) -> None | urllib.request.HTTPRedirectHandler:
102 """Handle HTTP 302 redirection error.
103
104 Args:
105 req (urllib.request.Request): The request object.
106 fp (BinaryIO): The file-like object containing the
107 response.
108 code (int): The HTTP status code.
109 msg (str): The HTTP status message.
110 headers (dict): The response headers.
111
112 Returns:
113 None | urllib.request.HTTPRedirectHandler: The HTTP redirect
114 handler instance, or None if no redirection is needed.
115 """
116 # Some servers (incorrectly) return multiple Location headers
117 # (so probably same goes for URI). Use first header.
118 if "location" in headers:
119 newurl = headers.get("location")
120 elif "uri" in headers:
121 newurl = headers.get("uri")
122 else:
123 return None
124
125 # Keep reference to new URL
126 LoggingHTTPRedirectHandler.newurl = newurl
127
128 if not hasattr(req, "redirect_dict"):
129 # First redirect in this chain. Log original URL
130 print(req.get_full_url(), end=" ")
131 print("\u2192", newurl)
132
133 return urllib.request.HTTPRedirectHandler.http_error_302(
134 self, req, fp, code, msg, headers
135 )
136
137 http_error_301 = http_error_303 = http_error_307 = http_error_302
138
139 inf_msg = urllib.request.HTTPRedirectHandler.inf_msg
140
141
142 class NoHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
143 """Like urllib2.HTTPRedirectHandler, but does not allow redirections.
144
145 Args:
146 req (urllib.request.Request): The request object.
147 fp (file-like object): The file-like object containing the response.
148 code (int): The HTTP status code.
149 msg (str): The HTTP status message.
150 headers (dict): The response headers.
151 """
152
153 def http_error_302(
154 self,
155 req: urllib.request.Request,
156 fp: BinaryIO,
157 code: int,
158 msg: str,
159 headers: dict,
160 ) -> None:
161 """Handle HTTP 302 redirection error.
162
163 Args:
164 req (urllib.request.Request): The request object.
165 fp (BinaryIO): The file-like object containing the
166 response.
167 code (int): The HTTP status code.
168 msg (str): The HTTP status message.
169 headers (dict): The response headers.
170
171 Raises:
172 urllib.error.HTTPError: If redirection is not allowed, raises an
173 HTTPError with the new URL and the original error message.
174 """
175 # Some servers (incorrectly) return multiple Location headers
176 # (so probably same goes for URI). Use first header.
177 if "location" in headers:
178 newurl = headers.get("location")
179 elif "uri" in headers:
180 newurl = headers.get("uri")
181 else:
182 return
183
184 raise urllib.error.HTTPError(
185 newurl,
186 code,
187 msg + f" - Redirection to url '{newurl}' is not allowed",
188 headers,
189 fp,
190 )
191
192 http_error_301 = http_error_303 = http_error_307 = http_error_302
193
194
195 class ScriptingClientSocket(socket.socket):
196 """A socket class for handling scripting client connections."""
197
198 def __init__(self) -> None:
199 socket.socket.__init__(self)
200 self.recv_buffer = b""
201
202 def __del__(self) -> None:
203 """Destructor for the ScriptingClientSocket class."""
204 self.disconnect()
205
206 def __enter__(self) -> Self:
207 """Enter method for context manager.
208
209 Returns:
210 ScriptingClientSocket: The instance of the socket.
211 """
212 return self
213
214 def __exit__(
215 self,
216 exc_type: None | type[BaseException],
217 exc_value: None | BaseException,
218 tb: None | TracebackType,
219 ) -> None:
220 """Exit method for context manager.
221
222 Args:
223 exc_type (type): The type of the exception raised, if any.
224 exc_value (None | BaseException): The exception instance, if any.
225 tb (None | TracebackType): The traceback object, if any.
226
227 Returns:
228 None
229 """
230 self.disconnect()
231
232 def disconnect(self) -> None:
233 """Disconnect the socket and clean up resources."""
234 try:
235 # Will fail if the socket isn't connected, i.e. if there was an
236 # error during the call to connect()
237 self.shutdown(socket.SHUT_RDWR)
238 except OSError as exception:
239 if exception.errno != errno.ENOTCONN:
240 print(exception)
241 self.close()
242
243 def get_single_response(self) -> bytes:
244 """Receive a single response from the socket.
245
246 Returns:
247 bytes: The single response received from the socket.
248 """
249 # Buffer received data until EOT (response end marker) and return
250 # single response (additional data will still be in the buffer)
251 while b"\4" not in self.recv_buffer:
252 incoming = self.recv(4096)
253 if incoming == b"":
254 raise OSError(lang.getstr("connection.broken"))
255 self.recv_buffer += incoming
256 end = self.recv_buffer.find(b"\4")
257 single_response = self.recv_buffer[:end]
258 self.recv_buffer = self.recv_buffer[end + 1 :]
259 return single_response
260
261 def send_command(self, command: str) -> None:
262 """Send a command to the socket.
263
264 Args:
265 command (str): The command to send.
266 """
267 # Automatically append newline (command end marker)
268 self.sendall((safe_str(command, "utf-8") + "\n").encode("utf-8"))