server.py 28 KB

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