source: mod_gnutls/test/mgstest/http.py @ a274959

asyncioproxy-ticket
Last change on this file since a274959 was 3deb86e, checked in by Fiona Klute <fiona.klute@…>, 18 months ago

Reorganize imports, remove already done TODO

  • Property mode set to 100644
File size: 5.0 KB
RevLine 
[6d3dc34]1#!/usr/bin/python3
2
3# Copyright 2019 Fiona Klute
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
[0560bb9]17"""HTTP handling components for mod_gnutls tests."""
18
[6d3dc34]19import socket
20import subprocess
[4459cdd]21import sys
[6d3dc34]22
23from http.client import HTTPConnection
[f6d2721]24from threading import Thread
[6d3dc34]25
26class HTTPSubprocessConnection(HTTPConnection):
[0560bb9]27    """An HTTPConnection that transports data through a subprocess instead
28    of a socket. The mod_gnutls test suite uses it to transport data
29    through gnutls-cli instead of the ssl module.
30
31    """
[6d3dc34]32    def __init__(self, command, host, port=None,
33                 output_filter=None,
[3be92d3]34                 stderr_log=None,
[006f91a]35                 timeout=socket.getdefaulttimeout(),
[6d3dc34]36                 blocksize=8192):
37        super(HTTPSubprocessConnection, self).__init__(host, port, timeout,
38                                                       source_address=None,
39                                                       blocksize=blocksize)
40        # "command" must be a list containing binary and command line
41        # parameters
42        self.command = command
43        # This will be the subprocess reference when connected
44        self._sproc = None
45        # The subprocess return code is stored here on close()
46        self.returncode = None
47        # The set_tunnel method of the super class is not supported
48        # (see exception doc)
49        self.set_tunnel = None
50        # This method will be run in a separate process and filter the
51        # stdout of self._sproc. Its arguments are self._sproc.stdout
52        # and the socket back to the HTTP connection (write-only).
53        self._output_filter = output_filter
[3be92d3]54        # If not None, write a copy of the subprocess' stderr to here.
55        self._stderr_log = stderr_log
[f6d2721]56        # output filter thread
57        self._fthread = None
[4459cdd]58        # Error stream handler thread. This is needed to synchronize
59        # output between Python and the subprocess.
60        self._ethread = None
[6d3dc34]61
62    def connect(self):
63        s_local, s_remote = socket.socketpair(socket.AF_UNIX,
64                                              socket.SOCK_STREAM)
65        s_local.settimeout(self.timeout)
66
67        if self._output_filter:
68            self._sproc = subprocess.Popen(self.command, stdout=subprocess.PIPE,
[4459cdd]69                                           stderr=subprocess.PIPE,
[6d3dc34]70                                           stdin=s_remote, close_fds=True,
71                                           bufsize=0)
[f6d2721]72            self._fthread = Thread(target=self._output_filter,
73                                   args=(self._sproc.stdout, s_remote))
74            self._fthread.start()
[6d3dc34]75        else:
76            self._sproc = subprocess.Popen(self.command, stdout=s_remote,
[4459cdd]77                                           stderr=subprocess.PIPE,
[6d3dc34]78                                           stdin=s_remote, close_fds=True,
79                                           bufsize=0)
[4459cdd]80        self._ethread = Thread(target=_stderr_writer,
[3be92d3]81                               args=(self._sproc.stderr, self._stderr_log))
[4459cdd]82        self._ethread.start()
[6d3dc34]83        self.sock = s_local
84
85    def close(self):
86        # close socket to subprocess for writing
87        if self.sock:
88            self.sock.shutdown(socket.SHUT_WR)
89
90        # Wait for the process to stop, send SIGTERM/SIGKILL if
91        # necessary
92        if self._sproc:
93            try:
94                self.returncode = self._sproc.wait(self.timeout)
95            except subprocess.TimeoutExpired:
96                try:
97                    self._sproc.terminate()
98                    self.returncode = self._sproc.wait(self.timeout)
99                except subprocess.TimeoutExpired:
100                    self._sproc.kill()
101                    self.returncode = self._sproc.wait(self.timeout)
102
[f6d2721]103        # filter thread receives HUP on pipe when the subprocess
[6d3dc34]104        # terminates
[f6d2721]105        if self._fthread:
106            self._fthread.join()
[4459cdd]107        if self._ethread:
108            self._ethread.join()
[6d3dc34]109
110        # close the connection in the super class, which also calls
111        # self.sock.close()
112        super().close()
[4459cdd]113
114
115
[3be92d3]116def _stderr_writer(stream, copy=None):
117    """Flush incoming data to sys.stderr, and optionally to "copy".
[4459cdd]118
119    This is a workaround to prevent output from gnutls-cli and the
120    Python interpreter overwriting each other in the test
121    logs. Forcing gnutls-cli stderr through Python ensures
122    synchronization (via global interpreter lock).
[3be92d3]123
[4459cdd]124    """
125    for line in stream:
126        print(line.decode(), file=sys.stderr, end='', flush=True)
[3be92d3]127        if copy:
128            print(line.decode(), file=copy, end='')
Note: See TracBrowser for help on using the repository browser.