server.py 29 KB

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