server.py 28 KB

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