server.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. # server.py -- Implementation of the server side git protocols
  2. # Copyright (C) 2008 John Carr <john.carr@unrouted.co.uk>
  3. # Coprygith (C) 2011-2012 Jelmer Vernooij <jelmer@samba.org>
  4. #
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Git smart network protocol server implementation.
  22. For more detailed implementation on the network protocol, see the
  23. Documentation/technical directory in the cgit distribution, and in particular:
  24. * Documentation/technical/protocol-capabilities.txt
  25. * Documentation/technical/pack-protocol.txt
  26. Currently supported capabilities:
  27. * include-tag
  28. * thin-pack
  29. * multi_ack_detailed
  30. * multi_ack
  31. * side-band-64k
  32. * ofs-delta
  33. * no-progress
  34. * report-status
  35. * delete-refs
  36. * shallow
  37. """
  38. import collections
  39. import os
  40. import socket
  41. import sys
  42. import zlib
  43. try:
  44. import SocketServer
  45. except ImportError:
  46. import socketserver as SocketServer
  47. from dulwich.errors import (
  48. ApplyDeltaError,
  49. ChecksumMismatch,
  50. GitProtocolError,
  51. NotGitRepository,
  52. UnexpectedCommandError,
  53. ObjectFormatException,
  54. )
  55. from dulwich import log_utils
  56. from dulwich.objects import (
  57. Commit,
  58. valid_hexsha,
  59. )
  60. from dulwich.pack import (
  61. write_pack_objects,
  62. )
  63. from dulwich.protocol import (
  64. BufferedPktLineWriter,
  65. capability_agent,
  66. CAPABILITIES_REF,
  67. CAPABILITY_DELETE_REFS,
  68. CAPABILITY_INCLUDE_TAG,
  69. CAPABILITY_MULTI_ACK_DETAILED,
  70. CAPABILITY_MULTI_ACK,
  71. CAPABILITY_NO_DONE,
  72. CAPABILITY_NO_PROGRESS,
  73. CAPABILITY_OFS_DELTA,
  74. CAPABILITY_QUIET,
  75. CAPABILITY_REPORT_STATUS,
  76. CAPABILITY_SHALLOW,
  77. CAPABILITY_SIDE_BAND_64K,
  78. CAPABILITY_THIN_PACK,
  79. COMMAND_DEEPEN,
  80. COMMAND_DONE,
  81. COMMAND_HAVE,
  82. COMMAND_SHALLOW,
  83. COMMAND_UNSHALLOW,
  84. COMMAND_WANT,
  85. MULTI_ACK,
  86. MULTI_ACK_DETAILED,
  87. Protocol,
  88. ProtocolFile,
  89. ReceivableProtocol,
  90. SIDE_BAND_CHANNEL_DATA,
  91. SIDE_BAND_CHANNEL_PROGRESS,
  92. SIDE_BAND_CHANNEL_FATAL,
  93. SINGLE_ACK,
  94. TCP_GIT_PORT,
  95. ZERO_SHA,
  96. ack_type,
  97. extract_capabilities,
  98. extract_want_line_capabilities,
  99. )
  100. from dulwich.refs import (
  101. ANNOTATED_TAG_SUFFIX,
  102. write_info_refs,
  103. )
  104. from dulwich.repo import (
  105. Repo,
  106. )
  107. logger = log_utils.getLogger(__name__)
  108. class Backend(object):
  109. """A backend for the Git smart server implementation."""
  110. def open_repository(self, path):
  111. """Open the repository at a path.
  112. :param path: Path to the repository
  113. :raise NotGitRepository: no git repository was found at path
  114. :return: Instance of BackendRepo
  115. """
  116. raise NotImplementedError(self.open_repository)
  117. class BackendRepo(object):
  118. """Repository abstraction used by the Git server.
  119. The methods required here are a subset of those provided by
  120. dulwich.repo.Repo.
  121. """
  122. object_store = None
  123. refs = None
  124. def get_refs(self):
  125. """
  126. Get all the refs in the repository
  127. :return: dict of name -> sha
  128. """
  129. raise NotImplementedError
  130. def get_peeled(self, name):
  131. """Return the cached peeled value of a ref, if available.
  132. :param name: Name of the ref to peel
  133. :return: The peeled value of the ref. If the ref is known not point to
  134. a tag, this will be the SHA the ref refers to. If no cached
  135. information about a tag is available, this method may return None,
  136. but it should attempt to peel the tag if possible.
  137. """
  138. return None
  139. def fetch_objects(self, determine_wants, graph_walker, progress,
  140. get_tagged=None):
  141. """
  142. Yield the objects required for a list of commits.
  143. :param progress: is a callback to send progress messages to the client
  144. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  145. sha for including tags.
  146. """
  147. raise NotImplementedError
  148. class DictBackend(Backend):
  149. """Trivial backend that looks up Git repositories in a dictionary."""
  150. def __init__(self, repos):
  151. self.repos = repos
  152. def open_repository(self, path):
  153. logger.debug('Opening repository at %s', path)
  154. try:
  155. return self.repos[path]
  156. except KeyError:
  157. raise NotGitRepository(
  158. "No git repository was found at %(path)s" % dict(path=path)
  159. )
  160. class FileSystemBackend(Backend):
  161. """Simple backend that looks up Git repositories in the local file system."""
  162. def __init__(self, root=os.sep):
  163. super(FileSystemBackend, self).__init__()
  164. self.root = (os.path.abspath(root) + os.sep).replace(os.sep * 2, os.sep)
  165. def open_repository(self, path):
  166. logger.debug('opening repository at %s', path)
  167. abspath = os.path.abspath(os.path.join(self.root, path)) + os.sep
  168. normcase_abspath = os.path.normcase(abspath)
  169. normcase_root = os.path.normcase(self.root)
  170. if not normcase_abspath.startswith(normcase_root):
  171. raise NotGitRepository("Path %r not inside root %r" % (path, self.root))
  172. return Repo(abspath)
  173. class Handler(object):
  174. """Smart protocol command handler base class."""
  175. def __init__(self, backend, proto, http_req=None):
  176. self.backend = backend
  177. self.proto = proto
  178. self.http_req = http_req
  179. def handle(self):
  180. raise NotImplementedError(self.handle)
  181. class PackHandler(Handler):
  182. """Protocol handler for packs."""
  183. def __init__(self, backend, proto, http_req=None):
  184. super(PackHandler, self).__init__(backend, proto, http_req)
  185. self._client_capabilities = None
  186. # Flags needed for the no-done capability
  187. self._done_received = False
  188. @classmethod
  189. def capability_line(cls):
  190. return b"".join([b" " + c for c in cls.capabilities()])
  191. @classmethod
  192. def capabilities(cls):
  193. raise NotImplementedError(cls.capabilities)
  194. @classmethod
  195. def innocuous_capabilities(cls):
  196. return (CAPABILITY_INCLUDE_TAG, CAPABILITY_THIN_PACK,
  197. CAPABILITY_NO_PROGRESS, CAPABILITY_OFS_DELTA,
  198. capability_agent())
  199. @classmethod
  200. def required_capabilities(cls):
  201. """Return a list of capabilities that we require the client to have."""
  202. return []
  203. def set_client_capabilities(self, caps):
  204. allowable_caps = set(self.innocuous_capabilities())
  205. allowable_caps.update(self.capabilities())
  206. for cap in caps:
  207. if cap not in allowable_caps:
  208. raise GitProtocolError('Client asked for capability %s that '
  209. 'was not advertised.' % cap)
  210. for cap in self.required_capabilities():
  211. if cap not in caps:
  212. raise GitProtocolError('Client does not support required '
  213. 'capability %s.' % cap)
  214. self._client_capabilities = set(caps)
  215. logger.info('Client capabilities: %s', caps)
  216. def has_capability(self, cap):
  217. if self._client_capabilities is None:
  218. raise GitProtocolError('Server attempted to access capability %s '
  219. 'before asking client' % cap)
  220. return cap in self._client_capabilities
  221. def notify_done(self):
  222. self._done_received = True
  223. class UploadPackHandler(PackHandler):
  224. """Protocol handler for uploading a pack to the client."""
  225. def __init__(self, backend, args, proto, http_req=None,
  226. advertise_refs=False):
  227. super(UploadPackHandler, self).__init__(backend, proto,
  228. http_req=http_req)
  229. self.repo = backend.open_repository(args[0])
  230. self._graph_walker = None
  231. self.advertise_refs = advertise_refs
  232. # A state variable for denoting that the have list is still
  233. # being processed, and the client is not accepting any other
  234. # data (such as side-band, see the progress method here).
  235. self._processing_have_lines = False
  236. @classmethod
  237. def capabilities(cls):
  238. return (CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_MULTI_ACK,
  239. CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK,
  240. CAPABILITY_OFS_DELTA, CAPABILITY_NO_PROGRESS,
  241. CAPABILITY_INCLUDE_TAG, CAPABILITY_SHALLOW, CAPABILITY_NO_DONE)
  242. @classmethod
  243. def required_capabilities(cls):
  244. return (CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK, CAPABILITY_OFS_DELTA)
  245. def progress(self, message):
  246. if self.has_capability(CAPABILITY_NO_PROGRESS) or self._processing_have_lines:
  247. return
  248. self.proto.write_sideband(SIDE_BAND_CHANNEL_PROGRESS, message)
  249. def get_tagged(self, refs=None, repo=None):
  250. """Get a dict of peeled values of tags to their original tag shas.
  251. :param refs: dict of refname -> sha of possible tags; defaults to all of
  252. the backend's refs.
  253. :param repo: optional Repo instance for getting peeled refs; defaults to
  254. the backend's repo, if available
  255. :return: dict of peeled_sha -> tag_sha, where tag_sha is the sha of a
  256. tag whose peeled value is peeled_sha.
  257. """
  258. if not self.has_capability(CAPABILITY_INCLUDE_TAG):
  259. return {}
  260. if refs is None:
  261. refs = self.repo.get_refs()
  262. if repo is None:
  263. repo = getattr(self.repo, "repo", None)
  264. if repo is None:
  265. # Bail if we don't have a Repo available; this is ok since
  266. # clients must be able to handle if the server doesn't include
  267. # all relevant tags.
  268. # TODO: fix behavior when missing
  269. return {}
  270. tagged = {}
  271. for name, sha in refs.items():
  272. peeled_sha = repo.get_peeled(name)
  273. if peeled_sha != sha:
  274. tagged[peeled_sha] = sha
  275. return tagged
  276. def handle(self):
  277. write = lambda x: self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, x)
  278. graph_walker = ProtocolGraphWalker(self, self.repo.object_store,
  279. self.repo.get_peeled)
  280. objects_iter = self.repo.fetch_objects(
  281. graph_walker.determine_wants, graph_walker, self.progress,
  282. get_tagged=self.get_tagged)
  283. # Note the fact that client is only processing responses related
  284. # to the have lines it sent, and any other data (including side-
  285. # band) will be be considered a fatal error.
  286. self._processing_have_lines = True
  287. # Did the process short-circuit (e.g. in a stateless RPC call)? Note
  288. # that the client still expects a 0-object pack in most cases.
  289. # Also, if it also happens that the object_iter is instantiated
  290. # with a graph walker with an implementation that talks over the
  291. # wire (which is this instance of this class) this will actually
  292. # iterate through everything and write things out to the wire.
  293. if len(objects_iter) == 0:
  294. return
  295. # The provided haves are processed, and it is safe to send side-
  296. # band data now.
  297. self._processing_have_lines = False
  298. if not graph_walker.handle_done(
  299. not self.has_capability(CAPABILITY_NO_DONE), self._done_received):
  300. return
  301. self.progress(b"dul-daemon says what\n")
  302. self.progress(("counting objects: %d, done.\n" % len(objects_iter)).encode('ascii'))
  303. write_pack_objects(ProtocolFile(None, write), objects_iter)
  304. self.progress(b"how was that, then?\n")
  305. # we are done
  306. self.proto.write_pkt_line(None)
  307. def _split_proto_line(line, allowed):
  308. """Split a line read from the wire.
  309. :param line: The line read from the wire.
  310. :param allowed: An iterable of command names that should be allowed.
  311. Command names not listed below as possible return values will be
  312. ignored. If None, any commands from the possible return values are
  313. allowed.
  314. :return: a tuple having one of the following forms:
  315. ('want', obj_id)
  316. ('have', obj_id)
  317. ('done', None)
  318. (None, None) (for a flush-pkt)
  319. :raise UnexpectedCommandError: if the line cannot be parsed into one of the
  320. allowed return values.
  321. """
  322. if not line:
  323. fields = [None]
  324. else:
  325. fields = line.rstrip(b'\n').split(b' ', 1)
  326. command = fields[0]
  327. if allowed is not None and command not in allowed:
  328. raise UnexpectedCommandError(command)
  329. if len(fields) == 1 and command in (COMMAND_DONE, None):
  330. return (command, None)
  331. elif len(fields) == 2:
  332. if command in (COMMAND_WANT, COMMAND_HAVE, COMMAND_SHALLOW,
  333. COMMAND_UNSHALLOW):
  334. if not valid_hexsha(fields[1]):
  335. raise GitProtocolError("Invalid sha")
  336. return tuple(fields)
  337. elif command == COMMAND_DEEPEN:
  338. return command, int(fields[1])
  339. raise GitProtocolError('Received invalid line from client: %r' % line)
  340. def _find_shallow(store, heads, depth):
  341. """Find shallow commits according to a given depth.
  342. :param store: An ObjectStore for looking up objects.
  343. :param heads: Iterable of head SHAs to start walking from.
  344. :param depth: The depth of ancestors to include. A depth of one includes
  345. only the heads themselves.
  346. :return: A tuple of (shallow, not_shallow), sets of SHAs that should be
  347. considered shallow and unshallow according to the arguments. Note that
  348. these sets may overlap if a commit is reachable along multiple paths.
  349. """
  350. parents = {}
  351. def get_parents(sha):
  352. result = parents.get(sha, None)
  353. if not result:
  354. result = store[sha].parents
  355. parents[sha] = result
  356. return result
  357. todo = [] # stack of (sha, depth)
  358. for head_sha in heads:
  359. obj = store.peel_sha(head_sha)
  360. if isinstance(obj, Commit):
  361. todo.append((obj.id, 1))
  362. not_shallow = set()
  363. shallow = set()
  364. while todo:
  365. sha, cur_depth = todo.pop()
  366. if cur_depth < depth:
  367. not_shallow.add(sha)
  368. new_depth = cur_depth + 1
  369. todo.extend((p, new_depth) for p in get_parents(sha))
  370. else:
  371. shallow.add(sha)
  372. return shallow, not_shallow
  373. def _want_satisfied(store, haves, want, earliest):
  374. o = store[want]
  375. pending = collections.deque([o])
  376. while pending:
  377. commit = pending.popleft()
  378. if commit.id in haves:
  379. return True
  380. if commit.type_name != b"commit":
  381. # non-commit wants are assumed to be satisfied
  382. continue
  383. for parent in commit.parents:
  384. parent_obj = store[parent]
  385. # TODO: handle parents with later commit times than children
  386. if parent_obj.commit_time >= earliest:
  387. pending.append(parent_obj)
  388. return False
  389. def _all_wants_satisfied(store, haves, wants):
  390. """Check whether all the current wants are satisfied by a set of haves.
  391. :param store: Object store to retrieve objects from
  392. :param haves: A set of commits we know the client has.
  393. :param wants: A set of commits the client wants
  394. :note: Wants are specified with set_wants rather than passed in since
  395. in the current interface they are determined outside this class.
  396. """
  397. haves = set(haves)
  398. if haves:
  399. earliest = min([store[h].commit_time for h in haves])
  400. else:
  401. earliest = 0
  402. for want in wants:
  403. if not _want_satisfied(store, haves, want, earliest):
  404. return False
  405. return True
  406. class ProtocolGraphWalker(object):
  407. """A graph walker that knows the git protocol.
  408. As a graph walker, this class implements ack(), next(), and reset(). It
  409. also contains some base methods for interacting with the wire and walking
  410. the commit tree.
  411. The work of determining which acks to send is passed on to the
  412. implementation instance stored in _impl. The reason for this is that we do
  413. not know at object creation time what ack level the protocol requires. A
  414. call to set_ack_level() is required to set up the implementation, before any
  415. calls to next() or ack() are made.
  416. """
  417. def __init__(self, handler, object_store, get_peeled):
  418. self.handler = handler
  419. self.store = object_store
  420. self.get_peeled = get_peeled
  421. self.proto = handler.proto
  422. self.http_req = handler.http_req
  423. self.advertise_refs = handler.advertise_refs
  424. self._wants = []
  425. self.shallow = set()
  426. self.client_shallow = set()
  427. self.unshallow = set()
  428. self._cached = False
  429. self._cache = []
  430. self._cache_index = 0
  431. self._impl = None
  432. def determine_wants(self, heads):
  433. """Determine the wants for a set of heads.
  434. The given heads are advertised to the client, who then specifies which
  435. refs he wants using 'want' lines. This portion of the protocol is the
  436. same regardless of ack type, and in fact is used to set the ack type of
  437. the ProtocolGraphWalker.
  438. If the client has the 'shallow' capability, this method also reads and
  439. responds to the 'shallow' and 'deepen' lines from the client. These are
  440. not part of the wants per se, but they set up necessary state for
  441. walking the graph. Additionally, later code depends on this method
  442. consuming everything up to the first 'have' line.
  443. :param heads: a dict of refname->SHA1 to advertise
  444. :return: a list of SHA1s requested by the client
  445. """
  446. values = set(heads.values())
  447. if self.advertise_refs or not self.http_req:
  448. for i, (ref, sha) in enumerate(sorted(heads.items())):
  449. line = sha + b' ' + ref
  450. if not i:
  451. line += b'\x00' + self.handler.capability_line()
  452. self.proto.write_pkt_line(line + b'\n')
  453. peeled_sha = self.get_peeled(ref)
  454. if peeled_sha != sha:
  455. self.proto.write_pkt_line(
  456. peeled_sha + b' ' + ref + ANNOTATED_TAG_SUFFIX + b'\n')
  457. # i'm done..
  458. self.proto.write_pkt_line(None)
  459. if self.advertise_refs:
  460. return []
  461. # Now client will sending want want want commands
  462. want = self.proto.read_pkt_line()
  463. if not want:
  464. return []
  465. line, caps = extract_want_line_capabilities(want)
  466. self.handler.set_client_capabilities(caps)
  467. self.set_ack_type(ack_type(caps))
  468. allowed = (COMMAND_WANT, COMMAND_SHALLOW, COMMAND_DEEPEN, None)
  469. command, sha = _split_proto_line(line, allowed)
  470. want_revs = []
  471. while command == COMMAND_WANT:
  472. if sha not in values:
  473. raise GitProtocolError(
  474. 'Client wants invalid object %s' % sha)
  475. want_revs.append(sha)
  476. command, sha = self.read_proto_line(allowed)
  477. self.set_wants(want_revs)
  478. if command in (COMMAND_SHALLOW, COMMAND_DEEPEN):
  479. self.unread_proto_line(command, sha)
  480. self._handle_shallow_request(want_revs)
  481. if self.http_req and self.proto.eof():
  482. # The client may close the socket at this point, expecting a
  483. # flush-pkt from the server. We might be ready to send a packfile at
  484. # this point, so we need to explicitly short-circuit in this case.
  485. return []
  486. return want_revs
  487. def unread_proto_line(self, command, value):
  488. if isinstance(value, int):
  489. value = str(value).encode('ascii')
  490. self.proto.unread_pkt_line(command + b' ' + value)
  491. def ack(self, have_ref):
  492. if len(have_ref) != 40:
  493. raise ValueError("invalid sha %r" % have_ref)
  494. return self._impl.ack(have_ref)
  495. def reset(self):
  496. self._cached = True
  497. self._cache_index = 0
  498. def next(self):
  499. if not self._cached:
  500. if not self._impl and self.http_req:
  501. return None
  502. return next(self._impl)
  503. self._cache_index += 1
  504. if self._cache_index > len(self._cache):
  505. return None
  506. return self._cache[self._cache_index]
  507. __next__ = next
  508. def read_proto_line(self, allowed):
  509. """Read a line from the wire.
  510. :param allowed: An iterable of command names that should be allowed.
  511. :return: A tuple of (command, value); see _split_proto_line.
  512. :raise UnexpectedCommandError: If an error occurred reading the line.
  513. """
  514. return _split_proto_line(self.proto.read_pkt_line(), allowed)
  515. def _handle_shallow_request(self, wants):
  516. while True:
  517. command, val = self.read_proto_line((COMMAND_DEEPEN, COMMAND_SHALLOW))
  518. if command == COMMAND_DEEPEN:
  519. depth = val
  520. break
  521. self.client_shallow.add(val)
  522. self.read_proto_line((None,)) # consume client's flush-pkt
  523. shallow, not_shallow = _find_shallow(self.store, wants, depth)
  524. # Update self.shallow instead of reassigning it since we passed a
  525. # reference to it before this method was called.
  526. self.shallow.update(shallow - not_shallow)
  527. new_shallow = self.shallow - self.client_shallow
  528. unshallow = self.unshallow = not_shallow & self.client_shallow
  529. for sha in sorted(new_shallow):
  530. self.proto.write_pkt_line(COMMAND_SHALLOW + b' ' + sha)
  531. for sha in sorted(unshallow):
  532. self.proto.write_pkt_line(COMMAND_UNSHALLOW + b' ' + sha)
  533. self.proto.write_pkt_line(None)
  534. def notify_done(self):
  535. # relay the message down to the handler.
  536. self.handler.notify_done()
  537. def send_ack(self, sha, ack_type=b''):
  538. if ack_type:
  539. ack_type = b' ' + ack_type
  540. self.proto.write_pkt_line(b'ACK ' + sha + ack_type + b'\n')
  541. def send_nak(self):
  542. self.proto.write_pkt_line(b'NAK\n')
  543. def handle_done(self, done_required, done_received):
  544. # Delegate this to the implementation.
  545. return self._impl.handle_done(done_required, done_received)
  546. def set_wants(self, wants):
  547. self._wants = wants
  548. def all_wants_satisfied(self, haves):
  549. """Check whether all the current wants are satisfied by a set of haves.
  550. :param haves: A set of commits we know the client has.
  551. :note: Wants are specified with set_wants rather than passed in since
  552. in the current interface they are determined outside this class.
  553. """
  554. return _all_wants_satisfied(self.store, haves, self._wants)
  555. def set_ack_type(self, ack_type):
  556. impl_classes = {
  557. MULTI_ACK: MultiAckGraphWalkerImpl,
  558. MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl,
  559. SINGLE_ACK: SingleAckGraphWalkerImpl,
  560. }
  561. self._impl = impl_classes[ack_type](self)
  562. _GRAPH_WALKER_COMMANDS = (COMMAND_HAVE, COMMAND_DONE, None)
  563. class SingleAckGraphWalkerImpl(object):
  564. """Graph walker implementation that speaks the single-ack protocol."""
  565. def __init__(self, walker):
  566. self.walker = walker
  567. self._common = []
  568. def ack(self, have_ref):
  569. if not self._common:
  570. self.walker.send_ack(have_ref)
  571. self._common.append(have_ref)
  572. def next(self):
  573. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  574. if command in (None, COMMAND_DONE):
  575. # defer the handling of done
  576. self.walker.notify_done()
  577. return None
  578. elif command == COMMAND_HAVE:
  579. return sha
  580. __next__ = next
  581. def handle_done(self, done_required, done_received):
  582. if not self._common:
  583. self.walker.send_nak()
  584. if done_required and not done_received:
  585. # we are not done, especially when done is required; skip
  586. # the pack for this request and especially do not handle
  587. # the done.
  588. return False
  589. if not done_received and not self._common:
  590. # Okay we are not actually done then since the walker picked
  591. # up no haves. This is usually triggered when client attempts
  592. # to pull from a source that has no common base_commit.
  593. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  594. # test_multi_ack_stateless_nodone
  595. return False
  596. return True
  597. class MultiAckGraphWalkerImpl(object):
  598. """Graph walker implementation that speaks the multi-ack protocol."""
  599. def __init__(self, walker):
  600. self.walker = walker
  601. self._found_base = False
  602. self._common = []
  603. def ack(self, have_ref):
  604. self._common.append(have_ref)
  605. if not self._found_base:
  606. self.walker.send_ack(have_ref, b'continue')
  607. if self.walker.all_wants_satisfied(self._common):
  608. self._found_base = True
  609. # else we blind ack within next
  610. def next(self):
  611. while True:
  612. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  613. if command is None:
  614. self.walker.send_nak()
  615. # in multi-ack mode, a flush-pkt indicates the client wants to
  616. # flush but more have lines are still coming
  617. continue
  618. elif command == COMMAND_DONE:
  619. self.walker.notify_done()
  620. return None
  621. elif command == COMMAND_HAVE:
  622. if self._found_base:
  623. # blind ack
  624. self.walker.send_ack(sha, b'continue')
  625. return sha
  626. __next__ = next
  627. def handle_done(self, done_required, done_received):
  628. if done_required and not done_received:
  629. # we are not done, especially when done is required; skip
  630. # the pack for this request and especially do not handle
  631. # the done.
  632. return False
  633. if not done_received and not self._common:
  634. # Okay we are not actually done then since the walker picked
  635. # up no haves. This is usually triggered when client attempts
  636. # to pull from a source that has no common base_commit.
  637. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  638. # test_multi_ack_stateless_nodone
  639. return False
  640. # don't nak unless no common commits were found, even if not
  641. # everything is satisfied
  642. if self._common:
  643. self.walker.send_ack(self._common[-1])
  644. else:
  645. self.walker.send_nak()
  646. return True
  647. class MultiAckDetailedGraphWalkerImpl(object):
  648. """Graph walker implementation speaking the multi-ack-detailed protocol."""
  649. def __init__(self, walker):
  650. self.walker = walker
  651. self._common = []
  652. def ack(self, have_ref):
  653. # Should only be called iff have_ref is common
  654. self._common.append(have_ref)
  655. self.walker.send_ack(have_ref, b'common')
  656. def next(self):
  657. while True:
  658. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  659. if command is None:
  660. if self.walker.all_wants_satisfied(self._common):
  661. self.walker.send_ack(self._common[-1], b'ready')
  662. self.walker.send_nak()
  663. if self.walker.http_req:
  664. # The HTTP version of this request a flush-pkt always
  665. # signifies an end of request, so we also return
  666. # nothing here as if we are done (but not really, as
  667. # it depends on whether no-done capability was
  668. # specified and that's handled in handle_done which
  669. # may or may not call post_nodone_check depending on
  670. # that).
  671. return None
  672. elif command == COMMAND_DONE:
  673. # Let the walker know that we got a done.
  674. self.walker.notify_done()
  675. break
  676. elif command == COMMAND_HAVE:
  677. # return the sha and let the caller ACK it with the
  678. # above ack method.
  679. return sha
  680. # don't nak unless no common commits were found, even if not
  681. # everything is satisfied
  682. __next__ = next
  683. def handle_done(self, done_required, done_received):
  684. if done_required and not done_received:
  685. # we are not done, especially when done is required; skip
  686. # the pack for this request and especially do not handle
  687. # the done.
  688. return False
  689. if not done_received and not self._common:
  690. # Okay we are not actually done then since the walker picked
  691. # up no haves. This is usually triggered when client attempts
  692. # to pull from a source that has no common base_commit.
  693. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  694. # test_multi_ack_stateless_nodone
  695. return False
  696. # don't nak unless no common commits were found, even if not
  697. # everything is satisfied
  698. if self._common:
  699. self.walker.send_ack(self._common[-1])
  700. else:
  701. self.walker.send_nak()
  702. return True
  703. class ReceivePackHandler(PackHandler):
  704. """Protocol handler for downloading a pack from the client."""
  705. def __init__(self, backend, args, proto, http_req=None,
  706. advertise_refs=False):
  707. super(ReceivePackHandler, self).__init__(backend, proto,
  708. http_req=http_req)
  709. self.repo = backend.open_repository(args[0])
  710. self.advertise_refs = advertise_refs
  711. @classmethod
  712. def capabilities(cls):
  713. return (CAPABILITY_REPORT_STATUS, CAPABILITY_DELETE_REFS, CAPABILITY_QUIET,
  714. CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K, CAPABILITY_NO_DONE)
  715. def _apply_pack(self, refs):
  716. all_exceptions = (IOError, OSError, ChecksumMismatch, ApplyDeltaError,
  717. AssertionError, socket.error, zlib.error,
  718. ObjectFormatException)
  719. status = []
  720. will_send_pack = False
  721. for command in refs:
  722. if command[1] != ZERO_SHA:
  723. will_send_pack = True
  724. if will_send_pack:
  725. # TODO: more informative error messages than just the exception string
  726. try:
  727. recv = getattr(self.proto, "recv", None)
  728. self.repo.object_store.add_thin_pack(self.proto.read, recv)
  729. status.append((b'unpack', b'ok'))
  730. except all_exceptions as e:
  731. status.append((b'unpack', str(e).replace('\n', '')))
  732. # The pack may still have been moved in, but it may contain broken
  733. # objects. We trust a later GC to clean it up.
  734. else:
  735. # The git protocol want to find a status entry related to unpack process
  736. # even if no pack data has been sent.
  737. status.append((b'unpack', b'ok'))
  738. for oldsha, sha, ref in refs:
  739. ref_status = b'ok'
  740. try:
  741. if sha == ZERO_SHA:
  742. if not CAPABILITY_DELETE_REFS in self.capabilities():
  743. raise GitProtocolError(
  744. 'Attempted to delete refs without delete-refs '
  745. 'capability.')
  746. try:
  747. self.repo.refs.remove_if_equals(ref, oldsha)
  748. except all_exceptions:
  749. ref_status = b'failed to delete'
  750. else:
  751. try:
  752. self.repo.refs.set_if_equals(ref, oldsha, sha)
  753. except all_exceptions:
  754. ref_status = b'failed to write'
  755. except KeyError as e:
  756. ref_status = b'bad ref'
  757. status.append((ref, ref_status))
  758. return status
  759. def _report_status(self, status):
  760. if self.has_capability(CAPABILITY_SIDE_BAND_64K):
  761. writer = BufferedPktLineWriter(
  762. lambda d: self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, d))
  763. write = writer.write
  764. def flush():
  765. writer.flush()
  766. self.proto.write_pkt_line(None)
  767. else:
  768. write = self.proto.write_pkt_line
  769. flush = lambda: None
  770. for name, msg in status:
  771. if name == b'unpack':
  772. write(b'unpack ' + msg + b'\n')
  773. elif msg == b'ok':
  774. write(b'ok ' + name + b'\n')
  775. else:
  776. write(b'ng ' + name + b' ' + msg + b'\n')
  777. write(None)
  778. flush()
  779. def handle(self):
  780. if self.advertise_refs or not self.http_req:
  781. refs = sorted(self.repo.get_refs().items())
  782. if not refs:
  783. refs = [(CAPABILITIES_REF, ZERO_SHA)]
  784. self.proto.write_pkt_line(
  785. refs[0][1] + b' ' + refs[0][0] + b'\0' +
  786. self.capability_line() + b'\n')
  787. for i in range(1, len(refs)):
  788. ref = refs[i]
  789. self.proto.write_pkt_line(ref[1] + b' ' + ref[0] + b'\n')
  790. self.proto.write_pkt_line(None)
  791. if self.advertise_refs:
  792. return
  793. client_refs = []
  794. ref = self.proto.read_pkt_line()
  795. # if ref is none then client doesnt want to send us anything..
  796. if ref is None:
  797. return
  798. ref, caps = extract_capabilities(ref)
  799. self.set_client_capabilities(caps)
  800. # client will now send us a list of (oldsha, newsha, ref)
  801. while ref:
  802. client_refs.append(ref.split())
  803. ref = self.proto.read_pkt_line()
  804. # backend can now deal with this refs and read a pack using self.read
  805. status = self._apply_pack(client_refs)
  806. # when we have read all the pack from the client, send a status report
  807. # if the client asked for it
  808. if self.has_capability(CAPABILITY_REPORT_STATUS):
  809. self._report_status(status)
  810. class UploadArchiveHandler(Handler):
  811. def __init__(self, backend, proto, http_req=None):
  812. super(UploadArchiveHandler, self).__init__(backend, proto, http_req)
  813. def handle(self):
  814. # TODO(jelmer)
  815. raise NotImplementedError(self.handle)
  816. # Default handler classes for git services.
  817. DEFAULT_HANDLERS = {
  818. b'git-upload-pack': UploadPackHandler,
  819. b'git-receive-pack': ReceivePackHandler,
  820. # b'git-upload-archive': UploadArchiveHandler,
  821. }
  822. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  823. def __init__(self, handlers, *args, **kwargs):
  824. self.handlers = handlers
  825. SocketServer.StreamRequestHandler.__init__(self, *args, **kwargs)
  826. def handle(self):
  827. proto = ReceivableProtocol(self.connection.recv, self.wfile.write)
  828. command, args = proto.read_cmd()
  829. logger.info('Handling %s request, args=%s', command, args)
  830. cls = self.handlers.get(command, None)
  831. if not callable(cls):
  832. raise GitProtocolError('Invalid service %s' % command)
  833. h = cls(self.server.backend, args, proto)
  834. h.handle()
  835. class TCPGitServer(SocketServer.TCPServer):
  836. allow_reuse_address = True
  837. serve = SocketServer.TCPServer.serve_forever
  838. def _make_handler(self, *args, **kwargs):
  839. return TCPGitRequestHandler(self.handlers, *args, **kwargs)
  840. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT, handlers=None):
  841. self.handlers = dict(DEFAULT_HANDLERS)
  842. if handlers is not None:
  843. self.handlers.update(handlers)
  844. self.backend = backend
  845. logger.info('Listening for TCP connections on %s:%d', listen_addr, port)
  846. SocketServer.TCPServer.__init__(self, (listen_addr, port),
  847. self._make_handler)
  848. def verify_request(self, request, client_address):
  849. logger.info('Handling request from %s', client_address)
  850. return True
  851. def handle_error(self, request, client_address):
  852. logger.exception('Exception happened during processing of request '
  853. 'from %s', client_address)
  854. def main(argv=sys.argv):
  855. """Entry point for starting a TCP git server."""
  856. import optparse
  857. parser = optparse.OptionParser()
  858. parser.add_option("-l", "--listen_address", dest="listen_address",
  859. default="localhost",
  860. help="Binding IP address.")
  861. parser.add_option("-p", "--port", dest="port", type=int,
  862. default=TCP_GIT_PORT,
  863. help="Binding TCP port.")
  864. options, args = parser.parse_args(argv)
  865. log_utils.default_logging_config()
  866. if len(args) > 1:
  867. gitdir = args[1]
  868. else:
  869. gitdir = '.'
  870. from dulwich import porcelain
  871. porcelain.daemon(gitdir, address=options.listen_address,
  872. port=options.port)
  873. def serve_command(handler_cls, argv=sys.argv, backend=None, inf=sys.stdin,
  874. outf=sys.stdout):
  875. """Serve a single command.
  876. This is mostly useful for the implementation of commands used by e.g. git+ssh.
  877. :param handler_cls: `Handler` class to use for the request
  878. :param argv: execv-style command-line arguments. Defaults to sys.argv.
  879. :param backend: `Backend` to use
  880. :param inf: File-like object to read from, defaults to standard input.
  881. :param outf: File-like object to write to, defaults to standard output.
  882. :return: Exit code for use with sys.exit. 0 on success, 1 on failure.
  883. """
  884. if backend is None:
  885. backend = FileSystemBackend()
  886. def send_fn(data):
  887. outf.write(data)
  888. outf.flush()
  889. proto = Protocol(inf.read, send_fn)
  890. handler = handler_cls(backend, argv[1:], proto)
  891. # FIXME: Catch exceptions and write a single-line summary to outf.
  892. handler.handle()
  893. return 0
  894. def generate_info_refs(repo):
  895. """Generate an info refs file."""
  896. refs = repo.get_refs()
  897. return write_info_refs(refs, repo.object_store)
  898. def generate_objects_info_packs(repo):
  899. """Generate an index for for packs."""
  900. for pack in repo.object_store.packs:
  901. yield b'P ' + pack.data.filename.encode(sys.getfilesystemencoding()) + b'\n'
  902. def update_server_info(repo):
  903. """Generate server info for dumb file access.
  904. This generates info/refs and objects/info/packs,
  905. similar to "git update-server-info".
  906. """
  907. repo._put_named_file(os.path.join('info', 'refs'),
  908. b"".join(generate_info_refs(repo)))
  909. repo._put_named_file(os.path.join('objects', 'info', 'packs'),
  910. b"".join(generate_objects_info_packs(repo)))
  911. if __name__ == '__main__':
  912. main()