server.py 24 KB

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