server.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. GitProtocolError,
  29. )
  30. from dulwich.objects import (
  31. hex_to_sha,
  32. )
  33. from dulwich.protocol import (
  34. Protocol,
  35. ProtocolFile,
  36. TCP_GIT_PORT,
  37. extract_capabilities,
  38. extract_want_line_capabilities,
  39. SINGLE_ACK,
  40. MULTI_ACK,
  41. ack_type,
  42. )
  43. from dulwich.repo import (
  44. Repo,
  45. )
  46. from dulwich.pack import (
  47. write_pack_data,
  48. )
  49. class Backend(object):
  50. def get_refs(self):
  51. """
  52. Get all the refs in the repository
  53. :return: dict of name -> sha
  54. """
  55. raise NotImplementedError
  56. def apply_pack(self, refs, read):
  57. """ Import a set of changes into a repository and update the refs
  58. :param refs: list of tuple(name, sha)
  59. :param read: callback to read from the incoming pack
  60. """
  61. raise NotImplementedError
  62. def fetch_objects(self, determine_wants, graph_walker, progress):
  63. """
  64. Yield the objects required for a list of commits.
  65. :param progress: is a callback to send progress messages to the client
  66. """
  67. raise NotImplementedError
  68. class GitBackend(Backend):
  69. def __init__(self, repo=None):
  70. if repo is None:
  71. repo = Repo(tmpfile.mkdtemp())
  72. self.repo = repo
  73. self.object_store = self.repo.object_store
  74. self.fetch_objects = self.repo.fetch_objects
  75. self.get_refs = self.repo.get_refs
  76. def apply_pack(self, refs, read):
  77. f, commit = self.repo.object_store.add_thin_pack()
  78. try:
  79. f.write(read())
  80. finally:
  81. commit()
  82. for oldsha, sha, ref in refs:
  83. if ref == "0" * 40:
  84. del self.repo.refs[ref]
  85. else:
  86. self.repo.refs[ref] = sha
  87. print "pack applied"
  88. class Handler(object):
  89. """Smart protocol command handler base class."""
  90. def __init__(self, backend, read, write):
  91. self.backend = backend
  92. self.proto = Protocol(read, write)
  93. def capabilities(self):
  94. return " ".join(self.default_capabilities())
  95. class UploadPackHandler(Handler):
  96. """Protocol handler for uploading a pack to the server."""
  97. def __init__(self, backend, read, write,
  98. stateless_rpc=False, advertise_refs=False):
  99. Handler.__init__(self, backend, read, write)
  100. self._client_capabilities = None
  101. self._graph_walker = None
  102. self._stateless_rpc = stateless_rpc
  103. self._advertise_refs = advertise_refs
  104. def default_capabilities(self):
  105. return ("multi_ack", "side-band-64k", "thin-pack", "ofs-delta")
  106. def set_client_capabilities(self, caps):
  107. my_caps = self.default_capabilities()
  108. for cap in caps:
  109. if '_ack' in cap and cap not in my_caps:
  110. raise GitProtocolError('Client asked for capability %s that '
  111. 'was not advertised.' % cap)
  112. self._client_capabilities = caps
  113. def get_client_capabilities(self):
  114. return self._client_capabilities
  115. client_capabilities = property(get_client_capabilities,
  116. set_client_capabilities)
  117. def handle(self):
  118. progress = lambda x: self.proto.write_sideband(2, x)
  119. write = lambda x: self.proto.write_sideband(1, x)
  120. graph_walker = ProtocolGraphWalker(self)
  121. objects_iter = self.backend.fetch_objects(
  122. graph_walker.determine_wants, graph_walker, progress)
  123. # Do they want any objects?
  124. if len(objects_iter) == 0:
  125. return
  126. progress("dul-daemon says what\n")
  127. progress("counting objects: %d, done.\n" % len(objects_iter))
  128. write_pack_data(ProtocolFile(None, write), objects_iter,
  129. len(objects_iter))
  130. progress("how was that, then?\n")
  131. # we are done
  132. self.proto.write("0000")
  133. class ProtocolGraphWalker(object):
  134. """A graph walker that knows the git protocol.
  135. As a graph walker, this class implements ack(), next(), and reset(). It also
  136. contains some base methods for interacting with the wire and walking the
  137. commit tree.
  138. The work of determining which acks to send is passed on to the
  139. implementation instance stored in _impl. The reason for this is that we do
  140. not know at object creation time what ack level the protocol requires. A
  141. call to set_ack_level() is required to set up the implementation, before any
  142. calls to next() or ack() are made.
  143. """
  144. def __init__(self, handler):
  145. self.handler = handler
  146. self.store = handler.backend.object_store
  147. self.proto = handler.proto
  148. self._wants = []
  149. self._cached = False
  150. self._cache = []
  151. self._cache_index = 0
  152. self._impl = None
  153. def determine_wants(self, heads):
  154. """Determine the wants for a set of heads.
  155. The given heads are advertised to the client, who then specifies which
  156. refs he wants using 'want' lines. This portion of the protocol is the
  157. same regardless of ack type, and in fact is used to set the ack type of
  158. the ProtocolGraphWalker.
  159. :param heads: a dict of refname->SHA1 to advertise
  160. :return: a list of SHA1s requested by the client
  161. """
  162. if not heads:
  163. raise GitProtocolError('No heads found')
  164. values = set(heads.itervalues())
  165. for i, (ref, sha) in enumerate(heads.iteritems()):
  166. line = "%s %s" % (sha, ref)
  167. if not i:
  168. line = "%s\x00%s" % (line, self.handler.capabilities())
  169. self.proto.write_pkt_line("%s\n" % line)
  170. # TODO: include peeled value of any tags
  171. # i'm done..
  172. self.proto.write_pkt_line(None)
  173. # Now client will sending want want want commands
  174. want = self.proto.read_pkt_line()
  175. if not want:
  176. return []
  177. line, caps = extract_want_line_capabilities(want)
  178. self.handler.client_capabilities = caps
  179. self.set_ack_type(ack_type(caps))
  180. command, sha = self._split_proto_line(line)
  181. want_revs = []
  182. while command != None:
  183. if command != 'want':
  184. raise GitProtocolError(
  185. 'Protocol got unexpected command %s' % command)
  186. if sha not in values:
  187. raise GitProtocolError(
  188. 'Client wants invalid object %s' % sha)
  189. want_revs.append(sha)
  190. command, sha = self.read_proto_line()
  191. self.set_wants(want_revs)
  192. return want_revs
  193. def ack(self, have_ref):
  194. return self._impl.ack(have_ref)
  195. def reset(self):
  196. self._cached = True
  197. self._cache_index = 0
  198. def next(self):
  199. if not self._cached:
  200. if not self._impl:
  201. return None
  202. return self._impl.next()
  203. self._cache_index += 1
  204. if self._cache_index > len(self._cache):
  205. return None
  206. return self._cache[self._cache_index]
  207. def _split_proto_line(self, line):
  208. fields = line.rstrip('\n').split(' ', 1)
  209. if len(fields) == 1 and fields[0] == 'done':
  210. return ('done', None)
  211. elif len(fields) == 2 and fields[0] in ('want', 'have'):
  212. try:
  213. hex_to_sha(fields[1])
  214. return tuple(fields)
  215. except (TypeError, AssertionError), e:
  216. raise GitProtocolError(e)
  217. raise GitProtocolError('Received invalid line from client:\n%s' % line)
  218. def read_proto_line(self):
  219. """Read a line from the wire.
  220. :return: a tuple having one of the following forms:
  221. ('want', obj_id)
  222. ('have', obj_id)
  223. ('done', None)
  224. (None, None) (for a flush-pkt)
  225. """
  226. line = self.proto.read_pkt_line()
  227. if not line:
  228. return (None, None)
  229. return self._split_proto_line(line)
  230. def send_ack(self, sha, ack_type=''):
  231. if ack_type:
  232. ack_type = ' %s' % ack_type
  233. self.proto.write_pkt_line('ACK %s%s\n' % (sha, ack_type))
  234. def send_nak(self):
  235. self.proto.write_pkt_line('NAK\n')
  236. def set_wants(self, wants):
  237. self._wants = wants
  238. def _is_satisfied(self, haves, want, earliest):
  239. """Check whether a want is satisfied by a set of haves.
  240. A want, typically a branch tip, is "satisfied" only if there exists a
  241. path back from that want to one of the haves.
  242. :param haves: A set of commits we know the client has.
  243. :param want: The want to check satisfaction for.
  244. :param earliest: A timestamp beyond which the search for haves will be
  245. terminated, presumably because we're searching too far down the
  246. wrong branch.
  247. """
  248. o = self.store[want]
  249. pending = collections.deque([o])
  250. while pending:
  251. commit = pending.popleft()
  252. if commit.id in haves:
  253. return True
  254. if not getattr(commit, 'get_parents', None):
  255. # non-commit wants are assumed to be satisfied
  256. continue
  257. for parent in commit.get_parents():
  258. parent_obj = self.store[parent]
  259. # TODO: handle parents with later commit times than children
  260. if parent_obj.commit_time >= earliest:
  261. pending.append(parent_obj)
  262. return False
  263. def all_wants_satisfied(self, haves):
  264. """Check whether all the current wants are satisfied by a set of haves.
  265. :param haves: A set of commits we know the client has.
  266. :note: Wants are specified with set_wants rather than passed in since
  267. in the current interface they are determined outside this class.
  268. """
  269. haves = set(haves)
  270. earliest = min([self.store[h].commit_time for h in haves])
  271. for want in self._wants:
  272. if not self._is_satisfied(haves, want, earliest):
  273. return False
  274. return True
  275. def set_ack_type(self, ack_type):
  276. impl_classes = {
  277. MULTI_ACK: MultiAckGraphWalkerImpl,
  278. SINGLE_ACK: SingleAckGraphWalkerImpl,
  279. }
  280. self._impl = impl_classes[ack_type](self)
  281. class SingleAckGraphWalkerImpl(object):
  282. """Graph walker implementation that speaks the single-ack protocol."""
  283. def __init__(self, walker):
  284. self.walker = walker
  285. self._sent_ack = False
  286. def ack(self, have_ref):
  287. if not self._sent_ack:
  288. self.walker.send_ack(have_ref)
  289. self._sent_ack = True
  290. def next(self):
  291. command, sha = self.walker.read_proto_line()
  292. if command in (None, 'done'):
  293. if not self._sent_ack:
  294. self.walker.send_nak()
  295. return None
  296. elif command == 'have':
  297. return sha
  298. class MultiAckGraphWalkerImpl(object):
  299. """Graph walker implementation that speaks the multi-ack protocol."""
  300. def __init__(self, walker):
  301. self.walker = walker
  302. self._found_base = False
  303. self._common = []
  304. def ack(self, have_ref):
  305. self._common.append(have_ref)
  306. if not self._found_base:
  307. self.walker.send_ack(have_ref, 'continue')
  308. if self.walker.all_wants_satisfied(self._common):
  309. self._found_base = True
  310. # else we blind ack within next
  311. def next(self):
  312. while True:
  313. command, sha = self.walker.read_proto_line()
  314. if command is None:
  315. self.walker.send_nak()
  316. # in multi-ack mode, a flush-pkt indicates the client wants to
  317. # flush but more have lines are still coming
  318. continue
  319. elif command == 'done':
  320. # don't nak unless no common commits were found, even if not
  321. # everything is satisfied
  322. if self._common:
  323. self.walker.send_ack(self._common[-1])
  324. else:
  325. self.walker.send_nak()
  326. return None
  327. elif command == 'have':
  328. if self._found_base:
  329. # blind ack
  330. self.walker.send_ack(sha, 'continue')
  331. return sha
  332. class ReceivePackHandler(Handler):
  333. """Protocol handler for downloading a pack to the client."""
  334. def __init__(self, backend, read, write,
  335. stateless_rpc=False, advertise_refs=False):
  336. Handler.__init__(self, backend, read, write)
  337. self._stateless_rpc = stateless_rpc
  338. self._advertise_refs = advertise_refs
  339. def default_capabilities(self):
  340. return ("report-status", "delete-refs")
  341. def handle(self):
  342. refs = self.backend.get_refs().items()
  343. if refs:
  344. self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
  345. for i in range(1, len(refs)):
  346. ref = refs[i]
  347. self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
  348. else:
  349. self.proto.write_pkt_line("0000000000000000000000000000000000000000 capabilities^{} %s" % self.capabilities())
  350. self.proto.write("0000")
  351. client_refs = []
  352. ref = self.proto.read_pkt_line()
  353. # if ref is none then client doesnt want to send us anything..
  354. if ref is None:
  355. return
  356. ref, client_capabilities = extract_capabilities(ref)
  357. # client will now send us a list of (oldsha, newsha, ref)
  358. while ref:
  359. client_refs.append(ref.split())
  360. ref = self.proto.read_pkt_line()
  361. # backend can now deal with this refs and read a pack using self.read
  362. self.backend.apply_pack(client_refs, self.proto.read)
  363. # when we have read all the pack from the client, it assumes
  364. # everything worked OK.
  365. # there is NO ack from the server before it reports victory.
  366. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  367. def handle(self):
  368. proto = Protocol(self.rfile.read, self.wfile.write)
  369. command, args = proto.read_cmd()
  370. # switch case to handle the specific git command
  371. if command == 'git-upload-pack':
  372. cls = UploadPackHandler
  373. elif command == 'git-receive-pack':
  374. cls = ReceivePackHandler
  375. else:
  376. return
  377. h = cls(self.server.backend, self.rfile.read, self.wfile.write)
  378. h.handle()
  379. class TCPGitServer(SocketServer.TCPServer):
  380. allow_reuse_address = True
  381. serve = SocketServer.TCPServer.serve_forever
  382. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
  383. self.backend = backend
  384. SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)