2
0

server.py 21 KB

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