File: httpserver.py

package info (click to toggle)
linkchecker 10.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,132 kB
  • sloc: python: 13,154; makefile: 134; sh: 71; xml: 36; sql: 20; javascript: 19; php: 2
file content (305 lines) | stat: -rw-r--r-- 9,253 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Copyright (C) 2004-2014 Bastian Kleineidam
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Define http test support classes for LinkChecker tests.
"""

import html
from http.server import SimpleHTTPRequestHandler, HTTPServer
from http.client import HTTPConnection, HTTPSConnection
import ssl
import time
import threading
import urllib.parse
from io import BytesIO
from . import LinkCheckTest
from .. import get_file


class StoppableHttpRequestHandler(SimpleHTTPRequestHandler):
    """
    HTTP request handler with QUIT stopping the server.
    """

    def do_QUIT(self):
        """
        Send 200 OK response, and set server.stop to True.
        """
        self.send_response(200)
        self.end_headers()
        self.server.stop = True

    def log_message(self, format, *args):
        """
        Logging is disabled.
        """
        pass


# serve .xhtml files as application/xhtml+xml
StoppableHttpRequestHandler.extensions_map.update(
    {".xhtml": "application/xhtml+xml"}
)


class StoppableHttpServer(HTTPServer):
    """
    HTTP server that reacts to self.stop flag.
    """

    def serve_forever(self):
        """
        Handle one request at a time until stopped.
        """
        self.stop = False
        while not self.stop:
            self.handle_request()


class NoQueryHttpRequestHandler(StoppableHttpRequestHandler):
    """
    Handler ignoring the query part of requests and sending dummy directory
    listings.
    """

    def remove_path_query(self):
        """
        Remove everything after a question mark.
        """
        i = self.path.find("?")
        if i != -1:
            self.path = self.path[:i]

    def get_status(self):
        dummy, status = self.path.rsplit("/", 1)
        status = int(status)
        if status in self.responses:
            return status
        return 500

    def do_GET(self):
        """
        Removes query part of GET request.
        """
        self.remove_path_query()
        if "status/" in self.path:
            status = self.get_status()
            self.send_response(status)
            self.end_headers()
            if status >= 200 and status not in (204, 304):
                self.wfile.write(b"testcontent")
        else:
            super().do_GET()

    def do_HEAD(self):
        """
        Removes query part of HEAD request.
        """
        self.remove_path_query()
        if "status/" in self.path:
            self.send_response(self.get_status())
            self.end_headers()
        else:
            super().do_HEAD()

    def list_directory(self, path):
        """Helper to produce a directory listing (absent index.html).

        Return value is either a file object, or None (indicating an
        error).  In either case, the headers are sent, making the
        interface the same as for send_head().

        """
        f = BytesIO()
        f.write(b'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
        f.write(b"<html>\n<title>Dummy directory listing</title>\n")
        f.write(b"<body>\n<h2>Dummy test directory listing</h2>\n")
        f.write(b"<hr>\n<ul>\n")
        list = ["example1.txt", "example2.html", "example3"]
        for name in list:
            displayname = linkname = name
            list_item = '<li><a href="{}">{}</a>\n'.format(
                urllib.parse.quote(linkname),
                html.escape(displayname),
            )
            f.write(list_item.encode())
        f.write(b"</ul>\n<hr>\n</body>\n</html>\n")
        length = f.tell()
        f.seek(0)
        self.send_response(200)
        encoding = "utf-8"
        self.send_header("Content-type", "text/html; charset=%s" % encoding)
        self.send_header("Content-Length", str(length))
        self.end_headers()
        return f


class HttpServerTest(LinkCheckTest):
    """
    Start/stop an HTTP server that can be used for testing.
    """

    def __init__(self, methodName="runTest"):
        """
        Init test class and store default http server port.
        """
        super().__init__(methodName=methodName)
        self.port = None
        self.handler = NoQueryHttpRequestHandler

    def setUp(self, https=False):
        """Start a new HTTP server in a new thread."""
        super().setUp()
        self.port = start_server(self.handler, https)
        assert self.port is not None

    def tearDown(self):
        """Send QUIT request to http server."""
        stop_server(self.port)

    def get_url(self, filename):
        """Get HTTP URL for filename."""
        return "http://localhost:%d/tests/checker/data/%s" % (self.port, filename)


class HttpsServerTest(HttpServerTest):
    """
    Start/stop an HTTPS server that can be used for testing.
    """

    def setUp(self):
        """Start a new HTTPS server in a new thread."""
        super().setUp(https=True)

    def tearDown(self):
        """Send QUIT request to http server."""
        stop_server(self.port, https=True)

    def get_url(self, filename):
        """Get HTTP URL for filename."""
        return "https://localhost:%d/tests/checker/data/%s" % (self.port, filename)


def start_server(handler, https=False):
    """Start an HTTP server thread and return its port number."""
    server_address = ("localhost", 0)
    handler.protocol_version = "HTTP/1.0"
    httpd = StoppableHttpServer(server_address, handler)
    if https:
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(
            get_file("https_cert.pem"), keyfile=get_file("https_key.pem"))
        httpd.socket = context.wrap_socket(
            httpd.socket,
            server_side=True,
        )
    port = httpd.server_port
    t = threading.Thread(None, httpd.serve_forever)
    t.start()
    # wait for server to start up
    while True:
        try:
            if https:
                conn = HTTPSConnection(
                    "localhost:%d" % port, context=ssl._create_unverified_context()
                )
            else:
                conn = HTTPConnection("localhost:%d" % port)
            conn.request("GET", "/")
            conn.getresponse()
            break
        except Exception:
            time.sleep(0.5)
    return port


def stop_server(port, https=False):
    """Stop an HTTP server thread."""
    if https:
        conn = HTTPSConnection(
            "localhost:%d" % port, context=ssl._create_unverified_context()
        )
    else:
        conn = HTTPConnection("localhost:%d" % port)
    conn.request("QUIT", "/")
    conn.getresponse()


def get_cookie(maxage=2000):
    data = (
        ("Comment", "justatest"),
        ("Max-Age", "%d" % maxage),
        ("Path", "/"),
        ("Version", "1"),
        ("Foo", "Bar"),
    )
    return "; ".join(f'{key}="{value}"' for key, value in data)


class CookieRedirectHttpRequestHandler(NoQueryHttpRequestHandler):
    """Handler redirecting certain requests, and setting cookies."""

    def end_headers(self):
        """Send cookie before ending headers."""
        self.send_header("Set-Cookie", get_cookie())
        self.send_header("Set-Cookie", get_cookie(maxage=0))
        super().end_headers()

    def redirect(self):
        """Redirect request."""
        path = self.path.replace("redirect", "newurl")
        self.send_response(302)
        self.send_header("Location", path)
        self.end_headers()

    def redirect_newhost(self):
        """Redirect request to a new host."""
        path = "http://www.example.com/"
        self.send_response(302)
        self.send_header("Location", path)
        self.end_headers()

    def redirect_newscheme(self):
        """Redirect request to a new scheme."""
        if "file" in self.path:
            path = "file:README.md"
        else:
            path = "ftp://example.com/"
        self.send_response(302)
        self.send_header("Location", path)
        self.end_headers()

    def do_GET(self):
        """Handle redirections for GET."""
        if "redirect_newscheme" in self.path:
            self.redirect_newscheme()
        elif "redirect_newhost" in self.path:
            self.redirect_newhost()
        elif "redirect" in self.path:
            self.redirect()
        else:
            super().do_GET()

    def do_HEAD(self):
        """Handle redirections for HEAD."""
        if "redirect_newscheme" in self.path:
            self.redirect_newscheme()
        elif "redirect_newhost" in self.path:
            self.redirect_newhost()
        elif "redirect" in self.path:
            self.redirect()
        else:
            super().do_HEAD()