server.py 29 KB

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