| 1 |
# mypy: allow-untyped-defs |
| 2 |
|
| 3 |
import json |
| 4 |
import select |
| 5 |
import socket |
| 6 |
|
| 7 |
from http.client import HTTPConnection |
| 8 |
from typing import Dict, List, Mapping, Sequence, Tuple |
| 9 |
from urllib import parse as urlparse |
| 10 |
|
| 11 |
from . import error |
| 12 |
|
| 13 |
"""Implements HTTP transport for the WebDriver wire protocol.""" |
| 14 |
|
| 15 |
|
| 16 |
missing = object() |
| 17 |
|
| 18 |
|
| 19 |
class ResponseHeaders(Mapping[str, str]): |
| 20 |
"""Read-only dictionary-like API for accessing response headers. |
| 21 |
|
| 22 |
This class: |
| 23 |
* Normalizes the header keys it is built with to lowercase (such that |
| 24 |
iterating the items will return lowercase header keys). |
| 25 |
* Has case-insensitive header lookup. |
| 26 |
* Always returns all header values that have the same name, separated by |
| 27 |
commas. |
| 28 |
""" |
| 29 |
def __init__(self, items: Sequence[Tuple[str, str]]): |
| 30 |
self.headers_dict: Dict[str, List[str]] = {} |
| 31 |
for key, value in items: |
| 32 |
key = key.lower() |
| 33 |
if key not in self.headers_dict: |
| 34 |
self.headers_dict[key] = [] |
| 35 |
self.headers_dict[key].append(value) |
| 36 |
|
| 37 |
def __getitem__(self, key): |
| 38 |
"""Get all headers of a certain (case-insensitive) name. If there is |
| 39 |
more than one, the values are returned comma separated""" |
| 40 |
values = self.headers_dict[key.lower()] |
| 41 |
if len(values) == 1: |
| 42 |
return values[0] |
| 43 |
else: |
| 44 |
return ", ".join(values) |
| 45 |
|
| 46 |
def get_list(self, key, default=missing): |
| 47 |
"""Get all the header values for a particular field name as a list""" |
| 48 |
try: |
| 49 |
return self.headers_dict[key.lower()] |
| 50 |
except KeyError: |
| 51 |
if default is not missing: |
| 52 |
return default |
| 53 |
else: |
| 54 |
raise |
| 55 |
|
| 56 |
def __iter__(self): |
| 57 |
yield from self.headers_dict |
| 58 |
|
| 59 |
def __len__(self): |
| 60 |
return len(self.headers_dict) |
| 61 |
|
| 62 |
|
| 63 |
class Response: |
| 64 |
""" |
| 65 |
Describes an HTTP response received from a remote end whose |
| 66 |
body has been read and parsed as appropriate. |
| 67 |
""" |
| 68 |
|
| 69 |
def __init__(self, status, body, headers): |
| 70 |
self.status = status |
| 71 |
self.body = body |
| 72 |
self.headers = headers |
| 73 |
|
| 74 |
def __repr__(self): |
| 75 |
cls_name = self.__class__.__name__ |
| 76 |
if self.error: |
| 77 |
return f"<{cls_name} status={self.status} error={repr(self.error)}>" |
| 78 |
return f"<{cls_name}: status={self.status} body={json.dumps(self.body)}>" |
| 79 |
|
| 80 |
def __str__(self): |
| 81 |
return json.dumps(self.body, indent=2) |
| 82 |
|
| 83 |
@property |
| 84 |
def error(self): |
| 85 |
if self.status != 200: |
| 86 |
return error.from_response(self) |
| 87 |
return None |
| 88 |
|
| 89 |
@classmethod |
| 90 |
def from_http(cls, http_response, decoder=json.JSONDecoder, **kwargs): |
| 91 |
try: |
| 92 |
body = json.load(http_response, cls=decoder, **kwargs) |
| 93 |
headers = ResponseHeaders(http_response.getheaders()) |
| 94 |
except ValueError: |
| 95 |
raise ValueError("Failed to decode response body as JSON:\n" + |
| 96 |
repr(http_response.read())) |
| 97 |
|
| 98 |
return cls(http_response.status, body, headers) |
| 99 |
|
| 100 |
|
| 101 |
class HTTPWireProtocol: |
| 102 |
""" |
| 103 |
Transports messages (commands and responses) over the WebDriver |
| 104 |
wire protocol. |
| 105 |
|
| 106 |
Complex objects, such as ``webdriver.ShadowRoot``, ``webdriver.WebElement``, |
| 107 |
``webdriver.WebFrame``, and ``webdriver.WebWindow`` are by default not |
| 108 |
marshaled to enable use of `session.transport.send` in WPT tests:: |
| 109 |
|
| 110 |
session = webdriver.Session("127.0.0.1", 4444) |
| 111 |
response = transport.send("GET", "element/active", None) |
| 112 |
print response.body["value"] |
| 113 |
# => {u'element-6066-11e4-a52e-4f735466cecf': u'<uuid>'} |
| 114 |
|
| 115 |
Automatic marshaling is provided by ``webdriver.protocol.Encoder`` |
| 116 |
and ``webdriver.protocol.Decoder``, which can be passed in to |
| 117 |
``HTTPWireProtocol.send`` along with a reference to the current |
| 118 |
``webdriver.Session``:: |
| 119 |
|
| 120 |
session = webdriver.Session("127.0.0.1", 4444) |
| 121 |
response = transport.send("GET", "element/active", None, |
| 122 |
encoder=protocol.Encoder, decoder=protocol.Decoder, |
| 123 |
session=session) |
| 124 |
print response.body["value"] |
| 125 |
# => webdriver.Element |
| 126 |
""" |
| 127 |
|
| 128 |
def __init__(self, host, port, url_prefix="/"): |
| 129 |
""" |
| 130 |
Construct interface for communicating with the remote server. |
| 131 |
|
| 132 |
:param url: URL of remote WebDriver server. |
| 133 |
:param wait: Duration to wait for remote to appear. |
| 134 |
""" |
| 135 |
self.host = host |
| 136 |
self.port = port |
| 137 |
self.url_prefix = url_prefix |
| 138 |
self._conn = None |
| 139 |
self._last_request_is_blocked = False |
| 140 |
|
| 141 |
def __del__(self): |
| 142 |
self.close() |
| 143 |
|
| 144 |
def close(self): |
| 145 |
"""Closes the current HTTP connection, if there is one.""" |
| 146 |
if self._conn: |
| 147 |
try: |
| 148 |
self._conn.close() |
| 149 |
except OSError: |
| 150 |
# The remote closed the connection |
| 151 |
pass |
| 152 |
self._conn = None |
| 153 |
|
| 154 |
@property |
| 155 |
def connection(self): |
| 156 |
"""Gets the current HTTP connection, or lazily creates one.""" |
| 157 |
if not self._conn: |
| 158 |
conn_kwargs = {} |
| 159 |
# We are not setting an HTTP timeout other than the default when the |
| 160 |
# connection its created. The send method has a timeout value if needed. |
| 161 |
self._conn = HTTPConnection(self.host, self.port, **conn_kwargs) |
| 162 |
|
| 163 |
return self._conn |
| 164 |
|
| 165 |
def url(self, suffix): |
| 166 |
""" |
| 167 |
From the relative path to a command end-point, |
| 168 |
craft a full URL suitable to be used in a request to the HTTPD. |
| 169 |
""" |
| 170 |
return urlparse.urljoin(self.url_prefix, suffix) |
| 171 |
|
| 172 |
def send(self, |
| 173 |
method, |
| 174 |
uri, |
| 175 |
body=None, |
| 176 |
headers=None, |
| 177 |
encoder=json.JSONEncoder, |
| 178 |
decoder=json.JSONDecoder, |
| 179 |
timeout=None, |
| 180 |
**codec_kwargs): |
| 181 |
""" |
| 182 |
Send a command to the remote. |
| 183 |
|
| 184 |
The request `body` must be JSON serializable unless a |
| 185 |
custom `encoder` has been provided. This means complex |
| 186 |
objects such as ``webdriver.ShadowRoot``, ``webdriver.WebElement``, |
| 187 |
``webdriver.WebFrame``, and `webdriver.Window`` are not automatically |
| 188 |
made into JSON. This behavior is, however, provided by |
| 189 |
``webdriver.protocol.Encoder``, should you want it. |
| 190 |
|
| 191 |
Similarly, the response body is returned au natural |
| 192 |
as plain JSON unless a `decoder` that converts web |
| 193 |
element references to ``webdriver.Element`` is provided. |
| 194 |
Use ``webdriver.protocol.Decoder`` to achieve this behavior. |
| 195 |
|
| 196 |
The client will attempt to use persistent HTTP connections. |
| 197 |
|
| 198 |
:param method: `GET`, `POST`, or `DELETE`. |
| 199 |
:param uri: Relative endpoint of the requests URL path. |
| 200 |
:param body: Body of the request. Defaults to an empty |
| 201 |
dictionary if ``method`` is `POST`. |
| 202 |
:param headers: Additional dictionary of headers to include |
| 203 |
in the request. |
| 204 |
:param encoder: JSON encoder class, which defaults to |
| 205 |
``json.JSONEncoder`` unless specified. |
| 206 |
:param decoder: JSON decoder class, which defaults to |
| 207 |
``json.JSONDecoder`` unless specified. |
| 208 |
:param timeout: Optional timeout for the underlying socket. `None` will |
| 209 |
retain the existing timeout. |
| 210 |
:param codec_kwargs: Surplus arguments passed on to `encoder` |
| 211 |
and `decoder` on construction. |
| 212 |
|
| 213 |
:return: Instance of ``webdriver.transport.Response`` |
| 214 |
describing the HTTP response received from the remote end. |
| 215 |
|
| 216 |
:raises ValueError: If `body` or the response body are not |
| 217 |
JSON serializable. |
| 218 |
""" |
| 219 |
if body is None and method == "POST": |
| 220 |
body = {} |
| 221 |
|
| 222 |
payload = None |
| 223 |
if body is not None: |
| 224 |
try: |
| 225 |
payload = json.dumps(body, cls=encoder, **codec_kwargs) |
| 226 |
except ValueError: |
| 227 |
raise ValueError("Failed to encode request body as JSON:\n" |
| 228 |
"%s" % json.dumps(body, indent=2)) |
| 229 |
|
| 230 |
response = self._request(method, uri, payload, headers, timeout=timeout) |
| 231 |
return Response.from_http(response, decoder=decoder, **codec_kwargs) |
| 232 |
|
| 233 |
def _request(self, method, uri, payload, headers=None, timeout=None): |
| 234 |
if isinstance(payload, str): |
| 235 |
payload = payload.encode("utf-8") |
| 236 |
|
| 237 |
if headers is None: |
| 238 |
headers = {} |
| 239 |
headers.update({"Connection": "keep-alive"}) |
| 240 |
|
| 241 |
url = self.url(uri) |
| 242 |
|
| 243 |
if self._last_request_is_blocked or self._has_unread_data(): |
| 244 |
self.close() |
| 245 |
|
| 246 |
# When the timeout triggers, the TestRunnerManager thread will reuse |
| 247 |
# this connection to check if the WebDriver its alive and we may end |
| 248 |
# raising an httplib.CannotSendRequest exception if the WebDriver is |
| 249 |
# not responding and this httplib.request() call is blocked on the |
| 250 |
# runner thread. We use the boolean below to check for that and restart |
| 251 |
# the connection in that case. |
| 252 |
self._last_request_is_blocked = True |
| 253 |
self.connection.request(method, url, payload, headers) |
| 254 |
|
| 255 |
# `timeout` for this request has to be set just before calling |
| 256 |
# `getresponse()` and the previous value restored just after that, |
| 257 |
# even on exception raised. Initialize `previous_timeout` to the global |
| 258 |
# default socket timeout in case the lazily created socket doesn't exist |
| 259 |
# before `getresponse()`. |
| 260 |
previous_timeout = socket.getdefaulttimeout() |
| 261 |
try: |
| 262 |
if timeout and self.connection.sock: |
| 263 |
previous_timeout = self.connection.sock.gettimeout() |
| 264 |
self.connection.sock.settimeout(timeout) |
| 265 |
response = self.connection.getresponse() |
| 266 |
finally: |
| 267 |
if timeout and self.connection.sock: |
| 268 |
self.connection.sock.settimeout(previous_timeout) |
| 269 |
|
| 270 |
self._last_request_is_blocked = False |
| 271 |
return response |
| 272 |
|
| 273 |
def _has_unread_data(self): |
| 274 |
return self._conn and self._conn.sock and select.select([self._conn.sock], [], [], 0)[0] |