server.py 22 KB

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