server.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  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 published 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 TYPE_CHECKING, Optional
  50. from typing import Protocol as TypingProtocol
  51. if TYPE_CHECKING:
  52. from .object_store import BaseObjectStore
  53. from dulwich import log_utils
  54. from .archive import tar_stream
  55. from .errors import (
  56. ApplyDeltaError,
  57. ChecksumMismatch,
  58. GitProtocolError,
  59. HookError,
  60. NotGitRepository,
  61. ObjectFormatException,
  62. UnexpectedCommandError,
  63. )
  64. from .object_store import find_shallow
  65. from .objects import Commit, ObjectID, Tree, valid_hexsha
  66. from .pack import ObjectContainer, PackedObjectContainer, write_pack_from_container
  67. from .protocol import (
  68. CAPABILITIES_REF,
  69. CAPABILITY_AGENT,
  70. CAPABILITY_DELETE_REFS,
  71. CAPABILITY_INCLUDE_TAG,
  72. CAPABILITY_MULTI_ACK,
  73. CAPABILITY_MULTI_ACK_DETAILED,
  74. CAPABILITY_NO_DONE,
  75. CAPABILITY_NO_PROGRESS,
  76. CAPABILITY_OFS_DELTA,
  77. CAPABILITY_QUIET,
  78. CAPABILITY_REPORT_STATUS,
  79. CAPABILITY_SHALLOW,
  80. CAPABILITY_SIDE_BAND_64K,
  81. CAPABILITY_THIN_PACK,
  82. COMMAND_DEEPEN,
  83. COMMAND_DONE,
  84. COMMAND_HAVE,
  85. COMMAND_SHALLOW,
  86. COMMAND_UNSHALLOW,
  87. COMMAND_WANT,
  88. MULTI_ACK,
  89. MULTI_ACK_DETAILED,
  90. NAK_LINE,
  91. SIDE_BAND_CHANNEL_DATA,
  92. SIDE_BAND_CHANNEL_FATAL,
  93. SIDE_BAND_CHANNEL_PROGRESS,
  94. SINGLE_ACK,
  95. TCP_GIT_PORT,
  96. ZERO_SHA,
  97. BufferedPktLineWriter,
  98. Protocol,
  99. ReceivableProtocol,
  100. ack_type,
  101. capability_agent,
  102. extract_capabilities,
  103. extract_want_line_capabilities,
  104. format_ack_line,
  105. format_ref_line,
  106. format_shallow_line,
  107. format_unshallow_line,
  108. symref_capabilities,
  109. )
  110. from .refs import PEELED_TAG_SUFFIX, Ref, RefsContainer, write_info_refs
  111. from .repo import Repo
  112. logger = log_utils.getLogger(__name__)
  113. class Backend:
  114. """A backend for the Git smart server implementation."""
  115. def open_repository(self, path) -> "BackendRepo":
  116. """Open the repository at a path.
  117. Args:
  118. path: Path to the repository
  119. Raises:
  120. NotGitRepository: no git repository was found at path
  121. Returns: Instance of BackendRepo
  122. """
  123. raise NotImplementedError(self.open_repository)
  124. class BackendRepo(TypingProtocol):
  125. """Repository abstraction used by the Git server.
  126. The methods required here are a subset of those provided by
  127. dulwich.repo.Repo.
  128. """
  129. object_store: PackedObjectContainer
  130. refs: RefsContainer
  131. def get_refs(self) -> dict[bytes, bytes]:
  132. """Get all the refs in the repository.
  133. Returns: dict of name -> sha
  134. """
  135. raise NotImplementedError
  136. def get_peeled(self, name: bytes) -> Optional[bytes]:
  137. """Return the cached peeled value of a ref, if available.
  138. Args:
  139. name: Name of the ref to peel
  140. Returns: The peeled value of the ref. If the ref is known not point to
  141. a tag, this will be the SHA the ref refers to. If no cached
  142. information about a tag is available, this method may return None,
  143. but it should attempt to peel the tag if possible.
  144. """
  145. return None
  146. def find_missing_objects(
  147. self, determine_wants, graph_walker, progress, get_tagged=None
  148. ) -> Iterator[ObjectID]:
  149. """Yield the objects required for a list of commits.
  150. Args:
  151. determine_wants: Function to determine which objects the client wants
  152. graph_walker: Object used to walk the commit graph
  153. progress: is a callback to send progress messages to the client
  154. get_tagged: Function that returns a dict of pointed-to sha ->
  155. tag sha for including tags.
  156. """
  157. raise NotImplementedError
  158. class DictBackend(Backend):
  159. """Trivial backend that looks up Git repositories in a dictionary."""
  160. def __init__(self, repos) -> None:
  161. """Initialize a DictBackend.
  162. Args:
  163. repos: Dictionary mapping repository paths to BackendRepo instances
  164. """
  165. self.repos = repos
  166. def open_repository(self, path: str) -> BackendRepo:
  167. """Open repository at given path.
  168. Args:
  169. path: Path to the repository
  170. Returns:
  171. Repository object
  172. Raises:
  173. NotGitRepository: If no repository found at path
  174. """
  175. logger.debug("Opening repository at %s", path)
  176. try:
  177. return self.repos[path]
  178. except KeyError as exc:
  179. raise NotGitRepository(
  180. "No git repository was found at {path}".format(**dict(path=path))
  181. ) from exc
  182. class FileSystemBackend(Backend):
  183. """Simple backend looking up Git repositories in the local file system."""
  184. def __init__(self, root=os.sep) -> None:
  185. """Initialize a FileSystemBackend.
  186. Args:
  187. root: Root directory to serve repositories from
  188. """
  189. super().__init__()
  190. self.root = (os.path.abspath(root) + os.sep).replace(os.sep * 2, os.sep)
  191. def open_repository(self, path):
  192. """Open a repository from the filesystem.
  193. Args:
  194. path: Path to the repository relative to the root
  195. Returns: Repo instance
  196. Raises:
  197. NotGitRepository: If path is outside the root or not a git repository
  198. """
  199. logger.debug("opening repository at %s", path)
  200. # Ensure path is a string to avoid TypeError when joining with self.root
  201. path = os.fspath(path)
  202. if isinstance(path, bytes):
  203. path = os.fsdecode(path)
  204. abspath = os.path.abspath(os.path.join(self.root, path)) + os.sep
  205. normcase_abspath = os.path.normcase(abspath)
  206. normcase_root = os.path.normcase(self.root)
  207. if not normcase_abspath.startswith(normcase_root):
  208. raise NotGitRepository(f"Path {path!r} not inside root {self.root!r}")
  209. return Repo(abspath)
  210. class Handler:
  211. """Smart protocol command handler base class."""
  212. def __init__(self, backend, proto, stateless_rpc=False) -> None:
  213. """Initialize a Handler.
  214. Args:
  215. backend: Backend instance for repository access
  216. proto: Protocol instance for communication
  217. stateless_rpc: Whether this is a stateless RPC session
  218. """
  219. self.backend = backend
  220. self.proto = proto
  221. self.stateless_rpc = stateless_rpc
  222. def handle(self) -> None:
  223. """Handle a request."""
  224. raise NotImplementedError(self.handle)
  225. class PackHandler(Handler):
  226. """Protocol handler for packs."""
  227. def __init__(self, backend, proto, stateless_rpc=False) -> None:
  228. """Initialize a PackHandler.
  229. Args:
  230. backend: Backend instance for repository access
  231. proto: Protocol instance for communication
  232. stateless_rpc: Whether this is a stateless RPC session
  233. """
  234. super().__init__(backend, proto, stateless_rpc)
  235. self._client_capabilities: Optional[set[bytes]] = None
  236. # Flags needed for the no-done capability
  237. self._done_received = False
  238. @classmethod
  239. def capabilities(cls) -> Iterable[bytes]:
  240. """Return a list of capabilities supported by this handler."""
  241. raise NotImplementedError(cls.capabilities)
  242. @classmethod
  243. def innocuous_capabilities(cls) -> Iterable[bytes]:
  244. """Return capabilities that don't affect protocol behavior.
  245. Returns:
  246. List of innocuous capability names
  247. """
  248. return [
  249. CAPABILITY_INCLUDE_TAG,
  250. CAPABILITY_THIN_PACK,
  251. CAPABILITY_NO_PROGRESS,
  252. CAPABILITY_OFS_DELTA,
  253. capability_agent(),
  254. ]
  255. @classmethod
  256. def required_capabilities(cls) -> Iterable[bytes]:
  257. """Return a list of capabilities that we require the client to have."""
  258. return []
  259. def set_client_capabilities(self, caps: Iterable[bytes]) -> None:
  260. """Set the client capabilities and validate them.
  261. Args:
  262. caps: List of capabilities requested by the client
  263. Raises:
  264. GitProtocolError: If client requests unsupported capability or lacks required ones
  265. """
  266. allowable_caps = set(self.innocuous_capabilities())
  267. allowable_caps.update(self.capabilities())
  268. for cap in caps:
  269. if cap.startswith(CAPABILITY_AGENT + b"="):
  270. continue
  271. if cap not in allowable_caps:
  272. raise GitProtocolError(
  273. f"Client asked for capability {cap!r} that was not advertised."
  274. )
  275. for cap in self.required_capabilities():
  276. if cap not in caps:
  277. raise GitProtocolError(
  278. f"Client does not support required capability {cap!r}."
  279. )
  280. self._client_capabilities = set(caps)
  281. logger.info("Client capabilities: %s", caps)
  282. def has_capability(self, cap: bytes) -> bool:
  283. """Check if the client supports a specific capability.
  284. Args:
  285. cap: Capability name to check
  286. Returns: True if the client supports the capability
  287. Raises:
  288. GitProtocolError: If called before client capabilities are set
  289. """
  290. if self._client_capabilities is None:
  291. raise GitProtocolError(
  292. f"Server attempted to access capability {cap!r} before asking client"
  293. )
  294. return cap in self._client_capabilities
  295. def notify_done(self) -> None:
  296. """Notify that the 'done' command has been received from the client."""
  297. self._done_received = True
  298. class UploadPackHandler(PackHandler):
  299. """Protocol handler for uploading a pack to the client."""
  300. def __init__(
  301. self, backend, args, proto, stateless_rpc=False, advertise_refs=False
  302. ) -> None:
  303. """Initialize an UploadPackHandler.
  304. Args:
  305. backend: Backend instance for repository access
  306. args: Command arguments (first arg is repository path)
  307. proto: Protocol instance for communication
  308. stateless_rpc: Whether this is a stateless RPC session
  309. advertise_refs: Whether to advertise refs
  310. """
  311. super().__init__(backend, proto, stateless_rpc=stateless_rpc)
  312. self.repo = backend.open_repository(args[0])
  313. self._graph_walker = None
  314. self.advertise_refs = advertise_refs
  315. # A state variable for denoting that the have list is still
  316. # being processed, and the client is not accepting any other
  317. # data (such as side-band, see the progress method here).
  318. self._processing_have_lines = False
  319. @classmethod
  320. def capabilities(cls):
  321. """Return the list of capabilities supported by upload-pack."""
  322. return [
  323. CAPABILITY_MULTI_ACK_DETAILED,
  324. CAPABILITY_MULTI_ACK,
  325. CAPABILITY_SIDE_BAND_64K,
  326. CAPABILITY_THIN_PACK,
  327. CAPABILITY_OFS_DELTA,
  328. CAPABILITY_NO_PROGRESS,
  329. CAPABILITY_INCLUDE_TAG,
  330. CAPABILITY_SHALLOW,
  331. CAPABILITY_NO_DONE,
  332. ]
  333. @classmethod
  334. def required_capabilities(cls):
  335. """Return the list of capabilities required for upload-pack."""
  336. return (
  337. CAPABILITY_SIDE_BAND_64K,
  338. CAPABILITY_THIN_PACK,
  339. CAPABILITY_OFS_DELTA,
  340. )
  341. def progress(self, message: bytes) -> None:
  342. """Send a progress message to the client.
  343. Args:
  344. message: Progress message to send
  345. """
  346. def _start_pack_send_phase(self) -> None:
  347. """Start the pack sending phase, setting up sideband if supported."""
  348. if self.has_capability(CAPABILITY_SIDE_BAND_64K):
  349. # The provided haves are processed, and it is safe to send side-
  350. # band data now.
  351. if not self.has_capability(CAPABILITY_NO_PROGRESS):
  352. self.progress = partial( # type: ignore
  353. self.proto.write_sideband, SIDE_BAND_CHANNEL_PROGRESS
  354. )
  355. self.write_pack_data = partial(
  356. self.proto.write_sideband, SIDE_BAND_CHANNEL_DATA
  357. )
  358. else:
  359. self.write_pack_data = self.proto.write
  360. def get_tagged(self, refs=None, repo=None) -> dict[ObjectID, ObjectID]:
  361. """Get a dict of peeled values of tags to their original tag shas.
  362. Args:
  363. refs: dict of refname -> sha of possible tags; defaults to all
  364. of the backend's refs.
  365. repo: optional Repo instance for getting peeled refs; defaults
  366. to the backend's repo, if available
  367. Returns: dict of peeled_sha -> tag_sha, where tag_sha is the sha of a
  368. tag whose peeled value is peeled_sha.
  369. """
  370. if not self.has_capability(CAPABILITY_INCLUDE_TAG):
  371. return {}
  372. if refs is None:
  373. refs = self.repo.get_refs()
  374. if repo is None:
  375. repo = getattr(self.repo, "repo", None)
  376. if repo is None:
  377. # Bail if we don't have a Repo available; this is ok since
  378. # clients must be able to handle if the server doesn't include
  379. # all relevant tags.
  380. # TODO: fix behavior when missing
  381. return {}
  382. # TODO(jelmer): Integrate this with the refs logic in
  383. # Repo.find_missing_objects
  384. tagged = {}
  385. for name, sha in refs.items():
  386. peeled_sha = repo.get_peeled(name)
  387. if peeled_sha != sha:
  388. tagged[peeled_sha] = sha
  389. return tagged
  390. def handle(self) -> None:
  391. """Handle an upload-pack request.
  392. This method processes the client's wants and haves, determines which
  393. objects to send, and writes the pack data to the client.
  394. """
  395. # Note the fact that client is only processing responses related
  396. # to the have lines it sent, and any other data (including side-
  397. # band) will be be considered a fatal error.
  398. self._processing_have_lines = True
  399. graph_walker = _ProtocolGraphWalker(
  400. self,
  401. self.repo.object_store,
  402. self.repo.get_peeled,
  403. self.repo.refs.get_symrefs,
  404. )
  405. wants = []
  406. def wants_wrapper(refs, **kwargs):
  407. wants.extend(graph_walker.determine_wants(refs, **kwargs))
  408. return wants
  409. missing_objects = self.repo.find_missing_objects(
  410. wants_wrapper,
  411. graph_walker,
  412. self.progress,
  413. get_tagged=self.get_tagged,
  414. )
  415. # Did the process short-circuit (e.g. in a stateless RPC call)? Note
  416. # that the client still expects a 0-object pack in most cases.
  417. # Also, if it also happens that the object_iter is instantiated
  418. # with a graph walker with an implementation that talks over the
  419. # wire (which is this instance of this class) this will actually
  420. # iterate through everything and write things out to the wire.
  421. if len(wants) == 0:
  422. return
  423. # Handle shallow clone case where missing_objects can be None
  424. if missing_objects is None:
  425. return
  426. object_ids = list(missing_objects)
  427. if not graph_walker.handle_done(
  428. not self.has_capability(CAPABILITY_NO_DONE), self._done_received
  429. ):
  430. return
  431. self._start_pack_send_phase()
  432. self.progress((f"counting objects: {len(object_ids)}, done.\n").encode("ascii"))
  433. write_pack_from_container(
  434. self.write_pack_data, self.repo.object_store, object_ids
  435. )
  436. # we are done
  437. self.proto.write_pkt_line(None)
  438. def _split_proto_line(line, allowed):
  439. """Split a line read from the wire.
  440. Args:
  441. line: The line read from the wire.
  442. allowed: An iterable of command names that should be allowed.
  443. Command names not listed below as possible return values will be
  444. ignored. If None, any commands from the possible return values are
  445. allowed.
  446. Returns: a tuple having one of the following forms:
  447. ('want', obj_id)
  448. ('have', obj_id)
  449. ('done', None)
  450. (None, None) (for a flush-pkt)
  451. Raises:
  452. UnexpectedCommandError: if the line cannot be parsed into one of the
  453. allowed return values.
  454. """
  455. if not line:
  456. fields = [None]
  457. else:
  458. fields = line.rstrip(b"\n").split(b" ", 1)
  459. command = fields[0]
  460. if allowed is not None and command not in allowed:
  461. raise UnexpectedCommandError(command)
  462. if len(fields) == 1 and command in (COMMAND_DONE, None):
  463. return (command, None)
  464. elif len(fields) == 2:
  465. if command in (
  466. COMMAND_WANT,
  467. COMMAND_HAVE,
  468. COMMAND_SHALLOW,
  469. COMMAND_UNSHALLOW,
  470. ):
  471. assert fields[1] is not None
  472. if not valid_hexsha(fields[1]):
  473. raise GitProtocolError("Invalid sha")
  474. return tuple(fields)
  475. elif command == COMMAND_DEEPEN:
  476. assert fields[1] is not None
  477. return command, int(fields[1])
  478. raise GitProtocolError(f"Received invalid line from client: {line!r}")
  479. def _want_satisfied(store: ObjectContainer, haves, want, earliest) -> bool:
  480. """Check if a specific want is satisfied by a set of haves.
  481. Args:
  482. store: Object store to retrieve objects from
  483. haves: Set of commit IDs the client has
  484. want: Commit ID the client wants
  485. earliest: Earliest commit time to consider
  486. Returns: True if the want is satisfied by the haves
  487. """
  488. o = store[want]
  489. pending = collections.deque([o])
  490. known = {want}
  491. while pending:
  492. commit = pending.popleft()
  493. if commit.id in haves:
  494. return True
  495. if not isinstance(commit, Commit):
  496. # non-commit wants are assumed to be satisfied
  497. continue
  498. for parent in commit.parents:
  499. if parent in known:
  500. continue
  501. known.add(parent)
  502. parent_obj = store[parent]
  503. assert isinstance(parent_obj, Commit)
  504. # TODO: handle parents with later commit times than children
  505. if parent_obj.commit_time >= earliest:
  506. pending.append(parent_obj)
  507. return False
  508. def _all_wants_satisfied(store: ObjectContainer, haves, wants) -> bool:
  509. """Check whether all the current wants are satisfied by a set of haves.
  510. Args:
  511. store: Object store to retrieve objects from
  512. haves: A set of commits we know the client has.
  513. wants: A set of commits the client wants
  514. Note: Wants are specified with set_wants rather than passed in since
  515. in the current interface they are determined outside this class.
  516. """
  517. haves = set(haves)
  518. if haves:
  519. have_objs = [store[h] for h in haves]
  520. earliest = min([h.commit_time for h in have_objs if isinstance(h, Commit)])
  521. else:
  522. earliest = 0
  523. for want in wants:
  524. if not _want_satisfied(store, haves, want, earliest):
  525. return False
  526. return True
  527. class AckGraphWalkerImpl:
  528. """Base class for acknowledgment graph walker implementations."""
  529. def __init__(self, graph_walker):
  530. """Initialize acknowledgment graph walker.
  531. Args:
  532. graph_walker: Graph walker to wrap
  533. """
  534. raise NotImplementedError
  535. def ack(self, have_ref: ObjectID) -> None:
  536. """Acknowledge a have reference.
  537. Args:
  538. have_ref: Object ID to acknowledge
  539. """
  540. raise NotImplementedError
  541. def handle_done(self, done_required, done_received):
  542. """Handle 'done' packet from client."""
  543. raise NotImplementedError
  544. class _ProtocolGraphWalker:
  545. """A graph walker that knows the git protocol.
  546. As a graph walker, this class implements ack(), next(), and reset(). It
  547. also contains some base methods for interacting with the wire and walking
  548. the commit tree.
  549. The work of determining which acks to send is passed on to the
  550. implementation instance stored in _impl. The reason for this is that we do
  551. not know at object creation time what ack level the protocol requires. A
  552. call to set_ack_type() is required to set up the implementation, before
  553. any calls to next() or ack() are made.
  554. """
  555. def __init__(
  556. self, handler, object_store: ObjectContainer, get_peeled, get_symrefs
  557. ) -> None:
  558. """Initialize a ProtocolGraphWalker.
  559. Args:
  560. handler: Protocol handler instance
  561. object_store: Object store for retrieving objects
  562. get_peeled: Function to get peeled refs
  563. get_symrefs: Function to get symbolic refs
  564. """
  565. self.handler = handler
  566. self.store: ObjectContainer = object_store
  567. self.get_peeled = get_peeled
  568. self.get_symrefs = get_symrefs
  569. self.proto = handler.proto
  570. self.stateless_rpc = handler.stateless_rpc
  571. self.advertise_refs = handler.advertise_refs
  572. self._wants: list[bytes] = []
  573. self.shallow: set[bytes] = set()
  574. self.client_shallow: set[bytes] = set()
  575. self.unshallow: set[bytes] = set()
  576. self._cached = False
  577. self._cache: list[bytes] = []
  578. self._cache_index = 0
  579. self._impl: Optional[AckGraphWalkerImpl] = None
  580. def determine_wants(self, heads, depth=None):
  581. """Determine the wants for a set of heads.
  582. The given heads are advertised to the client, who then specifies which
  583. refs they want using 'want' lines. This portion of the protocol is the
  584. same regardless of ack type, and in fact is used to set the ack type of
  585. the ProtocolGraphWalker.
  586. If the client has the 'shallow' capability, this method also reads and
  587. responds to the 'shallow' and 'deepen' lines from the client. These are
  588. not part of the wants per se, but they set up necessary state for
  589. walking the graph. Additionally, later code depends on this method
  590. consuming everything up to the first 'have' line.
  591. Args:
  592. heads: a dict of refname->SHA1 to advertise
  593. depth: Maximum depth for shallow clones
  594. Returns: a list of SHA1s requested by the client
  595. """
  596. symrefs = self.get_symrefs()
  597. values = set(heads.values())
  598. if self.advertise_refs or not self.stateless_rpc:
  599. for i, (ref, sha) in enumerate(sorted(heads.items())):
  600. try:
  601. peeled_sha = self.get_peeled(ref)
  602. except KeyError:
  603. # Skip refs that are inaccessible
  604. # TODO(jelmer): Integrate with Repo.find_missing_objects refs
  605. # logic.
  606. continue
  607. if i == 0:
  608. logger.info("Sending capabilities: %s", self.handler.capabilities())
  609. line = format_ref_line(
  610. ref,
  611. sha,
  612. self.handler.capabilities()
  613. + symref_capabilities(symrefs.items()),
  614. )
  615. else:
  616. line = format_ref_line(ref, sha)
  617. self.proto.write_pkt_line(line)
  618. if peeled_sha != sha:
  619. self.proto.write_pkt_line(
  620. format_ref_line(ref + PEELED_TAG_SUFFIX, peeled_sha)
  621. )
  622. # i'm done..
  623. self.proto.write_pkt_line(None)
  624. if self.advertise_refs:
  625. return []
  626. # Now client will sending want want want commands
  627. want = self.proto.read_pkt_line()
  628. if not want:
  629. return []
  630. line, caps = extract_want_line_capabilities(want)
  631. self.handler.set_client_capabilities(caps)
  632. self.set_ack_type(ack_type(caps))
  633. allowed = (COMMAND_WANT, COMMAND_SHALLOW, COMMAND_DEEPEN, None)
  634. command, sha = _split_proto_line(line, allowed)
  635. want_revs = []
  636. while command == COMMAND_WANT:
  637. if sha not in values:
  638. raise GitProtocolError(f"Client wants invalid object {sha}")
  639. want_revs.append(sha)
  640. command, sha = self.read_proto_line(allowed)
  641. self.set_wants(want_revs)
  642. if command in (COMMAND_SHALLOW, COMMAND_DEEPEN):
  643. self.unread_proto_line(command, sha)
  644. self._handle_shallow_request(want_revs)
  645. if self.stateless_rpc and self.proto.eof():
  646. # The client may close the socket at this point, expecting a
  647. # flush-pkt from the server. We might be ready to send a packfile
  648. # at this point, so we need to explicitly short-circuit in this
  649. # case.
  650. return []
  651. return want_revs
  652. def unread_proto_line(self, command, value) -> None:
  653. """Push a command back to be read again.
  654. Args:
  655. command: Command name
  656. value: Command value
  657. """
  658. if isinstance(value, int):
  659. value = str(value).encode("ascii")
  660. self.proto.unread_pkt_line(command + b" " + value)
  661. def nak(self) -> None:
  662. """Send a NAK response."""
  663. def ack(self, have_ref):
  664. """Acknowledge a have reference.
  665. Args:
  666. have_ref: SHA to acknowledge (40 bytes hex)
  667. Raises:
  668. ValueError: If have_ref is not 40 bytes
  669. """
  670. if len(have_ref) != 40:
  671. raise ValueError(f"invalid sha {have_ref!r}")
  672. assert self._impl is not None
  673. return self._impl.ack(have_ref)
  674. def reset(self) -> None:
  675. """Reset the graph walker cache."""
  676. self._cached = True
  677. self._cache_index = 0
  678. def next(self):
  679. """Get the next SHA from the graph walker.
  680. Returns: Next SHA or None if done
  681. """
  682. if not self._cached:
  683. if not self._impl and self.stateless_rpc:
  684. return None
  685. assert self._impl is not None
  686. return next(self._impl) # type: ignore[call-overload]
  687. self._cache_index += 1
  688. if self._cache_index > len(self._cache):
  689. return None
  690. return self._cache[self._cache_index]
  691. __next__ = next
  692. def read_proto_line(self, allowed):
  693. """Read a line from the wire.
  694. Args:
  695. allowed: An iterable of command names that should be allowed.
  696. Returns: A tuple of (command, value); see _split_proto_line.
  697. Raises:
  698. UnexpectedCommandError: If an error occurred reading the line.
  699. """
  700. return _split_proto_line(self.proto.read_pkt_line(), allowed)
  701. def _handle_shallow_request(self, wants) -> None:
  702. """Handle shallow clone requests from the client.
  703. Args:
  704. wants: List of wanted object SHAs
  705. """
  706. while True:
  707. command, val = self.read_proto_line((COMMAND_DEEPEN, COMMAND_SHALLOW))
  708. if command == COMMAND_DEEPEN:
  709. depth = val
  710. break
  711. self.client_shallow.add(val)
  712. self.read_proto_line((None,)) # consume client's flush-pkt
  713. shallow, not_shallow = find_shallow(self.store, wants, depth)
  714. # Update self.shallow instead of reassigning it since we passed a
  715. # reference to it before this method was called.
  716. self.shallow.update(shallow - not_shallow)
  717. new_shallow = self.shallow - self.client_shallow
  718. unshallow = self.unshallow = not_shallow & self.client_shallow
  719. self.update_shallow(new_shallow, unshallow)
  720. def update_shallow(self, new_shallow, unshallow):
  721. """Update shallow/unshallow information to the client.
  722. Args:
  723. new_shallow: Set of newly shallow commits
  724. unshallow: Set of commits to unshallow
  725. """
  726. for sha in sorted(new_shallow):
  727. self.proto.write_pkt_line(format_shallow_line(sha))
  728. for sha in sorted(unshallow):
  729. self.proto.write_pkt_line(format_unshallow_line(sha))
  730. self.proto.write_pkt_line(None)
  731. def notify_done(self) -> None:
  732. """Notify that the client sent 'done'."""
  733. # relay the message down to the handler.
  734. self.handler.notify_done()
  735. def send_ack(self, sha, ack_type=b"") -> None:
  736. """Send an ACK to the client.
  737. Args:
  738. sha: SHA to acknowledge
  739. ack_type: Type of ACK (e.g., b'continue', b'ready')
  740. """
  741. self.proto.write_pkt_line(format_ack_line(sha, ack_type))
  742. def send_nak(self) -> None:
  743. """Send a NAK to the client."""
  744. self.proto.write_pkt_line(NAK_LINE)
  745. def handle_done(self, done_required, done_received):
  746. """Handle the 'done' command.
  747. Args:
  748. done_required: Whether done is required
  749. done_received: Whether done was received
  750. Returns: True if done handling succeeded
  751. """
  752. # Delegate this to the implementation.
  753. assert self._impl is not None
  754. return self._impl.handle_done(done_required, done_received)
  755. def set_wants(self, wants) -> None:
  756. """Set the list of wanted objects.
  757. Args:
  758. wants: List of wanted object SHAs
  759. """
  760. self._wants = wants
  761. def all_wants_satisfied(self, haves):
  762. """Check whether all the current wants are satisfied by a set of haves.
  763. Args:
  764. haves: A set of commits we know the client has.
  765. Note: Wants are specified with set_wants rather than passed in since
  766. in the current interface they are determined outside this class.
  767. """
  768. return _all_wants_satisfied(self.store, haves, self._wants)
  769. def set_ack_type(self, ack_type) -> None:
  770. """Set the acknowledgment type for the graph walker.
  771. Args:
  772. ack_type: One of SINGLE_ACK, MULTI_ACK, or MULTI_ACK_DETAILED
  773. """
  774. impl_classes: dict[int, type[AckGraphWalkerImpl]] = {
  775. MULTI_ACK: MultiAckGraphWalkerImpl,
  776. MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl,
  777. SINGLE_ACK: SingleAckGraphWalkerImpl,
  778. }
  779. self._impl = impl_classes[ack_type](self)
  780. _GRAPH_WALKER_COMMANDS = (COMMAND_HAVE, COMMAND_DONE, None)
  781. class SingleAckGraphWalkerImpl(AckGraphWalkerImpl):
  782. """Graph walker implementation that speaks the single-ack protocol."""
  783. def __init__(self, walker) -> None:
  784. """Initialize a SingleAckGraphWalkerImpl.
  785. Args:
  786. walker: Parent ProtocolGraphWalker instance
  787. """
  788. self.walker = walker
  789. self._common: list[bytes] = []
  790. def ack(self, have_ref) -> None:
  791. """Acknowledge a have reference.
  792. Args:
  793. have_ref: Object ID to acknowledge
  794. """
  795. if not self._common:
  796. self.walker.send_ack(have_ref)
  797. self._common.append(have_ref)
  798. def next(self):
  799. """Get next SHA from graph walker.
  800. Returns:
  801. SHA bytes or None if done
  802. """
  803. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  804. if command in (None, COMMAND_DONE):
  805. # defer the handling of done
  806. self.walker.notify_done()
  807. return None
  808. elif command == COMMAND_HAVE:
  809. return sha
  810. __next__ = next
  811. def handle_done(self, done_required, done_received) -> bool:
  812. """Handle done command.
  813. Args:
  814. done_required: Whether done is required
  815. done_received: Whether done was received
  816. Returns:
  817. True if handling completed successfully
  818. """
  819. if not self._common:
  820. self.walker.send_nak()
  821. if done_required and not done_received:
  822. # we are not done, especially when done is required; skip
  823. # the pack for this request and especially do not handle
  824. # the done.
  825. return False
  826. if not done_received and not self._common:
  827. # Okay we are not actually done then since the walker picked
  828. # up no haves. This is usually triggered when client attempts
  829. # to pull from a source that has no common base_commit.
  830. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  831. # test_multi_ack_stateless_nodone
  832. return False
  833. return True
  834. class MultiAckGraphWalkerImpl(AckGraphWalkerImpl):
  835. """Graph walker implementation that speaks the multi-ack protocol."""
  836. def __init__(self, walker) -> None:
  837. """Initialize multi-ack graph walker.
  838. Args:
  839. walker: Parent ProtocolGraphWalker instance
  840. """
  841. self.walker = walker
  842. self._found_base = False
  843. self._common: list[bytes] = []
  844. def ack(self, have_ref) -> None:
  845. """Acknowledge a have reference.
  846. Args:
  847. have_ref: Object ID to acknowledge
  848. """
  849. self._common.append(have_ref)
  850. if not self._found_base:
  851. self.walker.send_ack(have_ref, b"continue")
  852. if self.walker.all_wants_satisfied(self._common):
  853. self._found_base = True
  854. # else we blind ack within next
  855. def next(self):
  856. """Get next SHA from graph walker.
  857. Returns:
  858. SHA bytes or None if done
  859. """
  860. while True:
  861. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  862. if command is None:
  863. self.walker.send_nak()
  864. # in multi-ack mode, a flush-pkt indicates the client wants to
  865. # flush but more have lines are still coming
  866. continue
  867. elif command == COMMAND_DONE:
  868. self.walker.notify_done()
  869. return None
  870. elif command == COMMAND_HAVE:
  871. if self._found_base:
  872. # blind ack
  873. self.walker.send_ack(sha, b"continue")
  874. return sha
  875. __next__ = next
  876. def handle_done(self, done_required, done_received) -> bool:
  877. """Handle done command.
  878. Args:
  879. done_required: Whether done is required
  880. done_received: Whether done was received
  881. Returns:
  882. True if handling completed successfully
  883. """
  884. if done_required and not done_received:
  885. # we are not done, especially when done is required; skip
  886. # the pack for this request and especially do not handle
  887. # the done.
  888. return False
  889. if not done_received and not self._common:
  890. # Okay we are not actually done then since the walker picked
  891. # up no haves. This is usually triggered when client attempts
  892. # to pull from a source that has no common base_commit.
  893. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  894. # test_multi_ack_stateless_nodone
  895. return False
  896. # don't nak unless no common commits were found, even if not
  897. # everything is satisfied
  898. if self._common:
  899. self.walker.send_ack(self._common[-1])
  900. else:
  901. self.walker.send_nak()
  902. return True
  903. class MultiAckDetailedGraphWalkerImpl(AckGraphWalkerImpl):
  904. """Graph walker implementation speaking the multi-ack-detailed protocol."""
  905. def __init__(self, walker) -> None:
  906. """Initialize multi-ack-detailed graph walker.
  907. Args:
  908. walker: Parent ProtocolGraphWalker instance
  909. """
  910. self.walker = walker
  911. self._common: list[bytes] = []
  912. def ack(self, have_ref) -> None:
  913. """Acknowledge a have reference.
  914. Args:
  915. have_ref: Object ID to acknowledge
  916. """
  917. # Should only be called iff have_ref is common
  918. self._common.append(have_ref)
  919. self.walker.send_ack(have_ref, b"common")
  920. def next(self):
  921. """Get next SHA from graph walker.
  922. Returns:
  923. SHA bytes or None if done
  924. """
  925. while True:
  926. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  927. if command is None:
  928. if self.walker.all_wants_satisfied(self._common):
  929. self.walker.send_ack(self._common[-1], b"ready")
  930. self.walker.send_nak()
  931. if self.walker.stateless_rpc:
  932. # The HTTP version of this request a flush-pkt always
  933. # signifies an end of request, so we also return
  934. # nothing here as if we are done (but not really, as
  935. # it depends on whether no-done capability was
  936. # specified and that's handled in handle_done which
  937. # may or may not call post_nodone_check depending on
  938. # that).
  939. return None
  940. elif command == COMMAND_DONE:
  941. # Let the walker know that we got a done.
  942. self.walker.notify_done()
  943. break
  944. elif command == COMMAND_HAVE:
  945. # return the sha and let the caller ACK it with the
  946. # above ack method.
  947. return sha
  948. # don't nak unless no common commits were found, even if not
  949. # everything is satisfied
  950. __next__ = next
  951. def handle_done(self, done_required, done_received) -> bool:
  952. """Handle done command.
  953. Args:
  954. done_required: Whether done is required
  955. done_received: Whether done was received
  956. Returns:
  957. True if handling completed successfully
  958. """
  959. if done_required and not done_received:
  960. # we are not done, especially when done is required; skip
  961. # the pack for this request and especially do not handle
  962. # the done.
  963. return False
  964. if not done_received and not self._common:
  965. # Okay we are not actually done then since the walker picked
  966. # up no haves. This is usually triggered when client attempts
  967. # to pull from a source that has no common base_commit.
  968. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  969. # test_multi_ack_stateless_nodone
  970. return False
  971. # don't nak unless no common commits were found, even if not
  972. # everything is satisfied
  973. if self._common:
  974. self.walker.send_ack(self._common[-1])
  975. else:
  976. self.walker.send_nak()
  977. return True
  978. class ReceivePackHandler(PackHandler):
  979. """Protocol handler for downloading a pack from the client."""
  980. def __init__(
  981. self, backend, args, proto, stateless_rpc=False, advertise_refs=False
  982. ) -> None:
  983. """Initialize receive-pack handler.
  984. Args:
  985. backend: Backend instance
  986. args: Command arguments
  987. proto: Protocol instance
  988. stateless_rpc: Whether to use stateless RPC
  989. advertise_refs: Whether to advertise refs
  990. """
  991. super().__init__(backend, proto, stateless_rpc=stateless_rpc)
  992. self.repo = backend.open_repository(args[0])
  993. self.advertise_refs = advertise_refs
  994. @classmethod
  995. def capabilities(cls) -> Iterable[bytes]:
  996. """Return supported capabilities.
  997. Returns:
  998. List of capability names
  999. """
  1000. return [
  1001. CAPABILITY_REPORT_STATUS,
  1002. CAPABILITY_DELETE_REFS,
  1003. CAPABILITY_QUIET,
  1004. CAPABILITY_OFS_DELTA,
  1005. CAPABILITY_SIDE_BAND_64K,
  1006. CAPABILITY_NO_DONE,
  1007. ]
  1008. def _apply_pack(
  1009. self, refs: list[tuple[ObjectID, ObjectID, Ref]]
  1010. ) -> Iterator[tuple[bytes, bytes]]:
  1011. """Apply received pack to repository.
  1012. Args:
  1013. refs: List of (old_sha, new_sha, ref_name) tuples
  1014. Yields:
  1015. Tuples of (ref_name, error_message) for any errors
  1016. """
  1017. all_exceptions = (
  1018. IOError,
  1019. OSError,
  1020. ChecksumMismatch,
  1021. ApplyDeltaError,
  1022. AssertionError,
  1023. socket.error,
  1024. zlib.error,
  1025. ObjectFormatException,
  1026. )
  1027. will_send_pack = False
  1028. for command in refs:
  1029. if command[1] != ZERO_SHA:
  1030. will_send_pack = True
  1031. if will_send_pack:
  1032. # TODO: more informative error messages than just the exception
  1033. # string
  1034. try:
  1035. recv = getattr(self.proto, "recv", None)
  1036. self.repo.object_store.add_thin_pack(self.proto.read, recv)
  1037. yield (b"unpack", b"ok")
  1038. except all_exceptions as e:
  1039. yield (b"unpack", str(e).replace("\n", "").encode("utf-8"))
  1040. # The pack may still have been moved in, but it may contain
  1041. # broken objects. We trust a later GC to clean it up.
  1042. else:
  1043. # The git protocol want to find a status entry related to unpack
  1044. # process even if no pack data has been sent.
  1045. yield (b"unpack", b"ok")
  1046. for oldsha, sha, ref in refs:
  1047. ref_status = b"ok"
  1048. try:
  1049. if sha == ZERO_SHA:
  1050. if CAPABILITY_DELETE_REFS not in self.capabilities():
  1051. raise GitProtocolError(
  1052. "Attempted to delete refs without delete-refs capability."
  1053. )
  1054. try:
  1055. self.repo.refs.remove_if_equals(ref, oldsha)
  1056. except all_exceptions:
  1057. ref_status = b"failed to delete"
  1058. else:
  1059. try:
  1060. self.repo.refs.set_if_equals(ref, oldsha, sha)
  1061. except all_exceptions:
  1062. ref_status = b"failed to write"
  1063. except KeyError:
  1064. ref_status = b"bad ref"
  1065. yield (ref, ref_status)
  1066. def _report_status(self, status: list[tuple[bytes, bytes]]) -> None:
  1067. """Report status to client.
  1068. Args:
  1069. status: List of (ref_name, status_message) tuples
  1070. """
  1071. if self.has_capability(CAPABILITY_SIDE_BAND_64K):
  1072. writer = BufferedPktLineWriter(
  1073. lambda d: self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, d)
  1074. )
  1075. write = writer.write
  1076. def flush() -> None:
  1077. writer.flush()
  1078. self.proto.write_pkt_line(None)
  1079. else:
  1080. write = self.proto.write_pkt_line
  1081. def flush() -> None:
  1082. pass
  1083. for name, msg in status:
  1084. if name == b"unpack":
  1085. write(b"unpack " + msg + b"\n")
  1086. elif msg == b"ok":
  1087. write(b"ok " + name + b"\n")
  1088. else:
  1089. write(b"ng " + name + b" " + msg + b"\n")
  1090. write(None) # type: ignore
  1091. flush()
  1092. def _on_post_receive(self, client_refs) -> None:
  1093. """Run post-receive hook.
  1094. Args:
  1095. client_refs: Dictionary of ref changes from client
  1096. """
  1097. hook = self.repo.hooks.get("post-receive", None)
  1098. if not hook:
  1099. return
  1100. try:
  1101. output = hook.execute(client_refs)
  1102. if output:
  1103. self.proto.write_sideband(SIDE_BAND_CHANNEL_PROGRESS, output)
  1104. except HookError as err:
  1105. self.proto.write_sideband(SIDE_BAND_CHANNEL_FATAL, str(err).encode("utf-8"))
  1106. def handle(self) -> None:
  1107. """Handle receive-pack request."""
  1108. if self.advertise_refs or not self.stateless_rpc:
  1109. refs = sorted(self.repo.get_refs().items())
  1110. symrefs = sorted(self.repo.refs.get_symrefs().items())
  1111. if not refs:
  1112. refs = [(CAPABILITIES_REF, ZERO_SHA)]
  1113. logger.info("Sending capabilities: %s", self.capabilities())
  1114. self.proto.write_pkt_line(
  1115. format_ref_line(
  1116. refs[0][0],
  1117. refs[0][1],
  1118. list(self.capabilities()) + symref_capabilities(symrefs),
  1119. )
  1120. )
  1121. for i in range(1, len(refs)):
  1122. ref = refs[i]
  1123. self.proto.write_pkt_line(format_ref_line(ref[0], ref[1]))
  1124. self.proto.write_pkt_line(None)
  1125. if self.advertise_refs:
  1126. return
  1127. client_refs = []
  1128. ref = self.proto.read_pkt_line()
  1129. # if ref is none then client doesn't want to send us anything..
  1130. if ref is None:
  1131. return
  1132. ref, caps = extract_capabilities(ref)
  1133. self.set_client_capabilities(caps)
  1134. # client will now send us a list of (oldsha, newsha, ref)
  1135. while ref:
  1136. (oldsha, newsha, ref) = ref.split()
  1137. client_refs.append((oldsha, newsha, ref))
  1138. ref = self.proto.read_pkt_line()
  1139. # backend can now deal with this refs and read a pack using self.read
  1140. status = list(self._apply_pack(client_refs))
  1141. self._on_post_receive(client_refs)
  1142. # when we have read all the pack from the client, send a status report
  1143. # if the client asked for it
  1144. if self.has_capability(CAPABILITY_REPORT_STATUS):
  1145. self._report_status(status)
  1146. class UploadArchiveHandler(Handler):
  1147. """Handler for git-upload-archive requests."""
  1148. def __init__(self, backend, args, proto, stateless_rpc=False) -> None:
  1149. """Initialize upload-archive handler.
  1150. Args:
  1151. backend: Backend instance
  1152. args: Command arguments
  1153. proto: Protocol instance
  1154. stateless_rpc: Whether to use stateless RPC
  1155. """
  1156. super().__init__(backend, proto, stateless_rpc)
  1157. self.repo = backend.open_repository(args[0])
  1158. def handle(self) -> None:
  1159. """Handle upload-archive request."""
  1160. def write(x):
  1161. return self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, x)
  1162. arguments = []
  1163. for pkt in self.proto.read_pkt_seq():
  1164. (key, value) = pkt.split(b" ", 1)
  1165. if key != b"argument":
  1166. raise GitProtocolError(f"unknown command {key}")
  1167. arguments.append(value.rstrip(b"\n"))
  1168. prefix = b""
  1169. format = "tar"
  1170. i = 0
  1171. store: BaseObjectStore = self.repo.object_store
  1172. while i < len(arguments):
  1173. argument = arguments[i]
  1174. if argument == b"--prefix":
  1175. i += 1
  1176. prefix = arguments[i]
  1177. elif argument == b"--format":
  1178. i += 1
  1179. format = arguments[i].decode("ascii")
  1180. else:
  1181. commit_sha = self.repo.refs[argument]
  1182. commit_obj = store[commit_sha]
  1183. assert isinstance(commit_obj, Commit)
  1184. tree_obj = store[commit_obj.tree]
  1185. assert isinstance(tree_obj, Tree)
  1186. tree = tree_obj
  1187. i += 1
  1188. self.proto.write_pkt_line(b"ACK")
  1189. self.proto.write_pkt_line(None)
  1190. for chunk in tar_stream(
  1191. store,
  1192. tree,
  1193. mtime=int(time.time()),
  1194. prefix=prefix,
  1195. format=format, # type: ignore
  1196. ):
  1197. write(chunk)
  1198. self.proto.write_pkt_line(None)
  1199. # Default handler classes for git services.
  1200. DEFAULT_HANDLERS = {
  1201. b"git-upload-pack": UploadPackHandler,
  1202. b"git-receive-pack": ReceivePackHandler,
  1203. b"git-upload-archive": UploadArchiveHandler,
  1204. }
  1205. class TCPGitRequestHandler(socketserver.StreamRequestHandler):
  1206. """TCP request handler for git protocol."""
  1207. def __init__(self, handlers, *args, **kwargs) -> None:
  1208. """Initialize TCP request handler.
  1209. Args:
  1210. handlers: Dictionary mapping commands to handler classes
  1211. *args: Additional arguments for StreamRequestHandler
  1212. **kwargs: Additional keyword arguments for StreamRequestHandler
  1213. """
  1214. self.handlers = handlers
  1215. socketserver.StreamRequestHandler.__init__(self, *args, **kwargs)
  1216. def handle(self) -> None:
  1217. """Handle TCP git request."""
  1218. proto = ReceivableProtocol(self.connection.recv, self.wfile.write)
  1219. command, args = proto.read_cmd()
  1220. logger.info("Handling %s request, args=%s", command, args)
  1221. cls = self.handlers.get(command, None)
  1222. if not callable(cls):
  1223. raise GitProtocolError(f"Invalid service {command!r}")
  1224. h = cls(self.server.backend, args, proto) # type: ignore
  1225. h.handle()
  1226. class TCPGitServer(socketserver.TCPServer):
  1227. """TCP server for git protocol."""
  1228. allow_reuse_address = True
  1229. serve = socketserver.TCPServer.serve_forever
  1230. def _make_handler(self, *args, **kwargs):
  1231. """Create request handler instance.
  1232. Args:
  1233. *args: Handler arguments
  1234. **kwargs: Handler keyword arguments
  1235. Returns:
  1236. TCPGitRequestHandler instance
  1237. """
  1238. return TCPGitRequestHandler(self.handlers, *args, **kwargs)
  1239. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT, handlers=None) -> None:
  1240. """Initialize TCP git server.
  1241. Args:
  1242. backend: Backend instance
  1243. listen_addr: Address to listen on
  1244. port: Port to listen on (default: TCP_GIT_PORT)
  1245. handlers: Optional dictionary of custom handlers
  1246. """
  1247. self.handlers = dict(DEFAULT_HANDLERS)
  1248. if handlers is not None:
  1249. self.handlers.update(handlers)
  1250. self.backend = backend
  1251. logger.info("Listening for TCP connections on %s:%d", listen_addr, port)
  1252. socketserver.TCPServer.__init__(self, (listen_addr, port), self._make_handler)
  1253. def verify_request(self, request, client_address) -> bool:
  1254. """Verify incoming request.
  1255. Args:
  1256. request: Request socket
  1257. client_address: Client address tuple
  1258. Returns:
  1259. True to accept request
  1260. """
  1261. logger.info("Handling request from %s", client_address)
  1262. return True
  1263. def handle_error(self, request, client_address) -> None:
  1264. """Handle request processing errors.
  1265. Args:
  1266. request: Request socket
  1267. client_address: Client address tuple
  1268. """
  1269. logger.exception(
  1270. "Exception happened during processing of request from %s",
  1271. client_address,
  1272. )
  1273. def main(argv=sys.argv) -> None:
  1274. """Entry point for starting a TCP git server."""
  1275. import optparse
  1276. parser = optparse.OptionParser()
  1277. parser.add_option(
  1278. "-l",
  1279. "--listen_address",
  1280. dest="listen_address",
  1281. default="localhost",
  1282. help="Binding IP address.",
  1283. )
  1284. parser.add_option(
  1285. "-p",
  1286. "--port",
  1287. dest="port",
  1288. type=int,
  1289. default=TCP_GIT_PORT,
  1290. help="Binding TCP port.",
  1291. )
  1292. options, args = parser.parse_args(argv)
  1293. log_utils.default_logging_config()
  1294. if len(args) > 1:
  1295. gitdir = args[1]
  1296. else:
  1297. gitdir = "."
  1298. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  1299. backend = FileSystemBackend(gitdir)
  1300. server = TCPGitServer(backend, options.listen_address, options.port)
  1301. server.serve_forever()
  1302. def serve_command(
  1303. handler_cls, argv=sys.argv, backend=None, inf=sys.stdin, outf=sys.stdout
  1304. ) -> int:
  1305. """Serve a single command.
  1306. This is mostly useful for the implementation of commands used by e.g.
  1307. git+ssh.
  1308. Args:
  1309. handler_cls: `Handler` class to use for the request
  1310. argv: execv-style command-line arguments. Defaults to sys.argv.
  1311. backend: `Backend` to use
  1312. inf: File-like object to read from, defaults to standard input.
  1313. outf: File-like object to write to, defaults to standard output.
  1314. Returns: Exit code for use with sys.exit. 0 on success, 1 on failure.
  1315. """
  1316. if backend is None:
  1317. backend = FileSystemBackend()
  1318. def send_fn(data) -> None:
  1319. outf.write(data)
  1320. outf.flush()
  1321. proto = Protocol(inf.read, send_fn)
  1322. handler = handler_cls(backend, argv[1:], proto)
  1323. # FIXME: Catch exceptions and write a single-line summary to outf.
  1324. handler.handle()
  1325. return 0
  1326. def generate_info_refs(repo):
  1327. """Generate an info refs file."""
  1328. refs = repo.get_refs()
  1329. return write_info_refs(refs, repo.object_store)
  1330. def generate_objects_info_packs(repo):
  1331. """Generate an index for for packs."""
  1332. for pack in repo.object_store.packs:
  1333. yield (b"P " + os.fsencode(pack.data.filename) + b"\n")
  1334. def update_server_info(repo) -> None:
  1335. """Generate server info for dumb file access.
  1336. This generates info/refs and objects/info/packs,
  1337. similar to "git update-server-info".
  1338. """
  1339. repo._put_named_file(
  1340. os.path.join("info", "refs"), b"".join(generate_info_refs(repo))
  1341. )
  1342. repo._put_named_file(
  1343. os.path.join("objects", "info", "packs"),
  1344. b"".join(generate_objects_info_packs(repo)),
  1345. )
  1346. if __name__ == "__main__":
  1347. main()