server.py 20 KB

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