server.py 43 KB

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