server.py 44 KB

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