/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 bzrlib/tests/http_utils.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
from cStringIO import StringIO
18
18
import errno
 
19
from SimpleHTTPServer import SimpleHTTPRequestHandler
19
20
import re
20
21
import socket
21
 
import threading
22
22
import time
23
23
import urllib2
24
24
import urlparse
25
25
 
26
 
 
27
 
from bzrlib import (
28
 
    errors,
29
 
    osutils,
30
 
    tests,
 
26
from bzrlib.osutils import md5
 
27
from bzrlib.smart import protocol
 
28
from bzrlib.tests import TestCaseWithTransport
 
29
from bzrlib.tests.http_server import (
 
30
    HttpServer,
 
31
    TestingHTTPRequestHandler,
31
32
    )
32
 
from bzrlib.smart import medium, protocol
33
 
from bzrlib.tests import http_server
34
33
from bzrlib.transport import (
35
 
    chroot,
36
34
    get_transport,
37
35
    )
38
36
 
39
37
 
40
 
class HTTPServerWithSmarts(http_server.HttpServer):
 
38
class WallRequestHandler(TestingHTTPRequestHandler):
 
39
    """Whatever request comes in, close the connection"""
 
40
 
 
41
    def handle_one_request(self):
 
42
        """Handle a single HTTP request, by abruptly closing the connection"""
 
43
        self.close_connection = 1
 
44
 
 
45
 
 
46
class BadStatusRequestHandler(TestingHTTPRequestHandler):
 
47
    """Whatever request comes in, returns a bad status"""
 
48
 
 
49
    def parse_request(self):
 
50
        """Fakes handling a single HTTP request, returns a bad status"""
 
51
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
52
        try:
 
53
            self.send_response(0, "Bad status")
 
54
            self.end_headers()
 
55
        except socket.error, e:
 
56
            # We don't want to pollute the test results with
 
57
            # spurious server errors while test succeed. In our
 
58
            # case, it may occur that the test has already read
 
59
            # the 'Bad Status' and closed the socket while we are
 
60
            # still trying to send some headers... So the test is
 
61
            # ok, but if we raise the exception, the output is
 
62
            # dirty. So we don't raise, but we close the
 
63
            # connection, just to be safe :)
 
64
            spurious = [errno.EPIPE,
 
65
                        errno.ECONNRESET,
 
66
                        errno.ECONNABORTED,
 
67
                        ]
 
68
            if (len(e.args) > 0) and (e.args[0] in spurious):
 
69
                self.close_connection = 1
 
70
                pass
 
71
            else:
 
72
                raise
 
73
        return False
 
74
 
 
75
 
 
76
class InvalidStatusRequestHandler(TestingHTTPRequestHandler):
 
77
    """Whatever request comes in, returns am invalid status"""
 
78
 
 
79
    def parse_request(self):
 
80
        """Fakes handling a single HTTP request, returns a bad status"""
 
81
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
82
        self.wfile.write("Invalid status line\r\n")
 
83
        return False
 
84
 
 
85
 
 
86
class BadProtocolRequestHandler(TestingHTTPRequestHandler):
 
87
    """Whatever request comes in, returns a bad protocol version"""
 
88
 
 
89
    def parse_request(self):
 
90
        """Fakes handling a single HTTP request, returns a bad status"""
 
91
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
92
        # Returns an invalid protocol version, but curl just
 
93
        # ignores it and those cannot be tested.
 
94
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
 
95
                                           404,
 
96
                                           'Look at my protocol version'))
 
97
        return False
 
98
 
 
99
 
 
100
class ForbiddenRequestHandler(TestingHTTPRequestHandler):
 
101
    """Whatever request comes in, returns a 403 code"""
 
102
 
 
103
    def parse_request(self):
 
104
        """Handle a single HTTP request, by replying we cannot handle it"""
 
105
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
106
        self.send_error(403)
 
107
        return False
 
108
 
 
109
 
 
110
class HTTPServerWithSmarts(HttpServer):
41
111
    """HTTPServerWithSmarts extends the HttpServer with POST methods that will
42
112
    trigger a smart server to execute with a transport rooted at the rootdir of
43
113
    the HTTP server.
44
114
    """
45
115
 
46
 
    def __init__(self, protocol_version=None):
47
 
        http_server.HttpServer.__init__(self, SmartRequestHandler,
48
 
                                        protocol_version=protocol_version)
49
 
 
50
 
 
51
 
class SmartRequestHandler(http_server.TestingHTTPRequestHandler):
52
 
    """Extend TestingHTTPRequestHandler to support smart client POSTs.
53
 
 
54
 
    XXX: This duplicates a fair bit of the logic in bzrlib.transport.http.wsgi.
55
 
    """
 
116
    def __init__(self):
 
117
        HttpServer.__init__(self, SmartRequestHandler)
 
118
 
 
119
 
 
120
class SmartRequestHandler(TestingHTTPRequestHandler):
 
121
    """Extend TestingHTTPRequestHandler to support smart client POSTs."""
56
122
 
57
123
    def do_POST(self):
58
124
        """Hand the request off to a smart server instance."""
59
 
        backing = get_transport(self.server.test_case_server._home_dir)
60
 
        chroot_server = chroot.ChrootServer(backing)
61
 
        chroot_server.start_server()
62
 
        try:
63
 
            t = get_transport(chroot_server.get_url())
64
 
            self.do_POST_inner(t)
65
 
        finally:
66
 
            chroot_server.stop_server()
67
 
 
68
 
    def do_POST_inner(self, chrooted_transport):
69
125
        self.send_response(200)
70
126
        self.send_header("Content-type", "application/octet-stream")
71
 
        if not self.path.endswith('.bzr/smart'):
72
 
            raise AssertionError(
73
 
                'POST to path not ending in .bzr/smart: %r' % (self.path,))
74
 
        t = chrooted_transport.clone(self.path[:-len('.bzr/smart')])
75
 
        # if this fails, we should return 400 bad request, but failure is
76
 
        # failure for now - RBC 20060919
77
 
        data_length = int(self.headers['Content-Length'])
 
127
        transport = get_transport(self.server.test_case_server._home_dir)
78
128
        # TODO: We might like to support streaming responses.  1.0 allows no
79
129
        # Content-length in this case, so for integrity we should perform our
80
130
        # own chunking within the stream.
82
132
        # the HTTP chunking as this will allow HTTP persistence safely, even if
83
133
        # we have to stop early due to error, but we would also have to use the
84
134
        # HTTP trailer facility which may not be widely available.
85
 
        request_bytes = self.rfile.read(data_length)
86
 
        protocol_factory, unused_bytes = medium._get_protocol_factory_for_bytes(
87
 
            request_bytes)
88
135
        out_buffer = StringIO()
89
 
        smart_protocol_request = protocol_factory(t, out_buffer.write, '/')
 
136
        smart_protocol_request = protocol.SmartServerRequestProtocolOne(
 
137
                transport, out_buffer.write)
 
138
        # if this fails, we should return 400 bad request, but failure is
 
139
        # failure for now - RBC 20060919
 
140
        data_length = int(self.headers['Content-Length'])
90
141
        # Perhaps there should be a SmartServerHTTPMedium that takes care of
91
142
        # feeding the bytes in the http request to the smart_protocol_request,
92
143
        # but for now it's simpler to just feed the bytes directly.
93
 
        smart_protocol_request.accept_bytes(unused_bytes)
94
 
        if not (smart_protocol_request.next_read_size() == 0):
95
 
            raise errors.SmartProtocolError(
96
 
                "not finished reading, but all data sent to protocol.")
 
144
        smart_protocol_request.accept_bytes(self.rfile.read(data_length))
 
145
        assert smart_protocol_request.next_read_size() == 0, (
 
146
            "not finished reading, but all data sent to protocol.")
97
147
        self.send_header("Content-Length", str(len(out_buffer.getvalue())))
98
148
        self.end_headers()
99
149
        self.wfile.write(out_buffer.getvalue())
100
150
 
101
151
 
102
 
class TestCaseWithWebserver(tests.TestCaseWithTransport):
 
152
class LimitedRangeRequestHandler(TestingHTTPRequestHandler):
 
153
    """Errors out when range specifiers exceed the limit"""
 
154
 
 
155
    def get_multiple_ranges(self, file, file_size, ranges):
 
156
        """Refuses the multiple ranges request"""
 
157
        tcs = self.server.test_case_server
 
158
        if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
 
159
            file.close()
 
160
            # Emulate apache behavior
 
161
            self.send_error(400, "Bad Request")
 
162
            return
 
163
        return TestingHTTPRequestHandler.get_multiple_ranges(self, file,
 
164
                                                             file_size, ranges)
 
165
 
 
166
 
 
167
class LimitedRangeHTTPServer(HttpServer):
 
168
    """An HttpServer erroring out on requests with too much range specifiers"""
 
169
 
 
170
    def __init__(self, request_handler=LimitedRangeRequestHandler,
 
171
                 range_limit=None):
 
172
        HttpServer.__init__(self, request_handler)
 
173
        self.range_limit = range_limit
 
174
 
 
175
 
 
176
class SingleRangeRequestHandler(TestingHTTPRequestHandler):
 
177
    """Always reply to range request as if they were single.
 
178
 
 
179
    Don't be explicit about it, just to annoy the clients.
 
180
    """
 
181
 
 
182
    def get_multiple_ranges(self, file, file_size, ranges):
 
183
        """Answer as if it was a single range request and ignores the rest"""
 
184
        (start, end) = ranges[0]
 
185
        return self.get_single_range(file, file_size, start, end)
 
186
 
 
187
 
 
188
class SingleOnlyRangeRequestHandler(TestingHTTPRequestHandler):
 
189
    """Only reply to simple range requests, errors out on multiple"""
 
190
 
 
191
    def get_multiple_ranges(self, file, file_size, ranges):
 
192
        """Refuses the multiple ranges request"""
 
193
        if len(ranges) > 1:
 
194
            file.close()
 
195
            self.send_error(416, "Requested range not satisfiable")
 
196
            return
 
197
        (start, end) = ranges[0]
 
198
        return self.get_single_range(file, file_size, start, end)
 
199
 
 
200
 
 
201
class NoRangeRequestHandler(TestingHTTPRequestHandler):
 
202
    """Ignore range requests without notice"""
 
203
 
 
204
    def do_GET(self):
 
205
        # Update the statistics
 
206
        self.server.test_case_server.GET_request_nb += 1
 
207
        # Just bypass the range handling done by TestingHTTPRequestHandler
 
208
        return SimpleHTTPRequestHandler.do_GET(self)
 
209
 
 
210
 
 
211
class TestCaseWithWebserver(TestCaseWithTransport):
103
212
    """A support class that provides readonly urls that are http://.
104
213
 
105
214
    This is done by forcing the readonly server to be an http
108
217
    """
109
218
    def setUp(self):
110
219
        super(TestCaseWithWebserver, self).setUp()
111
 
        self.transport_readonly_server = http_server.HttpServer
 
220
        self.transport_readonly_server = HttpServer
112
221
 
113
222
 
114
223
class TestCaseWithTwoWebservers(TestCaseWithWebserver):
119
228
    """
120
229
    def setUp(self):
121
230
        super(TestCaseWithTwoWebservers, self).setUp()
122
 
        self.transport_secondary_server = http_server.HttpServer
 
231
        self.transport_secondary_server = HttpServer
123
232
        self.__secondary_server = None
124
233
 
125
234
    def create_transport_secondary_server(self):
133
242
        """Get the server instance for the secondary transport."""
134
243
        if self.__secondary_server is None:
135
244
            self.__secondary_server = self.create_transport_secondary_server()
136
 
            self.start_server(self.__secondary_server)
 
245
            self.__secondary_server.setUp()
 
246
            self.addCleanup(self.__secondary_server.tearDown)
137
247
        return self.__secondary_server
138
248
 
139
249
 
140
 
class ProxyServer(http_server.HttpServer):
 
250
class ProxyServer(HttpServer):
141
251
    """A proxy test server for http transports."""
142
252
 
143
253
    proxy_requests = True
144
254
 
145
255
 
146
 
class RedirectRequestHandler(http_server.TestingHTTPRequestHandler):
 
256
class RedirectRequestHandler(TestingHTTPRequestHandler):
147
257
    """Redirect all request to the specified server"""
148
258
 
149
259
    def parse_request(self):
150
260
        """Redirect a single HTTP request to another host"""
151
 
        valid = http_server.TestingHTTPRequestHandler.parse_request(self)
 
261
        valid = TestingHTTPRequestHandler.parse_request(self)
152
262
        if valid:
153
263
            tcs = self.server.test_case_server
154
264
            code, target = tcs.is_redirected(self.path)
156
266
                # Redirect as instructed
157
267
                self.send_response(code)
158
268
                self.send_header('Location', target)
159
 
                # We do not send a body
160
 
                self.send_header('Content-Length', '0')
161
269
                self.end_headers()
162
270
                return False # The job is done
163
271
            else:
166
274
        return valid
167
275
 
168
276
 
169
 
class HTTPServerRedirecting(http_server.HttpServer):
 
277
class HTTPServerRedirecting(HttpServer):
170
278
    """An HttpServer redirecting to another server """
171
279
 
172
 
    def __init__(self, request_handler=RedirectRequestHandler,
173
 
                 protocol_version=None):
174
 
        http_server.HttpServer.__init__(self, request_handler,
175
 
                                        protocol_version=protocol_version)
 
280
    def __init__(self, request_handler=RedirectRequestHandler):
 
281
        HttpServer.__init__(self, request_handler)
176
282
        # redirections is a list of tuples (source, target, code)
177
283
        # - source is a regexp for the paths requested
178
284
        # - target is a replacement for re.sub describing where
230
336
       self.old_server = self.get_secondary_server()
231
337
 
232
338
 
233
 
class AuthRequestHandler(http_server.TestingHTTPRequestHandler):
 
339
class AuthRequestHandler(TestingHTTPRequestHandler):
234
340
    """Requires an authentication to process requests.
235
341
 
236
342
    This is intended to be used with a server that always and
245
351
 
246
352
    def do_GET(self):
247
353
        if self.authorized():
248
 
            return http_server.TestingHTTPRequestHandler.do_GET(self)
 
354
            return TestingHTTPRequestHandler.do_GET(self)
249
355
        else:
250
356
            # Note that we must update test_case_server *before*
251
357
            # sending the error or the client may try to read it
254
360
            tcs.auth_required_errors += 1
255
361
            self.send_response(tcs.auth_error_code)
256
362
            self.send_header_auth_reqed()
257
 
            # We do not send a body
258
 
            self.send_header('Content-Length', '0')
259
363
            self.end_headers()
260
364
            return
261
365
 
296
400
 
297
401
    def authorized(self):
298
402
        tcs = self.server.test_case_server
 
403
        if tcs.auth_scheme != 'digest':
 
404
            return False
299
405
 
300
406
        auth_header = self.headers.get(tcs.auth_header_recv, None)
301
407
        if auth_header is None:
316
422
        self.send_header(tcs.auth_header_sent,header)
317
423
 
318
424
 
319
 
class DigestAndBasicAuthRequestHandler(DigestAuthRequestHandler):
320
 
    """Implements a digest and basic authentication of a request.
321
 
 
322
 
    I.e. the server proposes both schemes and the client should choose the best
323
 
    one it can handle, which, in that case, should be digest, the only scheme
324
 
    accepted here.
325
 
    """
326
 
 
327
 
    def send_header_auth_reqed(self):
328
 
        tcs = self.server.test_case_server
329
 
        self.send_header(tcs.auth_header_sent,
330
 
                         'Basic realm="%s"' % tcs.auth_realm)
331
 
        header = 'Digest realm="%s", ' % tcs.auth_realm
332
 
        header += 'nonce="%s", algorithm="%s", qop="auth"' % (tcs.auth_nonce,
333
 
                                                              'MD5')
334
 
        self.send_header(tcs.auth_header_sent,header)
335
 
 
336
 
 
337
 
class AuthServer(http_server.HttpServer):
 
425
class AuthServer(HttpServer):
338
426
    """Extends HttpServer with a dictionary of passwords.
339
427
 
340
428
    This is used as a base class for various schemes which should
351
439
    auth_error_code = None
352
440
    auth_realm = "Thou should not pass"
353
441
 
354
 
    def __init__(self, request_handler, auth_scheme,
355
 
                 protocol_version=None):
356
 
        http_server.HttpServer.__init__(self, request_handler,
357
 
                                        protocol_version=protocol_version)
 
442
    def __init__(self, request_handler, auth_scheme):
 
443
        HttpServer.__init__(self, request_handler)
358
444
        self.auth_scheme = auth_scheme
359
445
        self.password_of = {}
360
446
        self.auth_required_errors = 0
383
469
 
384
470
    auth_nonce = 'now!'
385
471
 
386
 
    def __init__(self, request_handler, auth_scheme,
387
 
                 protocol_version=None):
388
 
        AuthServer.__init__(self, request_handler, auth_scheme,
389
 
                            protocol_version=protocol_version)
 
472
    def __init__(self, request_handler, auth_scheme):
 
473
        AuthServer.__init__(self, request_handler, auth_scheme)
390
474
 
391
475
    def digest_authorized(self, auth, command):
392
476
        nonce = auth['nonce']
412
496
        A1 = '%s:%s:%s' % (user, realm, password)
413
497
        A2 = '%s:%s' % (command, auth['uri'])
414
498
 
415
 
        H = lambda x: osutils.md5(x).hexdigest()
 
499
        H = lambda x: md5(x).hexdigest()
416
500
        KD = lambda secret, data: H("%s:%s" % (secret, data))
417
501
 
418
502
        nonce_count = int(auth['nc'], 16)
425
509
 
426
510
        return response_digest == auth['response']
427
511
 
428
 
 
429
512
class HTTPAuthServer(AuthServer):
430
513
    """An HTTP server requiring authentication"""
431
514
 
448
531
class HTTPBasicAuthServer(HTTPAuthServer):
449
532
    """An HTTP server requiring basic authentication"""
450
533
 
451
 
    def __init__(self, protocol_version=None):
452
 
        HTTPAuthServer.__init__(self, BasicAuthRequestHandler, 'basic',
453
 
                                protocol_version=protocol_version)
 
534
    def __init__(self):
 
535
        HTTPAuthServer.__init__(self, BasicAuthRequestHandler, 'basic')
454
536
        self.init_http_auth()
455
537
 
456
538
 
457
539
class HTTPDigestAuthServer(DigestAuthServer, HTTPAuthServer):
458
540
    """An HTTP server requiring digest authentication"""
459
541
 
460
 
    def __init__(self, protocol_version=None):
461
 
        DigestAuthServer.__init__(self, DigestAuthRequestHandler, 'digest',
462
 
                                  protocol_version=protocol_version)
463
 
        self.init_http_auth()
464
 
 
465
 
 
466
 
class HTTPBasicAndDigestAuthServer(DigestAuthServer, HTTPAuthServer):
467
 
    """An HTTP server requiring basic or digest authentication"""
468
 
 
469
 
    def __init__(self, protocol_version=None):
470
 
        DigestAuthServer.__init__(self, DigestAndBasicAuthRequestHandler,
471
 
                                  'basicdigest',
472
 
                                  protocol_version=protocol_version)
473
 
        self.init_http_auth()
474
 
        # We really accept Digest only
475
 
        self.auth_scheme = 'digest'
 
542
    def __init__(self):
 
543
        DigestAuthServer.__init__(self, DigestAuthRequestHandler, 'digest')
 
544
        self.init_http_auth()
476
545
 
477
546
 
478
547
class ProxyBasicAuthServer(ProxyAuthServer):
479
548
    """A proxy server requiring basic authentication"""
480
549
 
481
 
    def __init__(self, protocol_version=None):
482
 
        ProxyAuthServer.__init__(self, BasicAuthRequestHandler, 'basic',
483
 
                                 protocol_version=protocol_version)
 
550
    def __init__(self):
 
551
        ProxyAuthServer.__init__(self, BasicAuthRequestHandler, 'basic')
484
552
        self.init_proxy_auth()
485
553
 
486
554
 
487
555
class ProxyDigestAuthServer(DigestAuthServer, ProxyAuthServer):
488
556
    """A proxy server requiring basic authentication"""
489
557
 
490
 
    def __init__(self, protocol_version=None):
491
 
        ProxyAuthServer.__init__(self, DigestAuthRequestHandler, 'digest',
492
 
                                 protocol_version=protocol_version)
493
 
        self.init_proxy_auth()
494
 
 
495
 
 
496
 
class ProxyBasicAndDigestAuthServer(DigestAuthServer, ProxyAuthServer):
497
 
    """An proxy server requiring basic or digest authentication"""
498
 
 
499
 
    def __init__(self, protocol_version=None):
500
 
        DigestAuthServer.__init__(self, DigestAndBasicAuthRequestHandler,
501
 
                                  'basicdigest',
502
 
                                  protocol_version=protocol_version)
503
 
        self.init_proxy_auth()
504
 
        # We really accept Digest only
505
 
        self.auth_scheme = 'digest'
 
558
    def __init__(self):
 
559
        ProxyAuthServer.__init__(self, DigestAuthRequestHandler, 'digest')
 
560
        self.init_proxy_auth()
506
561
 
507
562