server.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. # server.py -- Implementation of the server side git protocols
  2. # Copryight (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 SocketServer
  26. from dulwich.errors import (
  27. ApplyDeltaError,
  28. ChecksumMismatch,
  29. GitProtocolError,
  30. )
  31. from dulwich.objects import (
  32. hex_to_sha,
  33. )
  34. from dulwich.protocol import (
  35. Protocol,
  36. ProtocolFile,
  37. TCP_GIT_PORT,
  38. ZERO_SHA,
  39. extract_capabilities,
  40. extract_want_line_capabilities,
  41. SINGLE_ACK,
  42. MULTI_ACK,
  43. MULTI_ACK_DETAILED,
  44. ack_type,
  45. )
  46. from dulwich.pack import (
  47. write_pack_data,
  48. )
  49. class Backend(object):
  50. """A backend for the Git smart server implementation."""
  51. def open_repository(self, path):
  52. """Open the repository at a path."""
  53. raise NotImplementedError(self.open_repository)
  54. class BackendRepo(object):
  55. """Repository abstraction used by the Git server.
  56. Please note that the methods required here are a
  57. subset of those provided by dulwich.repo.Repo.
  58. """
  59. object_store = None
  60. refs = None
  61. def get_refs(self):
  62. """
  63. Get all the refs in the repository
  64. :return: dict of name -> sha
  65. """
  66. raise NotImplementedError
  67. def get_peeled(self, name):
  68. """Return the cached peeled value of a ref, if available.
  69. :param name: Name of the ref to peel
  70. :return: The peeled value of the ref. If the ref is known not point to
  71. a tag, this will be the SHA the ref refers to. If the ref may
  72. point to a tag, but no cached information is available, None is
  73. returned.
  74. """
  75. return None
  76. def fetch_objects(self, determine_wants, graph_walker, progress,
  77. get_tagged=None):
  78. """
  79. Yield the objects required for a list of commits.
  80. :param progress: is a callback to send progress messages to the client
  81. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  82. sha for including tags.
  83. """
  84. raise NotImplementedError
  85. class DictBackend(Backend):
  86. """Trivial backend that looks up Git repositories in a dictionary."""
  87. def __init__(self, repos):
  88. self.repos = repos
  89. def open_repository(self, path):
  90. # FIXME: What to do in case there is no repo ?
  91. return self.repos[path]
  92. class Handler(object):
  93. """Smart protocol command handler base class."""
  94. def __init__(self, backend, read, write):
  95. self.backend = backend
  96. self.proto = Protocol(read, write)
  97. self._client_capabilities = None
  98. def capability_line(self):
  99. return " ".join(self.capabilities())
  100. def capabilities(self):
  101. raise NotImplementedError(self.capabilities)
  102. def innocuous_capabilities(self):
  103. return ("include-tag", "thin-pack", "no-progress", "ofs-delta")
  104. def required_capabilities(self):
  105. """Return a list of capabilities that we require the client to have."""
  106. return []
  107. def set_client_capabilities(self, caps):
  108. allowable_caps = set(self.innocuous_capabilities())
  109. allowable_caps.update(self.capabilities())
  110. for cap in caps:
  111. if cap not in allowable_caps:
  112. raise GitProtocolError('Client asked for capability %s that '
  113. 'was not advertised.' % cap)
  114. for cap in self.required_capabilities():
  115. if cap not in caps:
  116. raise GitProtocolError('Client does not support required '
  117. 'capability %s.' % cap)
  118. self._client_capabilities = set(caps)
  119. def has_capability(self, cap):
  120. if self._client_capabilities is None:
  121. raise GitProtocolError('Server attempted to access capability %s '
  122. 'before asking client' % cap)
  123. return cap in self._client_capabilities
  124. class UploadPackHandler(Handler):
  125. """Protocol handler for uploading a pack to the server."""
  126. def __init__(self, backend, args, read, write,
  127. stateless_rpc=False, advertise_refs=False):
  128. Handler.__init__(self, backend, read, write)
  129. self.repo = backend.open_repository(args[0])
  130. self._graph_walker = None
  131. self.stateless_rpc = stateless_rpc
  132. self.advertise_refs = advertise_refs
  133. def capabilities(self):
  134. return ("multi_ack_detailed", "multi_ack", "side-band-64k", "thin-pack",
  135. "ofs-delta", "no-progress", "include-tag")
  136. def required_capabilities(self):
  137. return ("side-band-64k", "thin-pack", "ofs-delta")
  138. def progress(self, message):
  139. if self.has_capability("no-progress"):
  140. return
  141. self.proto.write_sideband(2, message)
  142. def get_tagged(self, refs=None, repo=None):
  143. """Get a dict of peeled values of tags to their original tag shas.
  144. :param refs: dict of refname -> sha of possible tags; defaults to all of
  145. the backend's refs.
  146. :param repo: optional Repo instance for getting peeled refs; defaults to
  147. the backend's repo, if available
  148. :return: dict of peeled_sha -> tag_sha, where tag_sha is the sha of a
  149. tag whose peeled value is peeled_sha.
  150. """
  151. if not self.has_capability("include-tag"):
  152. return {}
  153. if refs is None:
  154. refs = self.repo.get_refs()
  155. if repo is None:
  156. repo = getattr(self.repo, "repo", None)
  157. if repo is None:
  158. # Bail if we don't have a Repo available; this is ok since
  159. # clients must be able to handle if the server doesn't include
  160. # all relevant tags.
  161. # TODO: fix behavior when missing
  162. return {}
  163. tagged = {}
  164. for name, sha in refs.iteritems():
  165. peeled_sha = repo.get_peeled(name)
  166. if peeled_sha != sha:
  167. tagged[peeled_sha] = sha
  168. return tagged
  169. def handle(self):
  170. write = lambda x: self.proto.write_sideband(1, x)
  171. graph_walker = ProtocolGraphWalker(self, self.repo.object_store,
  172. self.repo.get_peeled)
  173. objects_iter = self.repo.fetch_objects(
  174. graph_walker.determine_wants, graph_walker, self.progress,
  175. get_tagged=self.get_tagged)
  176. # Do they want any objects?
  177. if len(objects_iter) == 0:
  178. return
  179. self.progress("dul-daemon says what\n")
  180. self.progress("counting objects: %d, done.\n" % len(objects_iter))
  181. write_pack_data(ProtocolFile(None, write), objects_iter,
  182. len(objects_iter))
  183. self.progress("how was that, then?\n")
  184. # we are done
  185. self.proto.write("0000")
  186. class ProtocolGraphWalker(object):
  187. """A graph walker that knows the git protocol.
  188. As a graph walker, this class implements ack(), next(), and reset(). It
  189. also contains some base methods for interacting with the wire and walking
  190. the commit tree.
  191. The work of determining which acks to send is passed on to the
  192. implementation instance stored in _impl. The reason for this is that we do
  193. not know at object creation time what ack level the protocol requires. A
  194. call to set_ack_level() is required to set up the implementation, before any
  195. calls to next() or ack() are made.
  196. """
  197. def __init__(self, handler, object_store, get_peeled):
  198. self.handler = handler
  199. self.store = object_store
  200. self.get_peeled = get_peeled
  201. self.proto = handler.proto
  202. self.stateless_rpc = handler.stateless_rpc
  203. self.advertise_refs = handler.advertise_refs
  204. self._wants = []
  205. self._cached = False
  206. self._cache = []
  207. self._cache_index = 0
  208. self._impl = None
  209. def determine_wants(self, heads):
  210. """Determine the wants for a set of heads.
  211. The given heads are advertised to the client, who then specifies which
  212. refs he wants using 'want' lines. This portion of the protocol is the
  213. same regardless of ack type, and in fact is used to set the ack type of
  214. the ProtocolGraphWalker.
  215. :param heads: a dict of refname->SHA1 to advertise
  216. :return: a list of SHA1s requested by the client
  217. """
  218. if not heads:
  219. raise GitProtocolError('No heads found')
  220. values = set(heads.itervalues())
  221. if self.advertise_refs or not self.stateless_rpc:
  222. for i, (ref, sha) in enumerate(heads.iteritems()):
  223. line = "%s %s" % (sha, ref)
  224. if not i:
  225. line = "%s\x00%s" % (line, self.handler.capability_line())
  226. self.proto.write_pkt_line("%s\n" % line)
  227. peeled_sha = self.get_peeled(ref)
  228. if peeled_sha != sha:
  229. self.proto.write_pkt_line('%s %s^{}\n' %
  230. (peeled_sha, ref))
  231. # i'm done..
  232. self.proto.write_pkt_line(None)
  233. if self.advertise_refs:
  234. return []
  235. # Now client will sending want want want commands
  236. want = self.proto.read_pkt_line()
  237. if not want:
  238. return []
  239. line, caps = extract_want_line_capabilities(want)
  240. self.handler.set_client_capabilities(caps)
  241. self.set_ack_type(ack_type(caps))
  242. command, sha = self._split_proto_line(line)
  243. want_revs = []
  244. while command != None:
  245. if command != 'want':
  246. raise GitProtocolError(
  247. 'Protocol got unexpected command %s' % command)
  248. if sha not in values:
  249. raise GitProtocolError(
  250. 'Client wants invalid object %s' % sha)
  251. want_revs.append(sha)
  252. command, sha = self.read_proto_line()
  253. self.set_wants(want_revs)
  254. return want_revs
  255. def ack(self, have_ref):
  256. return self._impl.ack(have_ref)
  257. def reset(self):
  258. self._cached = True
  259. self._cache_index = 0
  260. def next(self):
  261. if not self._cached:
  262. if not self._impl and self.stateless_rpc:
  263. return None
  264. return self._impl.next()
  265. self._cache_index += 1
  266. if self._cache_index > len(self._cache):
  267. return None
  268. return self._cache[self._cache_index]
  269. def _split_proto_line(self, line):
  270. fields = line.rstrip('\n').split(' ', 1)
  271. if len(fields) == 1 and fields[0] == 'done':
  272. return ('done', None)
  273. elif len(fields) == 2 and fields[0] in ('want', 'have'):
  274. try:
  275. hex_to_sha(fields[1])
  276. return tuple(fields)
  277. except (TypeError, AssertionError), e:
  278. raise GitProtocolError(e)
  279. raise GitProtocolError('Received invalid line from client:\n%s' % line)
  280. def read_proto_line(self):
  281. """Read a line from the wire.
  282. :return: a tuple having one of the following forms:
  283. ('want', obj_id)
  284. ('have', obj_id)
  285. ('done', None)
  286. (None, None) (for a flush-pkt)
  287. :raise GitProtocolError: if the line cannot be parsed into one of the
  288. possible return values.
  289. """
  290. line = self.proto.read_pkt_line()
  291. if not line:
  292. return (None, None)
  293. return self._split_proto_line(line)
  294. def send_ack(self, sha, ack_type=''):
  295. if ack_type:
  296. ack_type = ' %s' % ack_type
  297. self.proto.write_pkt_line('ACK %s%s\n' % (sha, ack_type))
  298. def send_nak(self):
  299. self.proto.write_pkt_line('NAK\n')
  300. def set_wants(self, wants):
  301. self._wants = wants
  302. def _is_satisfied(self, haves, want, earliest):
  303. """Check whether a want is satisfied by a set of haves.
  304. A want, typically a branch tip, is "satisfied" only if there exists a
  305. path back from that want to one of the haves.
  306. :param haves: A set of commits we know the client has.
  307. :param want: The want to check satisfaction for.
  308. :param earliest: A timestamp beyond which the search for haves will be
  309. terminated, presumably because we're searching too far down the
  310. wrong branch.
  311. """
  312. o = self.store[want]
  313. pending = collections.deque([o])
  314. while pending:
  315. commit = pending.popleft()
  316. if commit.id in haves:
  317. return True
  318. if commit.type_name != "commit":
  319. # non-commit wants are assumed to be satisfied
  320. continue
  321. for parent in commit.parents:
  322. parent_obj = self.store[parent]
  323. # TODO: handle parents with later commit times than children
  324. if parent_obj.commit_time >= earliest:
  325. pending.append(parent_obj)
  326. return False
  327. def all_wants_satisfied(self, haves):
  328. """Check whether all the current wants are satisfied by a set of haves.
  329. :param haves: A set of commits we know the client has.
  330. :note: Wants are specified with set_wants rather than passed in since
  331. in the current interface they are determined outside this class.
  332. """
  333. haves = set(haves)
  334. earliest = min([self.store[h].commit_time for h in haves])
  335. for want in self._wants:
  336. if not self._is_satisfied(haves, want, earliest):
  337. return False
  338. return True
  339. def set_ack_type(self, ack_type):
  340. impl_classes = {
  341. MULTI_ACK: MultiAckGraphWalkerImpl,
  342. MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl,
  343. SINGLE_ACK: SingleAckGraphWalkerImpl,
  344. }
  345. self._impl = impl_classes[ack_type](self)
  346. class SingleAckGraphWalkerImpl(object):
  347. """Graph walker implementation that speaks the single-ack protocol."""
  348. def __init__(self, walker):
  349. self.walker = walker
  350. self._sent_ack = False
  351. def ack(self, have_ref):
  352. if not self._sent_ack:
  353. self.walker.send_ack(have_ref)
  354. self._sent_ack = True
  355. def next(self):
  356. command, sha = self.walker.read_proto_line()
  357. if command in (None, 'done'):
  358. if not self._sent_ack:
  359. self.walker.send_nak()
  360. return None
  361. elif command == 'have':
  362. return sha
  363. class MultiAckGraphWalkerImpl(object):
  364. """Graph walker implementation that speaks the multi-ack protocol."""
  365. def __init__(self, walker):
  366. self.walker = walker
  367. self._found_base = False
  368. self._common = []
  369. def ack(self, have_ref):
  370. self._common.append(have_ref)
  371. if not self._found_base:
  372. self.walker.send_ack(have_ref, 'continue')
  373. if self.walker.all_wants_satisfied(self._common):
  374. self._found_base = True
  375. # else we blind ack within next
  376. def next(self):
  377. while True:
  378. command, sha = self.walker.read_proto_line()
  379. if command is None:
  380. self.walker.send_nak()
  381. # in multi-ack mode, a flush-pkt indicates the client wants to
  382. # flush but more have lines are still coming
  383. continue
  384. elif command == 'done':
  385. # don't nak unless no common commits were found, even if not
  386. # everything is satisfied
  387. if self._common:
  388. self.walker.send_ack(self._common[-1])
  389. else:
  390. self.walker.send_nak()
  391. return None
  392. elif command == 'have':
  393. if self._found_base:
  394. # blind ack
  395. self.walker.send_ack(sha, 'continue')
  396. return sha
  397. class MultiAckDetailedGraphWalkerImpl(object):
  398. """Graph walker implementation speaking the multi-ack-detailed protocol."""
  399. def __init__(self, walker):
  400. self.walker = walker
  401. self._found_base = False
  402. self._common = []
  403. def ack(self, have_ref):
  404. self._common.append(have_ref)
  405. if not self._found_base:
  406. self.walker.send_ack(have_ref, 'common')
  407. if self.walker.all_wants_satisfied(self._common):
  408. self._found_base = True
  409. self.walker.send_ack(have_ref, 'ready')
  410. # else we blind ack within next
  411. def next(self):
  412. while True:
  413. command, sha = self.walker.read_proto_line()
  414. if command is None:
  415. self.walker.send_nak()
  416. if self.walker.stateless_rpc:
  417. return None
  418. continue
  419. elif command == 'done':
  420. # don't nak unless no common commits were found, even if not
  421. # everything is satisfied
  422. if self._common:
  423. self.walker.send_ack(self._common[-1])
  424. else:
  425. self.walker.send_nak()
  426. return None
  427. elif command == 'have':
  428. if self._found_base:
  429. # blind ack; can happen if the client has more requests
  430. # inflight
  431. self.walker.send_ack(sha, 'ready')
  432. return sha
  433. class ReceivePackHandler(Handler):
  434. """Protocol handler for downloading a pack from the client."""
  435. def __init__(self, backend, args, read, write,
  436. stateless_rpc=False, advertise_refs=False):
  437. Handler.__init__(self, backend, read, write)
  438. self.repo = backend.open_repository(args[0])
  439. self.stateless_rpc = stateless_rpc
  440. self.advertise_refs = advertise_refs
  441. def capabilities(self):
  442. return ("report-status", "delete-refs")
  443. def _apply_pack(self, refs, read, delete_refs=True):
  444. f, commit = self.repo.object_store.add_thin_pack()
  445. all_exceptions = (IOError, OSError, ChecksumMismatch, ApplyDeltaError)
  446. status = []
  447. unpack_error = None
  448. # TODO: more informative error messages than just the exception string
  449. try:
  450. # TODO: decode the pack as we stream to avoid blocking reads beyond
  451. # the end of data (when using HTTP/1.1 chunked encoding)
  452. while True:
  453. data = read(10240)
  454. if not data:
  455. break
  456. f.write(data)
  457. except all_exceptions, e:
  458. unpack_error = str(e).replace('\n', '')
  459. try:
  460. commit()
  461. except all_exceptions, e:
  462. if not unpack_error:
  463. unpack_error = str(e).replace('\n', '')
  464. if unpack_error:
  465. status.append(('unpack', unpack_error))
  466. else:
  467. status.append(('unpack', 'ok'))
  468. for oldsha, sha, ref in refs:
  469. ref_error = None
  470. try:
  471. if sha == ZERO_SHA:
  472. if not delete_refs:
  473. raise GitProtocolError(
  474. 'Attempted to delete refs without delete-refs '
  475. 'capability.')
  476. try:
  477. del self.repo.refs[ref]
  478. except all_exceptions:
  479. ref_error = 'failed to delete'
  480. else:
  481. try:
  482. self.repo.refs[ref] = sha
  483. except all_exceptions:
  484. ref_error = 'failed to write'
  485. except KeyError, e:
  486. ref_error = 'bad ref'
  487. if ref_error:
  488. status.append((ref, ref_error))
  489. else:
  490. status.append((ref, 'ok'))
  491. print "pack applied"
  492. return status
  493. def handle(self):
  494. refs = self.repo.get_refs().items()
  495. if self.advertise_refs or not self.stateless_rpc:
  496. if refs:
  497. self.proto.write_pkt_line(
  498. "%s %s\x00%s\n" % (refs[0][1], refs[0][0],
  499. self.capability_line()))
  500. for i in range(1, len(refs)):
  501. ref = refs[i]
  502. self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
  503. else:
  504. self.proto.write_pkt_line("%s capabilities^{} %s" % (
  505. ZERO_SHA, self.capability_line()))
  506. self.proto.write("0000")
  507. if self.advertise_refs:
  508. return
  509. client_refs = []
  510. ref = self.proto.read_pkt_line()
  511. # if ref is none then client doesnt want to send us anything..
  512. if ref is None:
  513. return
  514. ref, caps = extract_capabilities(ref)
  515. self.set_client_capabilities(caps)
  516. # client will now send us a list of (oldsha, newsha, ref)
  517. while ref:
  518. client_refs.append(ref.split())
  519. ref = self.proto.read_pkt_line()
  520. # backend can now deal with this refs and read a pack using self.read
  521. status = self.repo._apply_pack(client_refs, self.proto.read,
  522. self.has_capability('delete-refs'))
  523. # when we have read all the pack from the client, send a status report
  524. # if the client asked for it
  525. if self.has_capability('report-status'):
  526. for name, msg in status:
  527. if name == 'unpack':
  528. self.proto.write_pkt_line('unpack %s\n' % msg)
  529. elif msg == 'ok':
  530. self.proto.write_pkt_line('ok %s\n' % name)
  531. else:
  532. self.proto.write_pkt_line('ng %s %s\n' % (name, msg))
  533. self.proto.write_pkt_line(None)
  534. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  535. def handle(self):
  536. proto = Protocol(self.rfile.read, self.wfile.write)
  537. command, args = proto.read_cmd()
  538. # switch case to handle the specific git command
  539. if command == 'git-upload-pack':
  540. cls = UploadPackHandler
  541. elif command == 'git-receive-pack':
  542. cls = ReceivePackHandler
  543. else:
  544. return
  545. h = cls(self.server.backend, args, self.rfile.read, self.wfile.write)
  546. h.handle()
  547. class TCPGitServer(SocketServer.TCPServer):
  548. allow_reuse_address = True
  549. serve = SocketServer.TCPServer.serve_forever
  550. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
  551. self.backend = backend
  552. SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)