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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Basic server-side logic for dealing with requests.
21
The class names are a little confusing: the protocol will instantiate a
22
SmartServerRequestHandler, whose dispatch_command method creates an instance of
23
a SmartServerRequest subclass.
25
The request_handlers registry tracks SmartServerRequest classes (rather than
26
SmartServerRequestHandler).
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Infrastructure for server-side request handlers.
19
Interesting module attributes:
20
* The request_handlers registry maps verb names to SmartServerRequest
22
* The jail_info threading.local() object is used to prevent accidental
23
opening of BzrDirs outside of the backing transport, or any other
24
transports placed in jail_info.transports. The jail_info is reset on
25
every call into a request handler (which can happen an arbitrary number
26
of times during a request).
29
# XXX: The class names are a little confusing: the protocol will instantiate a
30
# SmartServerRequestHandler, whose dispatch_command method creates an instance
31
# of a SmartServerRequest subclass.
31
38
from bzrlib import (
38
from bzrlib.bundle.serializer import write_bundle
48
from bzrlib.lazy_import import lazy_import
49
lazy_import(globals(), """
50
from bzrlib.bundle import serializer
54
jail_info = threading.local()
55
jail_info.transports = None
59
bzrdir.BzrDir.hooks.install_named_hook(
60
'pre_open', _pre_open_hook, 'checking server jail')
63
def _pre_open_hook(transport):
64
allowed_transports = getattr(jail_info, 'transports', None)
65
if allowed_transports is None:
67
abspath = transport.base
68
for allowed_transport in allowed_transports:
70
allowed_transport.relpath(abspath)
71
except errors.PathNotChild:
75
raise errors.JailBreak(abspath)
41
81
class SmartServerRequest(object):
42
82
"""Base class for request handlers.
44
84
To define a new request, subclass this class and override the `do` method
45
85
(and if appropriate, `do_body` as well). Request implementors should take
46
86
care to call `translate_client_path` and `transport_from_client_path` as
97
143
"""Called if the client sends a body with the request.
99
145
The do() method is still called, and must have returned None.
101
147
Must return a SmartServerResponse.
103
raise NotImplementedError(self.do_body)
150
raise errors.SmartProtocolError('Request does not expect a body')
105
152
def do_chunk(self, chunk_bytes):
106
153
"""Called with each body chunk if the request has a streamed body.
108
155
The do() method is still called, and must have returned None.
110
raise NotImplementedError(self.do_chunk)
157
self._body_chunks.append(chunk_bytes)
112
159
def do_end(self):
113
160
"""Called when the end of the request has been received."""
161
body_bytes = ''.join(self._body_chunks)
162
self._body_chunks = None
163
return self.do_body(body_bytes)
165
def setup_jail(self):
166
jail_info.transports = [self._jail_root]
168
def teardown_jail(self):
169
jail_info.transports = None
116
171
def translate_client_path(self, client_path):
117
172
"""Translate a path received from a network client into a local
227
284
self._backing_transport = backing_transport
228
285
self._root_client_path = root_client_path
229
286
self._commands = commands
230
self._body_bytes = ''
287
if jail_root is None:
288
jail_root = backing_transport
289
self._jail_root = jail_root
231
290
self.response = None
232
291
self.finished_reading = False
233
292
self._command = None
293
if 'hpss' in debug.debug_flags:
294
self._request_start_time = osutils.timer_func()
295
self._thread_id = thread.get_ident()
297
def _trace(self, action, message, extra_bytes=None, include_time=False):
298
# It is a bit of a shame that this functionality overlaps with that of
299
# ProtocolThreeRequester._trace. However, there is enough difference
300
# that just putting it in a helper doesn't help a lot. And some state
301
# is taken from the instance.
303
t = '%5.3fs ' % (osutils.timer_func() - self._request_start_time)
306
if extra_bytes is None:
309
extra = ' ' + repr(extra_bytes[:40])
311
extra = extra[:29] + extra[-1] + '...'
312
trace.mutter('%12s: [%s] %s%s%s'
313
% (action, self._thread_id, t, message, extra))
235
315
def accept_body(self, bytes):
236
316
"""Accept body data."""
238
# TODO: This should be overriden for each command that desired body data
239
# to handle the right format of that data, i.e. plain bytes, a bundle,
240
# etc. The deserialisation into that format should be done in the
243
# default fallback is to accumulate bytes.
244
self._body_bytes += bytes
317
if self._command is None:
318
# no active command object, so ignore the event.
320
self._run_handler_code(self._command.do_chunk, (bytes,), {})
321
if 'hpss' in debug.debug_flags:
322
self._trace('accept body',
323
'%d bytes' % (len(bytes),), bytes)
246
325
def end_of_body(self):
247
326
"""No more body data will be received."""
248
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
327
self._run_handler_code(self._command.do_end, (), {})
249
328
# cannot read after this.
250
329
self.finished_reading = True
252
def dispatch_command(self, cmd, args):
253
"""Deprecated compatibility method.""" # XXX XXX
255
command = self._commands.get(cmd)
257
raise errors.UnknownSmartMethod(cmd)
258
self._command = command(self._backing_transport, self._root_client_path)
259
self._run_handler_code(self._command.execute, args, {})
330
if 'hpss' in debug.debug_flags:
331
self._trace('end of body', '', include_time=True)
261
333
def _run_handler_code(self, callable, args, kwargs):
262
334
"""Run some handler specific code 'callable'.
278
350
# XXX: most of this error conversion is VFS-related, and thus ought to
279
351
# be in SmartServerVFSRequestHandler somewhere.
281
return callable(*args, **kwargs)
282
except errors.NoSuchFile, e:
283
return FailedSmartServerResponse(('NoSuchFile', e.path))
284
except errors.FileExists, e:
285
return FailedSmartServerResponse(('FileExists', e.path))
286
except errors.DirectoryNotEmpty, e:
287
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
288
except errors.ShortReadvError, e:
289
return FailedSmartServerResponse(('ShortReadvError',
290
e.path, str(e.offset), str(e.length), str(e.actual)))
291
except UnicodeError, e:
292
# If it is a DecodeError, than most likely we are starting
293
# with a plain string
294
str_or_unicode = e.object
295
if isinstance(str_or_unicode, unicode):
296
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
297
# should escape it somehow.
298
val = 'u:' + str_or_unicode.encode('utf-8')
300
val = 's:' + str_or_unicode.encode('base64')
301
# This handles UnicodeEncodeError or UnicodeDecodeError
302
return FailedSmartServerResponse((e.__class__.__name__,
303
e.encoding, val, str(e.start), str(e.end), e.reason))
304
except errors.TransportNotPossible, e:
305
if e.msg == "readonly transport":
306
return FailedSmartServerResponse(('ReadOnlyError', ))
353
self._command.setup_jail()
355
return callable(*args, **kwargs)
357
self._command.teardown_jail()
358
except (KeyboardInterrupt, SystemExit):
360
except Exception, err:
361
err_struct = _translate_error(err)
362
return FailedSmartServerResponse(err_struct)
310
364
def headers_received(self, headers):
311
365
# Just a no-op at the moment.
366
if 'hpss' in debug.debug_flags:
367
self._trace('headers', repr(headers))
314
369
def args_received(self, args):
318
373
command = self._commands.get(cmd)
319
374
except LookupError:
375
if 'hpss' in debug.debug_flags:
376
self._trace('hpss unknown request',
377
cmd, repr(args)[1:-1])
320
378
raise errors.UnknownSmartMethod(cmd)
321
self._command = command(self._backing_transport)
379
if 'hpss' in debug.debug_flags:
380
from bzrlib.smart import vfs
381
if issubclass(command, vfs.VfsRequest):
382
action = 'hpss vfs req'
384
action = 'hpss request'
386
'%s %s' % (cmd, repr(args)[1:-1]))
387
self._command = command(
388
self._backing_transport, self._root_client_path, self._jail_root)
322
389
self._run_handler_code(self._command.execute, args, {})
324
def prefixed_body_received(self, body_bytes):
325
"""No more body data will be received."""
326
self._run_handler_code(self._command.do_body, (body_bytes,), {})
327
# cannot read after this.
328
self.finished_reading = True
330
def body_chunk_received(self, chunk_bytes):
331
self._run_handler_code(self._command.do_chunk, (chunk_bytes,), {})
333
391
def end_received(self):
392
if self._command is None:
393
# no active command object, so ignore the event.
334
395
self._run_handler_code(self._command.do_end, (), {})
396
if 'hpss' in debug.debug_flags:
397
self._trace('end', '', include_time=True)
399
def post_body_error_received(self, error_args):
400
# Just a no-op at the moment.
404
def _translate_error(err):
405
if isinstance(err, errors.NoSuchFile):
406
return ('NoSuchFile', err.path)
407
elif isinstance(err, errors.FileExists):
408
return ('FileExists', err.path)
409
elif isinstance(err, errors.DirectoryNotEmpty):
410
return ('DirectoryNotEmpty', err.path)
411
elif isinstance(err, errors.IncompatibleRepositories):
412
return ('IncompatibleRepositories', str(err.source), str(err.target),
414
elif isinstance(err, errors.ShortReadvError):
415
return ('ShortReadvError', err.path, str(err.offset), str(err.length),
417
elif isinstance(err, errors.UnstackableRepositoryFormat):
418
return (('UnstackableRepositoryFormat', str(err.format), err.url))
419
elif isinstance(err, errors.UnstackableBranchFormat):
420
return ('UnstackableBranchFormat', str(err.format), err.url)
421
elif isinstance(err, errors.NotStacked):
422
return ('NotStacked',)
423
elif isinstance(err, UnicodeError):
424
# If it is a DecodeError, than most likely we are starting
425
# with a plain string
426
str_or_unicode = err.object
427
if isinstance(str_or_unicode, unicode):
428
# XXX: UTF-8 might have \x01 (our protocol v1 and v2 seperator
429
# byte) in it, so this encoding could cause broken responses.
430
# Newer clients use protocol v3, so will be fine.
431
val = 'u:' + str_or_unicode.encode('utf-8')
433
val = 's:' + str_or_unicode.encode('base64')
434
# This handles UnicodeEncodeError or UnicodeDecodeError
435
return (err.__class__.__name__, err.encoding, val, str(err.start),
436
str(err.end), err.reason)
437
elif isinstance(err, errors.TransportNotPossible):
438
if err.msg == "readonly transport":
439
return ('ReadOnlyError', )
440
elif isinstance(err, errors.ReadError):
441
# cannot read the file
442
return ('ReadError', err.path)
443
elif isinstance(err, errors.PermissionDenied):
444
return ('PermissionDenied', err.path, err.extra)
445
elif isinstance(err, errors.TokenMismatch):
446
return ('TokenMismatch', err.given_token, err.lock_token)
447
elif isinstance(err, errors.LockContention):
448
return ('LockContention',)
449
# Unserialisable error. Log it, and return a generic error
450
trace.log_exception_quietly()
451
return ('error', str(err))
337
454
class HelloRequest(SmartServerRequest):
373
490
request_handlers.register_lazy(
374
491
'append', 'bzrlib.smart.vfs', 'AppendRequest')
375
492
request_handlers.register_lazy(
376
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
493
'Branch.get_config_file', 'bzrlib.smart.branch',
494
'SmartServerBranchGetConfigFile')
495
request_handlers.register_lazy(
496
'Branch.get_parent', 'bzrlib.smart.branch', 'SmartServerBranchGetParent')
497
request_handlers.register_lazy(
498
'Branch.get_tags_bytes', 'bzrlib.smart.branch',
499
'SmartServerBranchGetTagsBytes')
500
request_handlers.register_lazy(
501
'Branch.set_tags_bytes', 'bzrlib.smart.branch',
502
'SmartServerBranchSetTagsBytes')
503
request_handlers.register_lazy(
504
'Branch.get_stacked_on_url', 'bzrlib.smart.branch', 'SmartServerBranchRequestGetStackedOnURL')
377
505
request_handlers.register_lazy(
378
506
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
379
507
request_handlers.register_lazy(
380
508
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
381
request_handlers.register_lazy(
382
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
383
request_handlers.register_lazy(
384
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
509
request_handlers.register_lazy( 'Branch.revision_history',
510
'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
511
request_handlers.register_lazy( 'Branch.set_config_option',
512
'bzrlib.smart.branch', 'SmartServerBranchRequestSetConfigOption')
513
request_handlers.register_lazy( 'Branch.set_last_revision',
514
'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
385
515
request_handlers.register_lazy(
386
516
'Branch.set_last_revision_info', 'bzrlib.smart.branch',
387
517
'SmartServerBranchRequestSetLastRevisionInfo')
389
519
'Branch.set_last_revision_ex', 'bzrlib.smart.branch',
390
520
'SmartServerBranchRequestSetLastRevisionEx')
391
521
request_handlers.register_lazy(
522
'Branch.set_parent_location', 'bzrlib.smart.branch',
523
'SmartServerBranchRequestSetParentLocation')
524
request_handlers.register_lazy(
392
525
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
393
526
request_handlers.register_lazy(
394
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV1')
395
request_handlers.register_lazy(
396
'BzrDir.find_repositoryV2', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV2')
397
request_handlers.register_lazy(
398
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
399
request_handlers.register_lazy(
400
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
527
'BzrDir.cloning_metadir', 'bzrlib.smart.bzrdir',
528
'SmartServerBzrDirRequestCloningMetaDir')
529
request_handlers.register_lazy(
530
'BzrDir.create_branch', 'bzrlib.smart.bzrdir',
531
'SmartServerRequestCreateBranch')
532
request_handlers.register_lazy(
533
'BzrDir.create_repository', 'bzrlib.smart.bzrdir',
534
'SmartServerRequestCreateRepository')
535
request_handlers.register_lazy(
536
'BzrDir.find_repository', 'bzrlib.smart.bzrdir',
537
'SmartServerRequestFindRepositoryV1')
538
request_handlers.register_lazy(
539
'BzrDir.find_repositoryV2', 'bzrlib.smart.bzrdir',
540
'SmartServerRequestFindRepositoryV2')
541
request_handlers.register_lazy(
542
'BzrDir.find_repositoryV3', 'bzrlib.smart.bzrdir',
543
'SmartServerRequestFindRepositoryV3')
544
request_handlers.register_lazy(
545
'BzrDir.get_config_file', 'bzrlib.smart.bzrdir',
546
'SmartServerBzrDirRequestConfigFile')
547
request_handlers.register_lazy(
548
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir',
549
'SmartServerRequestInitializeBzrDir')
550
request_handlers.register_lazy(
551
'BzrDirFormat.initialize_ex_1.16', 'bzrlib.smart.bzrdir',
552
'SmartServerRequestBzrDirInitializeEx')
553
request_handlers.register_lazy(
554
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')
555
request_handlers.register_lazy(
556
'BzrDir.open_2.1', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir_2_1')
557
request_handlers.register_lazy(
558
'BzrDir.open_branch', 'bzrlib.smart.bzrdir',
559
'SmartServerRequestOpenBranch')
560
request_handlers.register_lazy(
561
'BzrDir.open_branchV2', 'bzrlib.smart.bzrdir',
562
'SmartServerRequestOpenBranchV2')
563
request_handlers.register_lazy(
564
'BzrDir.open_branchV3', 'bzrlib.smart.bzrdir',
565
'SmartServerRequestOpenBranchV3')
401
566
request_handlers.register_lazy(
402
567
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
403
568
request_handlers.register_lazy(
435
603
request_handlers.register_lazy(
436
604
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
437
605
request_handlers.register_lazy(
606
'Repository.insert_stream', 'bzrlib.smart.repository', 'SmartServerRepositoryInsertStream')
607
request_handlers.register_lazy(
608
'Repository.insert_stream_1.19', 'bzrlib.smart.repository', 'SmartServerRepositoryInsertStream_1_19')
609
request_handlers.register_lazy(
610
'Repository.insert_stream_locked', 'bzrlib.smart.repository', 'SmartServerRepositoryInsertStreamLocked')
611
request_handlers.register_lazy(
438
612
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
439
613
request_handlers.register_lazy(
440
614
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
441
615
request_handlers.register_lazy(
616
'Repository.set_make_working_trees', 'bzrlib.smart.repository',
617
'SmartServerRepositorySetMakeWorkingTrees')
618
request_handlers.register_lazy(
442
619
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
443
620
request_handlers.register_lazy(
621
'Repository.get_rev_id_for_revno', 'bzrlib.smart.repository',
622
'SmartServerRepositoryGetRevIdForRevno')
623
request_handlers.register_lazy(
624
'Repository.get_stream', 'bzrlib.smart.repository',
625
'SmartServerRepositoryGetStream')
626
request_handlers.register_lazy(
627
'Repository.get_stream_1.19', 'bzrlib.smart.repository',
628
'SmartServerRepositoryGetStream_1_19')
629
request_handlers.register_lazy(
444
630
'Repository.tarball', 'bzrlib.smart.repository',
445
631
'SmartServerRepositoryTarball')
446
632
request_handlers.register_lazy(