server.py 27 KB

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