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