server.py 20 KB

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