server.py 23 KB

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