server.py 23 KB

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