/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/http_server.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-30 22:17:31 UTC
  • mto: This revision was merged to the branch mainline in revision 6642.
  • Revision ID: jelmer@jelmer.uk-20170530221731-k3djl8mbldt2gmoi
Fix doc generation with sphinx.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
20
20
import posixpath
21
21
import random
22
22
import re
23
 
import select
24
23
import SimpleHTTPServer
25
24
import socket
26
 
import SocketServer
27
 
import sys
28
 
import threading
29
 
import time
30
 
import urllib
31
25
import urlparse
32
26
 
33
 
from bzrlib import transport
34
 
from bzrlib.tests import test_server
35
 
from bzrlib.transport import local
 
27
from .. import (
 
28
    osutils,
 
29
    urlutils,
 
30
)
 
31
from . import test_server
36
32
 
37
33
 
38
34
class BadWebserverPath(ValueError):
71
67
                self.headers.get('referer', '-'),
72
68
                self.headers.get('user-agent', '-'))
73
69
 
 
70
    def handle(self):
 
71
        SimpleHTTPServer.SimpleHTTPRequestHandler.handle(self)
 
72
        # Some client (pycurl, I'm looking at you) are more picky than others
 
73
        # and require that the socket itself is closed
 
74
        # (SocketServer.StreamRequestHandler only close the two associated
 
75
        # 'makefile' objects)
 
76
        self.connection.close()
 
77
 
74
78
    def handle_one_request(self):
75
79
        """Handle a single HTTP request.
76
80
 
78
82
        connection early to avoid polluting the test results.
79
83
        """
80
84
        try:
81
 
            SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
82
 
        except socket.error, e:
 
85
            self._handle_one_request()
 
86
        except socket.error as e:
83
87
            # Any socket error should close the connection, but some errors are
84
88
            # due to the client closing early and we don't want to pollute test
85
89
            # results, so we raise only the others.
89
93
                                     errno.ECONNABORTED, errno.EBADF)):
90
94
                raise
91
95
 
92
 
    _range_regexp = re.compile(r'^(?P<start>\d+)-(?P<end>\d+)$')
 
96
    error_content_type = 'text/plain'
 
97
    error_message_format = '''\
 
98
Error code: %(code)s.
 
99
Message: %(message)s.
 
100
'''
 
101
 
 
102
    def send_error(self, code, message=None):
 
103
        """Send and log an error reply.
 
104
 
 
105
        We redefine the python-provided version to be able to set a 
 
106
        ``Content-Length`` header as some http/1.1 clients complain otherwise
 
107
        (see bug #568421).
 
108
 
 
109
        :param code: The HTTP error code.
 
110
 
 
111
        :param message: The explanation of the error code, Defaults to a short
 
112
             entry.
 
113
        """
 
114
 
 
115
        if message is None:
 
116
            try:
 
117
                message = self.responses[code][0]
 
118
            except KeyError:
 
119
                message = '???'
 
120
        self.log_error("code %d, message %s", code, message)
 
121
        content = (self.error_message_format %
 
122
                   {'code': code, 'message': message})
 
123
        self.send_response(code, message)
 
124
        self.send_header("Content-Type", self.error_content_type)
 
125
        self.send_header("Content-Length", "%d" % len(content))
 
126
        self.send_header('Connection', 'close')
 
127
        self.end_headers()
 
128
        if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
 
129
            self.wfile.write(content)
 
130
 
 
131
    def _handle_one_request(self):
 
132
        SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
 
133
 
 
134
    _range_regexp = re.compile(r'^(?P<start>\d+)-(?P<end>\d+)?$')
93
135
    _tail_regexp = re.compile(r'^-(?P<tail>\d+)$')
94
136
 
95
 
    def parse_ranges(self, ranges_header):
96
 
        """Parse the range header value and returns ranges and tail.
97
 
 
98
 
        RFC2616 14.35 says that syntactically invalid range
99
 
        specifiers MUST be ignored. In that case, we return 0 for
100
 
        tail and [] for ranges.
 
137
    def _parse_ranges(self, ranges_header, file_size):
 
138
        """Parse the range header value and returns ranges.
 
139
 
 
140
        RFC2616 14.35 says that syntactically invalid range specifiers MUST be
 
141
        ignored. In that case, we return None instead of a range list.
 
142
 
 
143
        :param ranges_header: The 'Range' header value.
 
144
 
 
145
        :param file_size: The size of the requested file.
 
146
 
 
147
        :return: A list of (start, end) tuples or None if some invalid range
 
148
            specifier is encountered.
101
149
        """
102
 
        tail = 0
103
 
        ranges = []
104
150
        if not ranges_header.startswith('bytes='):
105
151
            # Syntactically invalid header
106
 
            return 0, []
 
152
            return None
107
153
 
 
154
        tail = None
 
155
        ranges = []
108
156
        ranges_header = ranges_header[len('bytes='):]
109
157
        for range_str in ranges_header.split(','):
110
 
            # FIXME: RFC2616 says end is optional and default to file_size
111
158
            range_match = self._range_regexp.match(range_str)
112
159
            if range_match is not None:
113
160
                start = int(range_match.group('start'))
114
 
                end = int(range_match.group('end'))
 
161
                end_match = range_match.group('end')
 
162
                if end_match is None:
 
163
                    # RFC2616 says end is optional and default to file_size
 
164
                    end = file_size
 
165
                else:
 
166
                    end = int(end_match)
115
167
                if start > end:
116
168
                    # Syntactically invalid range
117
 
                    return 0, []
 
169
                    return None
118
170
                ranges.append((start, end))
119
171
            else:
120
172
                tail_match = self._tail_regexp.match(range_str)
122
174
                    tail = int(tail_match.group('tail'))
123
175
                else:
124
176
                    # Syntactically invalid range
125
 
                    return 0, []
126
 
        return tail, ranges
 
177
                    return None
 
178
        if tail is not None:
 
179
            # Normalize tail into ranges
 
180
            ranges.append((max(0, file_size - tail), file_size))
 
181
 
 
182
        checked_ranges = []
 
183
        for start, end in ranges:
 
184
            if start >= file_size:
 
185
                # RFC2616 14.35, ranges are invalid if start >= file_size
 
186
                return None
 
187
            # RFC2616 14.35, end values should be truncated
 
188
            # to file_size -1 if they exceed it
 
189
            end = min(end, file_size - 1)
 
190
            checked_ranges.append((start, end))
 
191
        return checked_ranges
127
192
 
128
193
    def _header_line_length(self, keyword, value):
129
194
        header_line = '%s: %s\r\n' % (keyword, value)
213
278
            # mode may cause newline translations, making the
214
279
            # actual size of the content transmitted *less* than
215
280
            # the content-length!
216
 
            file = open(path, 'rb')
 
281
            f = open(path, 'rb')
217
282
        except IOError:
218
283
            self.send_error(404, "File not found")
219
284
            return
220
285
 
221
 
        file_size = os.fstat(file.fileno())[6]
222
 
        tail, ranges = self.parse_ranges(ranges_header_value)
223
 
        # Normalize tail into ranges
224
 
        if tail != 0:
225
 
            ranges.append((file_size - tail, file_size))
226
 
 
227
 
        self._satisfiable_ranges = True
228
 
        if len(ranges) == 0:
229
 
            self._satisfiable_ranges = False
230
 
        else:
231
 
            def check_range(range_specifier):
232
 
                start, end = range_specifier
233
 
                # RFC2616 14.35, ranges are invalid if start >= file_size
234
 
                if start >= file_size:
235
 
                    self._satisfiable_ranges = False # Side-effect !
236
 
                    return 0, 0
237
 
                # RFC2616 14.35, end values should be truncated
238
 
                # to file_size -1 if they exceed it
239
 
                end = min(end, file_size - 1)
240
 
                return start, end
241
 
 
242
 
            ranges = map(check_range, ranges)
243
 
 
244
 
        if not self._satisfiable_ranges:
 
286
        file_size = os.fstat(f.fileno())[6]
 
287
        ranges = self._parse_ranges(ranges_header_value, file_size)
 
288
        if not ranges:
245
289
            # RFC2616 14.16 and 14.35 says that when a server
246
290
            # encounters unsatisfiable range specifiers, it
247
291
            # SHOULD return a 416.
248
 
            file.close()
 
292
            f.close()
249
293
            # FIXME: We SHOULD send a Content-Range header too,
250
294
            # but the implementation of send_error does not
251
295
            # allows that. So far.
254
298
 
255
299
        if len(ranges) == 1:
256
300
            (start, end) = ranges[0]
257
 
            self.get_single_range(file, file_size, start, end)
 
301
            self.get_single_range(f, file_size, start, end)
258
302
        else:
259
 
            self.get_multiple_ranges(file, file_size, ranges)
260
 
        file.close()
 
303
            self.get_multiple_ranges(f, file_size, ranges)
 
304
        f.close()
261
305
 
262
306
    def translate_path(self, path):
263
307
        """Translate a /-separated PATH to the local filename syntax.
295
339
        """
296
340
        # abandon query parameters
297
341
        path = urlparse.urlparse(path)[2]
298
 
        path = posixpath.normpath(urllib.unquote(path))
 
342
        path = posixpath.normpath(urlutils.unquote(path))
299
343
        path = path.decode('utf-8')
300
344
        words = path.split('/')
301
 
        words = filter(None, words)
302
345
        path = self._cwd
303
 
        for num, word in enumerate(words):
 
346
        for num, word in enumerate(w for w in words if w):
304
347
            if num == 0:
305
348
                drive, word = os.path.splitdrive(word)
306
349
            head, word = os.path.split(word)
319
362
        self.test_case_server = test_case_server
320
363
        self._home_dir = test_case_server._home_dir
321
364
 
322
 
    def stop_server(self):
323
 
         """Called to clean-up the server.
324
 
 
325
 
         Since the server may be (surely is, even) in a blocking listen, we
326
 
         shutdown its socket before closing it.
327
 
         """
328
 
         # Note that is this executed as part of the implicit tear down in the
329
 
         # main thread while the server runs in its own thread. The clean way
330
 
         # to tear down the server is to instruct him to stop accepting
331
 
         # connections and wait for the current connection(s) to end
332
 
         # naturally. To end the connection naturally, the http transports
333
 
         # should close their socket when they do not need to talk to the
334
 
         # server anymore. This happens naturally during the garbage collection
335
 
         # phase of the test transport objetcs (the server clients), so we
336
 
         # don't have to worry about them.  So, for the server, we must tear
337
 
         # down here, from the main thread, when the test have ended.  Note
338
 
         # that since the server is in a blocking operation and since python
339
 
         # use select internally, shutting down the socket is reliable and
340
 
         # relatively clean.
341
 
         try:
342
 
             self.socket.shutdown(socket.SHUT_RDWR)
343
 
         except socket.error, e:
344
 
             # WSAENOTCONN (10057) 'Socket is not connected' is harmless on
345
 
             # windows (occurs before the first connection attempt
346
 
             # vila--20071230)
347
 
 
348
 
             # 'Socket is not connected' can also occur on OSX, with a
349
 
             # "regular" ENOTCONN (when something went wrong during test case
350
 
             # setup leading to self.setUp() *not* being called but
351
 
             # self.stop_server() still being called -- vila20081106
352
 
             if not len(e.args) or e.args[0] not in (errno.ENOTCONN, 10057):
353
 
                 raise
354
 
         # Let the server properly close the socket
355
 
         self.server_close()
356
 
 
357
 
 
358
 
class TestingHTTPServer(SocketServer.TCPServer, TestingHTTPServerMixin):
 
365
 
 
366
class TestingHTTPServer(test_server.TestingTCPServer, TestingHTTPServerMixin):
359
367
 
360
368
    def __init__(self, server_address, request_handler_class,
361
369
                 test_case_server):
 
370
        test_server.TestingTCPServer.__init__(self, server_address,
 
371
                                              request_handler_class)
362
372
        TestingHTTPServerMixin.__init__(self, test_case_server)
363
 
        SocketServer.TCPServer.__init__(self, server_address,
364
 
                                        request_handler_class)
365
 
 
366
 
 
367
 
class TestingThreadingHTTPServer(SocketServer.ThreadingTCPServer,
 
373
 
 
374
 
 
375
class TestingThreadingHTTPServer(test_server.TestingThreadingTCPServer,
368
376
                                 TestingHTTPServerMixin):
369
377
    """A threading HTTP test server for HTTP 1.1.
370
378
 
372
380
    server, we need an independent connection for each of them. We achieve that
373
381
    by spawning a new thread for each connection.
374
382
    """
375
 
 
376
383
    def __init__(self, server_address, request_handler_class,
377
384
                 test_case_server):
 
385
        test_server.TestingThreadingTCPServer.__init__(self, server_address,
 
386
                                                       request_handler_class)
378
387
        TestingHTTPServerMixin.__init__(self, test_case_server)
379
 
        SocketServer.ThreadingTCPServer.__init__(self, server_address,
380
 
                                                 request_handler_class)
381
 
        # Decides how threads will act upon termination of the main
382
 
        # process. This is prophylactic as we should not leave the threads
383
 
        # lying around.
384
 
        self.daemon_threads = True
385
 
 
386
 
    def process_request_thread(self, request, client_address):
387
 
        SocketServer.ThreadingTCPServer.process_request_thread(
388
 
            self, request, client_address)
389
 
        # Under some circumstances (as in bug #383920), we need to force the
390
 
        # shutdown as python delays it until gc occur otherwise and the client
391
 
        # may hang.
392
 
        try:
393
 
            # The request process has been completed, the thread is about to
394
 
            # die, let's shutdown the socket if we can.
395
 
            request.shutdown(socket.SHUT_RDWR)
396
 
        except (socket.error, select.error), e:
397
 
            if e[0] in (errno.EBADF, errno.ENOTCONN):
398
 
                # Right, the socket is already down
399
 
                pass
400
 
            else:
401
 
                raise
402
 
 
403
 
 
404
 
class HttpServer(transport.Server):
 
388
 
 
389
 
 
390
class HttpServer(test_server.TestingTCPServerInAThread):
405
391
    """A test server for http transports.
406
392
 
407
393
    Subclasses can provide a specific request handler.
429
415
        :param protocol_version: if specified, will override the protocol
430
416
            version of the request handler.
431
417
        """
432
 
        transport.Server.__init__(self)
433
 
        self.request_handler = request_handler
 
418
        # Depending on the protocol version, we will create the approriate
 
419
        # server
 
420
        if protocol_version is None:
 
421
            # Use the request handler one
 
422
            proto_vers = request_handler.protocol_version
 
423
        else:
 
424
            # Use our own, it will be used to override the request handler
 
425
            # one too.
 
426
            proto_vers = protocol_version
 
427
        # Get the appropriate server class for the required protocol
 
428
        serv_cls = self.http_server_class.get(proto_vers, None)
 
429
        if serv_cls is None:
 
430
            raise httplib.UnknownProtocol(proto_vers)
434
431
        self.host = 'localhost'
435
432
        self.port = 0
436
 
        self._httpd = None
437
 
        self.protocol_version = protocol_version
 
433
        super(HttpServer, self).__init__((self.host, self.port),
 
434
                                         serv_cls,
 
435
                                         request_handler)
 
436
        self.protocol_version = proto_vers
438
437
        # Allows tests to verify number of GET requests issued
439
438
        self.GET_request_nb = 0
440
 
 
441
 
    def create_httpd(self, serv_cls, rhandler_cls):
442
 
        return serv_cls((self.host, self.port), self.request_handler, self)
443
 
 
444
 
    def __repr__(self):
445
 
        return "%s(%s:%s)" % \
446
 
            (self.__class__.__name__, self.host, self.port)
447
 
 
448
 
    def _get_httpd(self):
449
 
        if self._httpd is None:
450
 
            rhandler = self.request_handler
451
 
            # Depending on the protocol version, we will create the approriate
452
 
            # server
453
 
            if self.protocol_version is None:
454
 
                # Use the request handler one
455
 
                proto_vers = rhandler.protocol_version
456
 
            else:
457
 
                # Use our own, it will be used to override the request handler
458
 
                # one too.
459
 
                proto_vers = self.protocol_version
460
 
            # Create the appropriate server for the required protocol
461
 
            serv_cls = self.http_server_class.get(proto_vers, None)
462
 
            if serv_cls is None:
463
 
                raise httplib.UnknownProtocol(proto_vers)
464
 
            else:
465
 
                self._httpd = self.create_httpd(serv_cls, rhandler)
466
 
            self.host, self.port = self._httpd.socket.getsockname()
467
 
        return self._httpd
468
 
 
469
 
    def _http_start(self):
470
 
        """Server thread main entry point. """
471
 
        self._http_running = False
472
 
        try:
473
 
            try:
474
 
                httpd = self._get_httpd()
475
 
                self._http_base_url = '%s://%s:%s/' % (self._url_protocol,
476
 
                                                       self.host, self.port)
477
 
                self._http_running = True
478
 
            except:
479
 
                # Whatever goes wrong, we save the exception for the main
480
 
                # thread. Note that since we are running in a thread, no signal
481
 
                # can be received, so we don't care about KeyboardInterrupt.
482
 
                self._http_exception = sys.exc_info()
483
 
        finally:
484
 
            # Release the lock or the main thread will block and the whole
485
 
            # process will hang.
486
 
            self._http_starting.release()
487
 
 
488
 
        # From now on, exceptions are taken care of by the
489
 
        # SocketServer.BaseServer or the request handler.
490
 
        while self._http_running:
491
 
            try:
492
 
                # Really an HTTP connection but the python framework is generic
493
 
                # and call them requests
494
 
                httpd.handle_request()
495
 
            except socket.timeout:
496
 
                pass
497
 
            except (socket.error, select.error), e:
498
 
                if (e[0] == errno.EBADF
499
 
                    or (sys.platform == 'win32' and e[0] == 10038)):
500
 
                    # Starting with python-2.6, handle_request may raise socket
501
 
                    # or select exceptions when the server is shut down (as we
502
 
                    # do).
503
 
                    # 10038 = WSAENOTSOCK
504
 
                    # http://msdn.microsoft.com/en-us/library/ms740668%28VS.85%29.aspx
505
 
                    pass
506
 
                else:
507
 
                    raise
 
439
        self._http_base_url = None
 
440
        self.logs = []
 
441
 
 
442
    def create_server(self):
 
443
        return self.server_class(
 
444
            (self.host, self.port), self.request_handler_class, self)
508
445
 
509
446
    def _get_remote_url(self, path):
510
447
        path_parts = path.split(os.path.sep)
523
460
        self.logs.append(format % args)
524
461
 
525
462
    def start_server(self, backing_transport_server=None):
526
 
        """See bzrlib.transport.Server.start_server.
 
463
        """See breezy.transport.Server.start_server.
527
464
 
528
465
        :param backing_transport_server: The transport that requests over this
529
466
            protocol should be forwarded to. Note that this is currently not
535
472
                or isinstance(backing_transport_server,
536
473
                              test_server.LocalURLServer)):
537
474
            raise AssertionError(
538
 
                "HTTPServer currently assumes local transport, got %s" % \
 
475
                "HTTPServer currently assumes local transport, got %s" %
539
476
                backing_transport_server)
540
 
        self._home_dir = os.getcwdu()
 
477
        self._home_dir = osutils.getcwd()
541
478
        self._local_path_parts = self._home_dir.split(os.path.sep)
542
 
        self._http_base_url = None
543
 
 
544
 
        # Create the server thread
545
 
        self._http_starting = threading.Lock()
546
 
        self._http_starting.acquire()
547
 
        self._http_thread = threading.Thread(target=self._http_start)
548
 
        self._http_thread.setDaemon(True)
549
 
        self._http_exception = None
550
 
        self._http_thread.start()
551
 
 
552
 
        # Wait for the server thread to start (i.e release the lock)
553
 
        self._http_starting.acquire()
554
 
 
555
 
        if self._http_exception is not None:
556
 
            # Something went wrong during server start
557
 
            exc_class, exc_value, exc_tb = self._http_exception
558
 
            raise exc_class, exc_value, exc_tb
559
 
        self._http_starting.release()
560
479
        self.logs = []
561
480
 
562
 
    def stop_server(self):
563
 
        self._httpd.stop_server()
564
 
        self._http_running = False
565
 
        # We don't need to 'self._http_thread.join()' here since the thread is
566
 
        # a daemonic one and will be garbage collected anyway. Joining just
567
 
        # slows us down for no added benefit.
 
481
        super(HttpServer, self).start_server()
 
482
        self._http_base_url = '%s://%s:%s/' % (
 
483
            self._url_protocol, self.host, self.port)
568
484
 
569
485
    def get_url(self):
570
 
        """See bzrlib.transport.Server.get_url."""
 
486
        """See breezy.transport.Server.get_url."""
571
487
        return self._get_remote_url(self._home_dir)
572
488
 
573
489
    def get_bogus_url(self):
574
 
        """See bzrlib.transport.Server.get_bogus_url."""
 
490
        """See breezy.transport.Server.get_bogus_url."""
575
491
        # this is chosen to try to prevent trouble with proxies, weird dns,
576
492
        # etc
577
493
        return self._url_protocol + '://127.0.0.1:1/'