1 | #!/usr/bin/python3 |
---|
2 | # PYTHON_ARGCOMPLETE_OK |
---|
3 | |
---|
4 | # Copyright 2019 Fiona Klute |
---|
5 | # |
---|
6 | # Licensed under the Apache License, Version 2.0 (the "License"); |
---|
7 | # you may not use this file except in compliance with the License. |
---|
8 | # You may obtain a copy of the License at |
---|
9 | # |
---|
10 | # http://www.apache.org/licenses/LICENSE-2.0 |
---|
11 | # |
---|
12 | # Unless required by applicable law or agreed to in writing, software |
---|
13 | # distributed under the License is distributed on an "AS IS" BASIS, |
---|
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
---|
15 | # See the License for the specific language governing permissions and |
---|
16 | # limitations under the License. |
---|
17 | |
---|
18 | import re |
---|
19 | import socket |
---|
20 | import subprocess |
---|
21 | import yaml |
---|
22 | |
---|
23 | from http.client import HTTPConnection |
---|
24 | from multiprocessing import Process |
---|
25 | from time import sleep |
---|
26 | |
---|
27 | class HTTPSubprocessConnection(HTTPConnection): |
---|
28 | def __init__(self, command, host, port=None, |
---|
29 | output_filter=None, |
---|
30 | timeout=socket._GLOBAL_DEFAULT_TIMEOUT, |
---|
31 | blocksize=8192): |
---|
32 | super(HTTPSubprocessConnection, self).__init__(host, port, timeout, |
---|
33 | source_address=None, |
---|
34 | blocksize=blocksize) |
---|
35 | # "command" must be a list containing binary and command line |
---|
36 | # parameters |
---|
37 | self.command = command |
---|
38 | # This will be the subprocess reference when connected |
---|
39 | self._sproc = None |
---|
40 | # The subprocess return code is stored here on close() |
---|
41 | self.returncode = None |
---|
42 | # The set_tunnel method of the super class is not supported |
---|
43 | # (see exception doc) |
---|
44 | self.set_tunnel = None |
---|
45 | # This method will be run in a separate process and filter the |
---|
46 | # stdout of self._sproc. Its arguments are self._sproc.stdout |
---|
47 | # and the socket back to the HTTP connection (write-only). |
---|
48 | self._output_filter = output_filter |
---|
49 | # output filter process |
---|
50 | self._fproc = None |
---|
51 | |
---|
52 | def connect(self): |
---|
53 | s_local, s_remote = socket.socketpair(socket.AF_UNIX, |
---|
54 | socket.SOCK_STREAM) |
---|
55 | s_local.settimeout(self.timeout) |
---|
56 | |
---|
57 | # TODO: Maybe capture stderr? |
---|
58 | if self._output_filter: |
---|
59 | self._sproc = subprocess.Popen(self.command, stdout=subprocess.PIPE, |
---|
60 | stdin=s_remote, close_fds=True, |
---|
61 | bufsize=0) |
---|
62 | self._fproc = Process(target=self._output_filter, |
---|
63 | args=(self._sproc.stdout, s_remote)) |
---|
64 | self._fproc.start() |
---|
65 | else: |
---|
66 | self._sproc = subprocess.Popen(self.command, stdout=s_remote, |
---|
67 | stdin=s_remote, close_fds=True, |
---|
68 | bufsize=0) |
---|
69 | s_remote.close() |
---|
70 | self.sock = s_local |
---|
71 | |
---|
72 | def close(self): |
---|
73 | # close socket to subprocess for writing |
---|
74 | if self.sock: |
---|
75 | self.sock.shutdown(socket.SHUT_WR) |
---|
76 | |
---|
77 | # Wait for the process to stop, send SIGTERM/SIGKILL if |
---|
78 | # necessary |
---|
79 | if self._sproc: |
---|
80 | try: |
---|
81 | self.returncode = self._sproc.wait(self.timeout) |
---|
82 | except subprocess.TimeoutExpired: |
---|
83 | try: |
---|
84 | self._sproc.terminate() |
---|
85 | self.returncode = self._sproc.wait(self.timeout) |
---|
86 | except subprocess.TimeoutExpired: |
---|
87 | self._sproc.kill() |
---|
88 | self.returncode = self._sproc.wait(self.timeout) |
---|
89 | |
---|
90 | # filter process receives HUP on pipe when the subprocess |
---|
91 | # terminates |
---|
92 | if self._fproc: |
---|
93 | self._fproc.join() |
---|
94 | |
---|
95 | # close the connection in the super class, which also calls |
---|
96 | # self.sock.close() |
---|
97 | super().close() |
---|
98 | |
---|
99 | |
---|
100 | |
---|
101 | class TestRequest(yaml.YAMLObject): |
---|
102 | yaml_tag = '!request' |
---|
103 | def __init__(self, path, method='GET', headers=dict(), |
---|
104 | expect=dict(status=200)): |
---|
105 | self.method = method |
---|
106 | self.path = path |
---|
107 | self.headers = headers |
---|
108 | self.expect = expect |
---|
109 | |
---|
110 | def __repr__(self): |
---|
111 | return (f'{self.__class__.__name__!s}(path={self.path!r}, ' |
---|
112 | f'method={self.method!r}, headers={self.headers!r}, ' |
---|
113 | f'expect={self.expect!r})') |
---|
114 | |
---|
115 | def run(self, conn): |
---|
116 | try: |
---|
117 | conn.request(self.method, self.path, headers=self.headers) |
---|
118 | resp = conn.getresponse() |
---|
119 | except ConnectionResetError as err: |
---|
120 | if self.expects_conn_reset(): |
---|
121 | print('connection reset as expected.') |
---|
122 | return |
---|
123 | else: |
---|
124 | raise err |
---|
125 | body = resp.read().decode() |
---|
126 | print(format_response(resp, body)) |
---|
127 | self.check_response(resp, body) |
---|
128 | |
---|
129 | def _check_body(self, body): |
---|
130 | """ |
---|
131 | >>> r1 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'exactly': 'test\\n'}}) |
---|
132 | >>> r1._check_body('test\\n') |
---|
133 | >>> r1._check_body('xyz\\n') |
---|
134 | Traceback (most recent call last): |
---|
135 | ... |
---|
136 | https-test-client.TestExpectationFailed: Unexpected body: 'xyz\\n' != 'test\\n' |
---|
137 | >>> r2 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'contains': ['tes', 'est']}}) |
---|
138 | >>> r2._check_body('test\\n') |
---|
139 | >>> r2._check_body('est\\n') |
---|
140 | Traceback (most recent call last): |
---|
141 | ... |
---|
142 | https-test-client.TestExpectationFailed: Unexpected body: 'est\\n' does not contain 'tes' |
---|
143 | >>> r3 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'contains': 'test'}}) |
---|
144 | >>> r3._check_body('test\\n') |
---|
145 | """ |
---|
146 | if 'exactly' in self.expect['body'] \ |
---|
147 | and body != self.expect['body']['exactly']: |
---|
148 | raise TestExpectationFailed( |
---|
149 | f'Unexpected body: {body!r} != ' |
---|
150 | f'{self.expect["body"]["exactly"]!r}') |
---|
151 | if 'contains' in self.expect['body']: |
---|
152 | if type(self.expect['body']['contains']) is str: |
---|
153 | self.expect['body']['contains'] = [ |
---|
154 | self.expect['body']['contains']] |
---|
155 | for s in self.expect['body']['contains']: |
---|
156 | if not s in body: |
---|
157 | raise TestExpectationFailed( |
---|
158 | f'Unexpected body: {body!r} does not contain ' |
---|
159 | f'{s!r}') |
---|
160 | |
---|
161 | def check_response(self, response, body): |
---|
162 | if self.expects_conn_reset(): |
---|
163 | raise TestExpectationFailed( |
---|
164 | 'Got a response, but connection should have failed!') |
---|
165 | if response.status != self.expect['status']: |
---|
166 | raise TestExpectationFailed( |
---|
167 | f'Unexpected status: {response.status} != ' |
---|
168 | f'{self.expect["status"]}') |
---|
169 | if 'body' in self.expect: |
---|
170 | self._check_body(body) |
---|
171 | |
---|
172 | def expects_conn_reset(self): |
---|
173 | if 'reset' in self.expect: |
---|
174 | return self.expect['reset'] |
---|
175 | return False |
---|
176 | |
---|
177 | @classmethod |
---|
178 | def _from_yaml(cls, loader, node): |
---|
179 | fields = loader.construct_mapping(node) |
---|
180 | req = TestRequest(**fields) |
---|
181 | return req |
---|
182 | |
---|
183 | class TestConnection(yaml.YAMLObject): |
---|
184 | yaml_tag = '!connection' |
---|
185 | |
---|
186 | def __init__(self, actions, gnutls_params=[], transport='gnutls'): |
---|
187 | self.gnutls_params = gnutls_params |
---|
188 | self.actions = actions |
---|
189 | self.transport = transport |
---|
190 | |
---|
191 | def __repr__(self): |
---|
192 | return (f'{self.__class__.__name__!s}' |
---|
193 | f'(gnutls_params={self.gnutls_params!r}, ' |
---|
194 | f'actions={self.actions!r}, transport={self.transport!r})') |
---|
195 | |
---|
196 | @classmethod |
---|
197 | def _from_yaml(cls, loader, node): |
---|
198 | fields = loader.construct_mapping(node) |
---|
199 | conn = TestConnection(**fields) |
---|
200 | return conn |
---|
201 | |
---|
202 | class TestRaw10(TestRequest): |
---|
203 | """This is a minimal (and likely incomplete) HTTP/1.0 test client for |
---|
204 | the one test case that strictly requires HTTP/1.0. All request |
---|
205 | parameters (method, path, headers) MUST be specified in the config |
---|
206 | file. |
---|
207 | |
---|
208 | """ |
---|
209 | yaml_tag = '!raw10' |
---|
210 | status_re = re.compile('^HTTP/([\d\.]+) (\d+) (.*)$') |
---|
211 | |
---|
212 | def __init__(self, method, path, headers, expect): |
---|
213 | self.method = method |
---|
214 | self.path = path |
---|
215 | self.headers = headers |
---|
216 | self.expect = expect |
---|
217 | |
---|
218 | def __repr__(self): |
---|
219 | return (f'{self.__class__.__name__!s}' |
---|
220 | f'(method={self.method!r}, path={self.path!r}, ' |
---|
221 | f'headers={self.headers!r}, expect={self.expect!r})') |
---|
222 | |
---|
223 | def run(self, command, timeout=None): |
---|
224 | req = f'{self.method} {self.path} HTTP/1.0\r\n' |
---|
225 | for name, value in self.headers.items(): |
---|
226 | req = req + f'{name}: {value}\r\n' |
---|
227 | req = req + f'\r\n' |
---|
228 | proc = subprocess.Popen(command, stdout=subprocess.PIPE, |
---|
229 | stdin=subprocess.PIPE, close_fds=True, |
---|
230 | bufsize=0) |
---|
231 | try: |
---|
232 | # Note: errs will be empty because stderr is not captured |
---|
233 | outs, errs = proc.communicate(input=req.encode(), |
---|
234 | timeout=timeout) |
---|
235 | except TimeoutExpired: |
---|
236 | proc.kill() |
---|
237 | outs, errs = proc.communicate() |
---|
238 | |
---|
239 | # first line of the received data must be the status |
---|
240 | status, rest = outs.decode().split('\r\n', maxsplit=1) |
---|
241 | # headers and body are separated by double newline |
---|
242 | headers, body = rest.split('\r\n\r\n', maxsplit=1) |
---|
243 | # log response for debugging |
---|
244 | print(f'{status}\n{headers}\n\n{body}') |
---|
245 | |
---|
246 | m = self.status_re.match(status) |
---|
247 | if m: |
---|
248 | status_code = int(m.group(2)) |
---|
249 | status_expect = self.expect.get('status') |
---|
250 | if status_expect and not status_code == status_expect: |
---|
251 | raise TestExpectationFailed('Unexpected status code: ' |
---|
252 | f'{status}, expected ' |
---|
253 | f'{status_expect}') |
---|
254 | else: |
---|
255 | raise TestExpectationFailed(f'Invalid status line: "{status}"') |
---|
256 | |
---|
257 | if 'body' in self.expect: |
---|
258 | self._check_body(body) |
---|
259 | |
---|
260 | # Override the default constructors. Pyyaml ignores default parameters |
---|
261 | # otherwise. |
---|
262 | yaml.add_constructor('!request', TestRequest._from_yaml, yaml.Loader) |
---|
263 | yaml.add_constructor('!connection', TestConnection._from_yaml, yaml.Loader) |
---|
264 | |
---|
265 | |
---|
266 | |
---|
267 | class TestExpectationFailed(Exception): |
---|
268 | """Raise if a test failed. The constructor should be called with a |
---|
269 | string describing the problem.""" |
---|
270 | pass |
---|
271 | |
---|
272 | |
---|
273 | |
---|
274 | def filter_cert_log(in_stream, out_stream): |
---|
275 | import fcntl |
---|
276 | import os |
---|
277 | import select |
---|
278 | # This filters out a log line about loading client |
---|
279 | # certificates that is mistakenly sent to stdout. My fix has |
---|
280 | # been merged, but buggy binaries will probably be around for |
---|
281 | # a while. |
---|
282 | # https://gitlab.com/gnutls/gnutls/merge_requests/1125 |
---|
283 | cert_log = b'Processed 1 client X.509 certificates...\n' |
---|
284 | |
---|
285 | # Set the input to non-blocking mode |
---|
286 | fd = in_stream.fileno() |
---|
287 | fl = fcntl.fcntl(fd, fcntl.F_GETFL) |
---|
288 | fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) |
---|
289 | |
---|
290 | # The poll object allows waiting for events on non-blocking IO |
---|
291 | # channels. |
---|
292 | poller = select.poll() |
---|
293 | poller.register(fd) |
---|
294 | |
---|
295 | init_done = False |
---|
296 | run_loop = True |
---|
297 | while run_loop: |
---|
298 | # The returned tuples are file descriptor and event, but |
---|
299 | # we're only listening on one stream anyway, so we don't |
---|
300 | # need to check it here. |
---|
301 | for x, event in poller.poll(): |
---|
302 | # Critical: "event" is a bitwise OR of the POLL* constants |
---|
303 | if event & select.POLLIN or event & select.POLLPRI: |
---|
304 | data = in_stream.read() |
---|
305 | if not init_done: |
---|
306 | # If the erroneous log line shows up it's the |
---|
307 | # first piece of data we receive. Just copy |
---|
308 | # everything after. |
---|
309 | init_done = True |
---|
310 | if cert_log in data: |
---|
311 | data = data.replace(cert_log, b'') |
---|
312 | out_stream.send(data) |
---|
313 | if event & select.POLLHUP or event & select.POLLRDHUP: |
---|
314 | # Stop the loop, but process any other events that |
---|
315 | # might be in the list returned by poll() first. |
---|
316 | run_loop = False |
---|
317 | |
---|
318 | in_stream.close() |
---|
319 | out_stream.close() |
---|
320 | |
---|
321 | |
---|
322 | |
---|
323 | def format_response(resp, body): |
---|
324 | s = f'{resp.status} {resp.reason}\n' |
---|
325 | s = s + '\n'.join(f'{name}: {value}' for name, value in resp.getheaders()) |
---|
326 | s = s + '\n\n' + body |
---|
327 | return s |
---|
328 | |
---|
329 | |
---|
330 | |
---|
331 | if __name__ == "__main__": |
---|
332 | import argparse |
---|
333 | parser = argparse.ArgumentParser( |
---|
334 | description='Send HTTP requests through gnutls-cli', |
---|
335 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
---|
336 | parser.add_argument('host', nargs='?', help='Access the specified host', |
---|
337 | default='localhost') |
---|
338 | parser.add_argument('-p', '--port', type=int, |
---|
339 | help='Access the specified port', default='8000') |
---|
340 | parser.add_argument('--test-config', type=argparse.FileType('r'), |
---|
341 | required=True, help='load YAML test configuration') |
---|
342 | |
---|
343 | # enable bash completion if argcomplete is available |
---|
344 | try: |
---|
345 | import argcomplete |
---|
346 | argcomplete.autocomplete(parser) |
---|
347 | except ImportError: |
---|
348 | pass |
---|
349 | |
---|
350 | args = parser.parse_args() |
---|
351 | |
---|
352 | test_conn = None |
---|
353 | |
---|
354 | config = yaml.load(args.test_config, Loader=yaml.Loader) |
---|
355 | if type(config) is TestConnection: |
---|
356 | test_conn = config |
---|
357 | print(test_conn) |
---|
358 | else: |
---|
359 | raise TypeError(f'Unsupported configuration: {config!r}') |
---|
360 | |
---|
361 | # note: "--logfile" option requires GnuTLS version >= 3.6.7 |
---|
362 | command = ['gnutls-cli', '--logfile=/dev/stderr'] |
---|
363 | for s in test_conn.gnutls_params: |
---|
364 | command.append('--' + s) |
---|
365 | command = command + ['-p', str(args.port), args.host] |
---|
366 | |
---|
367 | conn = HTTPSubprocessConnection(command, args.host, port=args.port, |
---|
368 | output_filter=filter_cert_log, |
---|
369 | timeout=6.0) |
---|
370 | |
---|
371 | try: |
---|
372 | for act in test_conn.actions: |
---|
373 | if type(act) is TestRequest: |
---|
374 | act.run(conn) |
---|
375 | elif type(act) is TestRaw10: |
---|
376 | act.run(command, conn.timeout) |
---|
377 | else: |
---|
378 | raise TypeError(f'Unsupported action requested: {act!r}') |
---|
379 | finally: |
---|
380 | conn.close() |
---|