server.py 28 KB

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