server.py 28 KB

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