server.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. # server.py -- Implementation of the server side git protocols
  2. # Copyright (C) 2008 John Carr <john.carr@unrouted.co.uk>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # or (at your option) any later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Git smart network protocol server implementation.
  19. For more detailed implementation on the network protocol, see the
  20. Documentation/technical directory in the cgit distribution, and in particular:
  21. * Documentation/technical/protocol-capabilities.txt
  22. * Documentation/technical/pack-protocol.txt
  23. """
  24. import collections
  25. import socket
  26. import SocketServer
  27. import sys
  28. import zlib
  29. from dulwich.errors import (
  30. ApplyDeltaError,
  31. ChecksumMismatch,
  32. GitProtocolError,
  33. UnexpectedCommandError,
  34. ObjectFormatException,
  35. )
  36. from dulwich import log_utils
  37. from dulwich.objects import (
  38. hex_to_sha,
  39. )
  40. from dulwich.pack import (
  41. PackStreamReader,
  42. write_pack_data,
  43. )
  44. from dulwich.protocol import (
  45. MULTI_ACK,
  46. MULTI_ACK_DETAILED,
  47. ProtocolFile,
  48. ReceivableProtocol,
  49. SINGLE_ACK,
  50. TCP_GIT_PORT,
  51. ZERO_SHA,
  52. ack_type,
  53. extract_capabilities,
  54. extract_want_line_capabilities,
  55. BufferedPktLineWriter,
  56. )
  57. from dulwich.repo import (
  58. Repo,
  59. )
  60. logger = log_utils.getLogger(__name__)
  61. class Backend(object):
  62. """A backend for the Git smart server implementation."""
  63. def open_repository(self, path):
  64. """Open the repository at a path."""
  65. raise NotImplementedError(self.open_repository)
  66. class BackendRepo(object):
  67. """Repository abstraction used by the Git server.
  68. Please note that the methods required here are a
  69. subset of those provided by dulwich.repo.Repo.
  70. """
  71. object_store = None
  72. refs = None
  73. def get_refs(self):
  74. """
  75. Get all the refs in the repository
  76. :return: dict of name -> sha
  77. """
  78. raise NotImplementedError
  79. def get_peeled(self, name):
  80. """Return the cached peeled value of a ref, if available.
  81. :param name: Name of the ref to peel
  82. :return: The peeled value of the ref. If the ref is known not point to
  83. a tag, this will be the SHA the ref refers to. If no cached
  84. information about a tag is available, this method may return None,
  85. but it should attempt to peel the tag if possible.
  86. """
  87. return None
  88. def fetch_objects(self, determine_wants, graph_walker, progress,
  89. get_tagged=None):
  90. """
  91. Yield the objects required for a list of commits.
  92. :param progress: is a callback to send progress messages to the client
  93. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  94. sha for including tags.
  95. """
  96. raise NotImplementedError
  97. class PackStreamCopier(PackStreamReader):
  98. """Class to verify a pack stream as it is being read.
  99. The pack is read from a ReceivableProtocol using read() or recv() as
  100. appropriate and written out to the given file-like object.
  101. """
  102. def __init__(self, read_all, read_some, outfile):
  103. super(PackStreamCopier, self).__init__(read_all, read_some)
  104. self.outfile = outfile
  105. def _read(self, read, size):
  106. data = super(PackStreamCopier, self)._read(read, size)
  107. self.outfile.write(data)
  108. return data
  109. def verify(self):
  110. """Verify a pack stream and write it to the output file.
  111. See PackStreamReader.iterobjects for a list of exceptions this may
  112. throw.
  113. """
  114. for _, _, _ in self.read_objects():
  115. pass
  116. class DictBackend(Backend):
  117. """Trivial backend that looks up Git repositories in a dictionary."""
  118. def __init__(self, repos):
  119. self.repos = repos
  120. def open_repository(self, path):
  121. logger.debug('Opening repository at %s', path)
  122. # FIXME: What to do in case there is no repo ?
  123. return self.repos[path]
  124. class Handler(object):
  125. """Smart protocol command handler base class."""
  126. def __init__(self, backend, proto):
  127. self.backend = backend
  128. self.proto = proto
  129. self._client_capabilities = None
  130. @classmethod
  131. def capability_line(cls):
  132. return " ".join(cls.capabilities())
  133. @classmethod
  134. def capabilities(cls):
  135. raise NotImplementedError(cls.capabilities)
  136. @classmethod
  137. def innocuous_capabilities(cls):
  138. return ("include-tag", "thin-pack", "no-progress", "ofs-delta")
  139. @classmethod
  140. def required_capabilities(cls):
  141. """Return a list of capabilities that we require the client to have."""
  142. return []
  143. def set_client_capabilities(self, caps):
  144. allowable_caps = set(self.innocuous_capabilities())
  145. allowable_caps.update(self.capabilities())
  146. for cap in caps:
  147. if cap not in allowable_caps:
  148. raise GitProtocolError('Client asked for capability %s that '
  149. 'was not advertised.' % cap)
  150. for cap in self.required_capabilities():
  151. if cap not in caps:
  152. raise GitProtocolError('Client does not support required '
  153. 'capability %s.' % cap)
  154. self._client_capabilities = set(caps)
  155. logger.info('Client capabilities: %s', caps)
  156. def has_capability(self, cap):
  157. if self._client_capabilities is None:
  158. raise GitProtocolError('Server attempted to access capability %s '
  159. 'before asking client' % cap)
  160. return cap in self._client_capabilities
  161. class UploadPackHandler(Handler):
  162. """Protocol handler for uploading a pack to the server."""
  163. def __init__(self, backend, args, proto,
  164. stateless_rpc=False, advertise_refs=False):
  165. Handler.__init__(self, backend, proto)
  166. self.repo = backend.open_repository(args[0])
  167. self._graph_walker = None
  168. self.stateless_rpc = stateless_rpc
  169. self.advertise_refs = advertise_refs
  170. @classmethod
  171. def capabilities(cls):
  172. return ("multi_ack_detailed", "multi_ack", "side-band-64k", "thin-pack",
  173. "ofs-delta", "no-progress", "include-tag")
  174. @classmethod
  175. def required_capabilities(cls):
  176. return ("side-band-64k", "thin-pack", "ofs-delta")
  177. def progress(self, message):
  178. if self.has_capability("no-progress"):
  179. return
  180. self.proto.write_sideband(2, message)
  181. def get_tagged(self, refs=None, repo=None):
  182. """Get a dict of peeled values of tags to their original tag shas.
  183. :param refs: dict of refname -> sha of possible tags; defaults to all of
  184. the backend's refs.
  185. :param repo: optional Repo instance for getting peeled refs; defaults to
  186. the backend's repo, if available
  187. :return: dict of peeled_sha -> tag_sha, where tag_sha is the sha of a
  188. tag whose peeled value is peeled_sha.
  189. """
  190. if not self.has_capability("include-tag"):
  191. return {}
  192. if refs is None:
  193. refs = self.repo.get_refs()
  194. if repo is None:
  195. repo = getattr(self.repo, "repo", None)
  196. if repo is None:
  197. # Bail if we don't have a Repo available; this is ok since
  198. # clients must be able to handle if the server doesn't include
  199. # all relevant tags.
  200. # TODO: fix behavior when missing
  201. return {}
  202. tagged = {}
  203. for name, sha in refs.iteritems():
  204. peeled_sha = repo.get_peeled(name)
  205. if peeled_sha != sha:
  206. tagged[peeled_sha] = sha
  207. return tagged
  208. def handle(self):
  209. write = lambda x: self.proto.write_sideband(1, x)
  210. graph_walker = ProtocolGraphWalker(self, self.repo.object_store,
  211. self.repo.get_peeled)
  212. objects_iter = self.repo.fetch_objects(
  213. graph_walker.determine_wants, graph_walker, self.progress,
  214. get_tagged=self.get_tagged)
  215. # Do they want any objects?
  216. if len(objects_iter) == 0:
  217. return
  218. self.progress("dul-daemon says what\n")
  219. self.progress("counting objects: %d, done.\n" % len(objects_iter))
  220. write_pack_data(ProtocolFile(None, write), objects_iter,
  221. len(objects_iter))
  222. self.progress("how was that, then?\n")
  223. # we are done
  224. self.proto.write("0000")
  225. def _split_proto_line(line, allowed):
  226. """Split a line read from the wire.
  227. :param line: The line read from the wire.
  228. :param allowed: An iterable of command names that should be allowed.
  229. Command names not listed below as possible return values will be
  230. ignored. If None, any commands from the possible return values are
  231. allowed.
  232. :return: a tuple having one of the following forms:
  233. ('want', obj_id)
  234. ('have', obj_id)
  235. ('done', None)
  236. (None, None) (for a flush-pkt)
  237. :raise UnexpectedCommandError: if the line cannot be parsed into one of the
  238. allowed return values.
  239. """
  240. if not line:
  241. fields = [None]
  242. else:
  243. fields = line.rstrip('\n').split(' ', 1)
  244. command = fields[0]
  245. if allowed is not None and command not in allowed:
  246. raise UnexpectedCommandError(command)
  247. try:
  248. if len(fields) == 1 and command in ('done', None):
  249. return (command, None)
  250. elif len(fields) == 2 and command in ('want', 'have'):
  251. hex_to_sha(fields[1])
  252. return tuple(fields)
  253. except (TypeError, AssertionError), e:
  254. raise GitProtocolError(e)
  255. raise GitProtocolError('Received invalid line from client: %s' % line)
  256. class ProtocolGraphWalker(object):
  257. """A graph walker that knows the git protocol.
  258. As a graph walker, this class implements ack(), next(), and reset(). It
  259. also contains some base methods for interacting with the wire and walking
  260. the commit tree.
  261. The work of determining which acks to send is passed on to the
  262. implementation instance stored in _impl. The reason for this is that we do
  263. not know at object creation time what ack level the protocol requires. A
  264. call to set_ack_level() is required to set up the implementation, before any
  265. calls to next() or ack() are made.
  266. """
  267. def __init__(self, handler, object_store, get_peeled):
  268. self.handler = handler
  269. self.store = object_store
  270. self.get_peeled = get_peeled
  271. self.proto = handler.proto
  272. self.stateless_rpc = handler.stateless_rpc
  273. self.advertise_refs = handler.advertise_refs
  274. self._wants = []
  275. self._cached = False
  276. self._cache = []
  277. self._cache_index = 0
  278. self._impl = None
  279. def determine_wants(self, heads):
  280. """Determine the wants for a set of heads.
  281. The given heads are advertised to the client, who then specifies which
  282. refs he wants using 'want' lines. This portion of the protocol is the
  283. same regardless of ack type, and in fact is used to set the ack type of
  284. the ProtocolGraphWalker.
  285. :param heads: a dict of refname->SHA1 to advertise
  286. :return: a list of SHA1s requested by the client
  287. """
  288. if not heads:
  289. raise GitProtocolError('No heads found')
  290. values = set(heads.itervalues())
  291. if self.advertise_refs or not self.stateless_rpc:
  292. for i, (ref, sha) in enumerate(heads.iteritems()):
  293. line = "%s %s" % (sha, ref)
  294. if not i:
  295. line = "%s\x00%s" % (line, self.handler.capability_line())
  296. self.proto.write_pkt_line("%s\n" % line)
  297. peeled_sha = self.get_peeled(ref)
  298. if peeled_sha != sha:
  299. self.proto.write_pkt_line('%s %s^{}\n' %
  300. (peeled_sha, ref))
  301. # i'm done..
  302. self.proto.write_pkt_line(None)
  303. if self.advertise_refs:
  304. return []
  305. # Now client will sending want want want commands
  306. want = self.proto.read_pkt_line()
  307. if not want:
  308. return []
  309. line, caps = extract_want_line_capabilities(want)
  310. self.handler.set_client_capabilities(caps)
  311. self.set_ack_type(ack_type(caps))
  312. allowed = ('want', None)
  313. command, sha = _split_proto_line(line, allowed)
  314. want_revs = []
  315. while command != None:
  316. if sha not in values:
  317. raise GitProtocolError(
  318. 'Client wants invalid object %s' % sha)
  319. want_revs.append(sha)
  320. command, sha = self.read_proto_line(allowed)
  321. self.set_wants(want_revs)
  322. return want_revs
  323. def ack(self, have_ref):
  324. return self._impl.ack(have_ref)
  325. def reset(self):
  326. self._cached = True
  327. self._cache_index = 0
  328. def next(self):
  329. if not self._cached:
  330. if not self._impl and self.stateless_rpc:
  331. return None
  332. return self._impl.next()
  333. self._cache_index += 1
  334. if self._cache_index > len(self._cache):
  335. return None
  336. return self._cache[self._cache_index]
  337. def read_proto_line(self, allowed):
  338. """Read a line from the wire.
  339. :param allowed: An iterable of command names that should be allowed.
  340. :return: A tuple of (command, value); see _split_proto_line.
  341. :raise GitProtocolError: If an error occurred reading the line.
  342. """
  343. return _split_proto_line(self.proto.read_pkt_line(), allowed)
  344. def send_ack(self, sha, ack_type=''):
  345. if ack_type:
  346. ack_type = ' %s' % ack_type
  347. self.proto.write_pkt_line('ACK %s%s\n' % (sha, ack_type))
  348. def send_nak(self):
  349. self.proto.write_pkt_line('NAK\n')
  350. def set_wants(self, wants):
  351. self._wants = wants
  352. def _is_satisfied(self, haves, want, earliest):
  353. """Check whether a want is satisfied by a set of haves.
  354. A want, typically a branch tip, is "satisfied" only if there exists a
  355. path back from that want to one of the haves.
  356. :param haves: A set of commits we know the client has.
  357. :param want: The want to check satisfaction for.
  358. :param earliest: A timestamp beyond which the search for haves will be
  359. terminated, presumably because we're searching too far down the
  360. wrong branch.
  361. """
  362. o = self.store[want]
  363. pending = collections.deque([o])
  364. while pending:
  365. commit = pending.popleft()
  366. if commit.id in haves:
  367. return True
  368. if commit.type_name != "commit":
  369. # non-commit wants are assumed to be satisfied
  370. continue
  371. for parent in commit.parents:
  372. parent_obj = self.store[parent]
  373. # TODO: handle parents with later commit times than children
  374. if parent_obj.commit_time >= earliest:
  375. pending.append(parent_obj)
  376. return False
  377. def all_wants_satisfied(self, haves):
  378. """Check whether all the current wants are satisfied by a set of haves.
  379. :param haves: A set of commits we know the client has.
  380. :note: Wants are specified with set_wants rather than passed in since
  381. in the current interface they are determined outside this class.
  382. """
  383. haves = set(haves)
  384. earliest = min([self.store[h].commit_time for h in haves])
  385. for want in self._wants:
  386. if not self._is_satisfied(haves, want, earliest):
  387. return False
  388. return True
  389. def set_ack_type(self, ack_type):
  390. impl_classes = {
  391. MULTI_ACK: MultiAckGraphWalkerImpl,
  392. MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl,
  393. SINGLE_ACK: SingleAckGraphWalkerImpl,
  394. }
  395. self._impl = impl_classes[ack_type](self)
  396. _GRAPH_WALKER_COMMANDS = ('have', 'done', None)
  397. class SingleAckGraphWalkerImpl(object):
  398. """Graph walker implementation that speaks the single-ack protocol."""
  399. def __init__(self, walker):
  400. self.walker = walker
  401. self._sent_ack = False
  402. def ack(self, have_ref):
  403. if not self._sent_ack:
  404. self.walker.send_ack(have_ref)
  405. self._sent_ack = True
  406. def next(self):
  407. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  408. if command in (None, 'done'):
  409. if not self._sent_ack:
  410. self.walker.send_nak()
  411. return None
  412. elif command == 'have':
  413. return sha
  414. class MultiAckGraphWalkerImpl(object):
  415. """Graph walker implementation that speaks the multi-ack protocol."""
  416. def __init__(self, walker):
  417. self.walker = walker
  418. self._found_base = False
  419. self._common = []
  420. def ack(self, have_ref):
  421. self._common.append(have_ref)
  422. if not self._found_base:
  423. self.walker.send_ack(have_ref, 'continue')
  424. if self.walker.all_wants_satisfied(self._common):
  425. self._found_base = True
  426. # else we blind ack within next
  427. def next(self):
  428. while True:
  429. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  430. if command is None:
  431. self.walker.send_nak()
  432. # in multi-ack mode, a flush-pkt indicates the client wants to
  433. # flush but more have lines are still coming
  434. continue
  435. elif command == 'done':
  436. # don't nak unless no common commits were found, even if not
  437. # everything is satisfied
  438. if self._common:
  439. self.walker.send_ack(self._common[-1])
  440. else:
  441. self.walker.send_nak()
  442. return None
  443. elif command == 'have':
  444. if self._found_base:
  445. # blind ack
  446. self.walker.send_ack(sha, 'continue')
  447. return sha
  448. class MultiAckDetailedGraphWalkerImpl(object):
  449. """Graph walker implementation speaking the multi-ack-detailed protocol."""
  450. def __init__(self, walker):
  451. self.walker = walker
  452. self._found_base = False
  453. self._common = []
  454. def ack(self, have_ref):
  455. self._common.append(have_ref)
  456. if not self._found_base:
  457. self.walker.send_ack(have_ref, 'common')
  458. if self.walker.all_wants_satisfied(self._common):
  459. self._found_base = True
  460. self.walker.send_ack(have_ref, 'ready')
  461. # else we blind ack within next
  462. def next(self):
  463. while True:
  464. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  465. if command is None:
  466. self.walker.send_nak()
  467. if self.walker.stateless_rpc:
  468. return None
  469. continue
  470. elif command == 'done':
  471. # don't nak unless no common commits were found, even if not
  472. # everything is satisfied
  473. if self._common:
  474. self.walker.send_ack(self._common[-1])
  475. else:
  476. self.walker.send_nak()
  477. return None
  478. elif command == 'have':
  479. if self._found_base:
  480. # blind ack; can happen if the client has more requests
  481. # inflight
  482. self.walker.send_ack(sha, 'ready')
  483. return sha
  484. class ReceivePackHandler(Handler):
  485. """Protocol handler for downloading a pack from the client."""
  486. def __init__(self, backend, args, proto,
  487. stateless_rpc=False, advertise_refs=False):
  488. Handler.__init__(self, backend, proto)
  489. self.repo = backend.open_repository(args[0])
  490. self.stateless_rpc = stateless_rpc
  491. self.advertise_refs = advertise_refs
  492. @classmethod
  493. def capabilities(cls):
  494. return ("report-status", "delete-refs", "side-band-64k")
  495. def _apply_pack(self, refs):
  496. f, commit = self.repo.object_store.add_thin_pack()
  497. all_exceptions = (IOError, OSError, ChecksumMismatch, ApplyDeltaError,
  498. AssertionError, socket.error, zlib.error,
  499. ObjectFormatException)
  500. status = []
  501. # TODO: more informative error messages than just the exception string
  502. try:
  503. PackStreamCopier(self.proto.read, self.proto.recv, f).verify()
  504. p = commit()
  505. if not p:
  506. raise IOError('Failed to write pack')
  507. p.check()
  508. status.append(('unpack', 'ok'))
  509. except all_exceptions, e:
  510. status.append(('unpack', str(e).replace('\n', '')))
  511. # The pack may still have been moved in, but it may contain broken
  512. # objects. We trust a later GC to clean it up.
  513. for oldsha, sha, ref in refs:
  514. ref_status = 'ok'
  515. try:
  516. if sha == ZERO_SHA:
  517. if not 'delete-refs' in self.capabilities():
  518. raise GitProtocolError(
  519. 'Attempted to delete refs without delete-refs '
  520. 'capability.')
  521. try:
  522. del self.repo.refs[ref]
  523. except all_exceptions:
  524. ref_status = 'failed to delete'
  525. else:
  526. try:
  527. self.repo.refs[ref] = sha
  528. except all_exceptions:
  529. ref_status = 'failed to write'
  530. except KeyError, e:
  531. ref_status = 'bad ref'
  532. status.append((ref, ref_status))
  533. return status
  534. def _report_status(self, status):
  535. if self.has_capability('side-band-64k'):
  536. writer = BufferedPktLineWriter(
  537. lambda d: self.proto.write_sideband(1, d))
  538. write = writer.write
  539. def flush():
  540. writer.flush()
  541. self.proto.write_pkt_line(None)
  542. else:
  543. write = self.proto.write_pkt_line
  544. flush = lambda: None
  545. for name, msg in status:
  546. if name == 'unpack':
  547. write('unpack %s\n' % msg)
  548. elif msg == 'ok':
  549. write('ok %s\n' % name)
  550. else:
  551. write('ng %s %s\n' % (name, msg))
  552. write(None)
  553. flush()
  554. def handle(self):
  555. refs = self.repo.get_refs().items()
  556. if self.advertise_refs or not self.stateless_rpc:
  557. if refs:
  558. self.proto.write_pkt_line(
  559. "%s %s\x00%s\n" % (refs[0][1], refs[0][0],
  560. self.capability_line()))
  561. for i in range(1, len(refs)):
  562. ref = refs[i]
  563. self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
  564. else:
  565. self.proto.write_pkt_line("%s capabilities^{} %s" % (
  566. ZERO_SHA, self.capability_line()))
  567. self.proto.write("0000")
  568. if self.advertise_refs:
  569. return
  570. client_refs = []
  571. ref = self.proto.read_pkt_line()
  572. # if ref is none then client doesnt want to send us anything..
  573. if ref is None:
  574. return
  575. ref, caps = extract_capabilities(ref)
  576. self.set_client_capabilities(caps)
  577. # client will now send us a list of (oldsha, newsha, ref)
  578. while ref:
  579. client_refs.append(ref.split())
  580. ref = self.proto.read_pkt_line()
  581. # backend can now deal with this refs and read a pack using self.read
  582. status = self._apply_pack(client_refs)
  583. # when we have read all the pack from the client, send a status report
  584. # if the client asked for it
  585. if self.has_capability('report-status'):
  586. self._report_status(status)
  587. # Default handler classes for git services.
  588. DEFAULT_HANDLERS = {
  589. 'git-upload-pack': UploadPackHandler,
  590. 'git-receive-pack': ReceivePackHandler,
  591. }
  592. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  593. def __init__(self, handlers, *args, **kwargs):
  594. self.handlers = handlers
  595. SocketServer.StreamRequestHandler.__init__(self, *args, **kwargs)
  596. def handle(self):
  597. proto = ReceivableProtocol(self.connection.recv, self.wfile.write)
  598. command, args = proto.read_cmd()
  599. logger.info('Handling %s request, args=%s', command, args)
  600. cls = self.handlers.get(command, None)
  601. if not callable(cls):
  602. raise GitProtocolError('Invalid service %s' % command)
  603. h = cls(self.server.backend, args, proto)
  604. h.handle()
  605. class TCPGitServer(SocketServer.TCPServer):
  606. allow_reuse_address = True
  607. serve = SocketServer.TCPServer.serve_forever
  608. def _make_handler(self, *args, **kwargs):
  609. return TCPGitRequestHandler(self.handlers, *args, **kwargs)
  610. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT, handlers=None):
  611. self.handlers = dict(DEFAULT_HANDLERS)
  612. if handlers is not None:
  613. self.handlers.update(handlers)
  614. self.backend = backend
  615. logger.info('Listening for TCP connections on %s:%d', listen_addr, port)
  616. SocketServer.TCPServer.__init__(self, (listen_addr, port),
  617. self._make_handler)
  618. def verify_request(self, request, client_address):
  619. logger.info('Handling request from %s', client_address)
  620. return True
  621. def handle_error(self, request, client_address):
  622. logger.exception('Exception happened during processing of request '
  623. 'from %s', client_address)
  624. def main(argv=sys.argv):
  625. """Entry point for starting a TCP git server."""
  626. if len(argv) > 1:
  627. gitdir = argv[1]
  628. else:
  629. gitdir = '.'
  630. log_utils.default_logging_config()
  631. backend = DictBackend({'/': Repo(gitdir)})
  632. server = TCPGitServer(backend, 'localhost')
  633. server.serve_forever()