server.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  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, cast
  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. if not valid_hexsha(fields[1]):
  472. raise GitProtocolError("Invalid sha")
  473. return tuple(fields)
  474. elif command == COMMAND_DEEPEN:
  475. return command, int(fields[1])
  476. raise GitProtocolError(f"Received invalid line from client: {line!r}")
  477. def _want_satisfied(store: ObjectContainer, haves, want, earliest) -> bool:
  478. """Check if a specific want is satisfied by a set of haves.
  479. Args:
  480. store: Object store to retrieve objects from
  481. haves: Set of commit IDs the client has
  482. want: Commit ID the client wants
  483. earliest: Earliest commit time to consider
  484. Returns: True if the want is satisfied by the haves
  485. """
  486. o = store[want]
  487. pending = collections.deque([o])
  488. known = {want}
  489. while pending:
  490. commit = pending.popleft()
  491. if commit.id in haves:
  492. return True
  493. if not isinstance(commit, Commit):
  494. # non-commit wants are assumed to be satisfied
  495. continue
  496. for parent in commit.parents:
  497. if parent in known:
  498. continue
  499. known.add(parent)
  500. parent_obj = store[parent]
  501. assert isinstance(parent_obj, Commit)
  502. # TODO: handle parents with later commit times than children
  503. if parent_obj.commit_time >= earliest:
  504. pending.append(parent_obj)
  505. return False
  506. def _all_wants_satisfied(store: ObjectContainer, haves, wants) -> bool:
  507. """Check whether all the current wants are satisfied by a set of haves.
  508. Args:
  509. store: Object store to retrieve objects from
  510. haves: A set of commits we know the client has.
  511. wants: A set of commits the client wants
  512. Note: Wants are specified with set_wants rather than passed in since
  513. in the current interface they are determined outside this class.
  514. """
  515. haves = set(haves)
  516. if haves:
  517. have_objs = [store[h] for h in haves]
  518. earliest = min([h.commit_time for h in have_objs if isinstance(h, Commit)])
  519. else:
  520. earliest = 0
  521. for want in wants:
  522. if not _want_satisfied(store, haves, want, earliest):
  523. return False
  524. return True
  525. class AckGraphWalkerImpl:
  526. """Base class for acknowledgment graph walker implementations."""
  527. def __init__(self, graph_walker):
  528. """Initialize acknowledgment graph walker.
  529. Args:
  530. graph_walker: Graph walker to wrap
  531. """
  532. raise NotImplementedError
  533. def ack(self, have_ref: ObjectID) -> None:
  534. """Acknowledge a have reference.
  535. Args:
  536. have_ref: Object ID to acknowledge
  537. """
  538. raise NotImplementedError
  539. class _ProtocolGraphWalker:
  540. """A graph walker that knows the git protocol.
  541. As a graph walker, this class implements ack(), next(), and reset(). It
  542. also contains some base methods for interacting with the wire and walking
  543. the commit tree.
  544. The work of determining which acks to send is passed on to the
  545. implementation instance stored in _impl. The reason for this is that we do
  546. not know at object creation time what ack level the protocol requires. A
  547. call to set_ack_type() is required to set up the implementation, before
  548. any calls to next() or ack() are made.
  549. """
  550. def __init__(
  551. self, handler, object_store: ObjectContainer, get_peeled, get_symrefs
  552. ) -> None:
  553. """Initialize a ProtocolGraphWalker.
  554. Args:
  555. handler: Protocol handler instance
  556. object_store: Object store for retrieving objects
  557. get_peeled: Function to get peeled refs
  558. get_symrefs: Function to get symbolic refs
  559. """
  560. self.handler = handler
  561. self.store: ObjectContainer = object_store
  562. self.get_peeled = get_peeled
  563. self.get_symrefs = get_symrefs
  564. self.proto = handler.proto
  565. self.stateless_rpc = handler.stateless_rpc
  566. self.advertise_refs = handler.advertise_refs
  567. self._wants: list[bytes] = []
  568. self.shallow: set[bytes] = set()
  569. self.client_shallow: set[bytes] = set()
  570. self.unshallow: set[bytes] = set()
  571. self._cached = False
  572. self._cache: list[bytes] = []
  573. self._cache_index = 0
  574. self._impl: Optional[AckGraphWalkerImpl] = None
  575. def determine_wants(self, heads, depth=None):
  576. """Determine the wants for a set of heads.
  577. The given heads are advertised to the client, who then specifies which
  578. refs they want using 'want' lines. This portion of the protocol is the
  579. same regardless of ack type, and in fact is used to set the ack type of
  580. the ProtocolGraphWalker.
  581. If the client has the 'shallow' capability, this method also reads and
  582. responds to the 'shallow' and 'deepen' lines from the client. These are
  583. not part of the wants per se, but they set up necessary state for
  584. walking the graph. Additionally, later code depends on this method
  585. consuming everything up to the first 'have' line.
  586. Args:
  587. heads: a dict of refname->SHA1 to advertise
  588. depth: Maximum depth for shallow clones
  589. Returns: a list of SHA1s requested by the client
  590. """
  591. symrefs = self.get_symrefs()
  592. values = set(heads.values())
  593. if self.advertise_refs or not self.stateless_rpc:
  594. for i, (ref, sha) in enumerate(sorted(heads.items())):
  595. try:
  596. peeled_sha = self.get_peeled(ref)
  597. except KeyError:
  598. # Skip refs that are inaccessible
  599. # TODO(jelmer): Integrate with Repo.find_missing_objects refs
  600. # logic.
  601. continue
  602. if i == 0:
  603. logger.info("Sending capabilities: %s", self.handler.capabilities())
  604. line = format_ref_line(
  605. ref,
  606. sha,
  607. self.handler.capabilities()
  608. + symref_capabilities(symrefs.items()),
  609. )
  610. else:
  611. line = format_ref_line(ref, sha)
  612. self.proto.write_pkt_line(line)
  613. if peeled_sha != sha:
  614. self.proto.write_pkt_line(
  615. format_ref_line(ref + PEELED_TAG_SUFFIX, peeled_sha)
  616. )
  617. # i'm done..
  618. self.proto.write_pkt_line(None)
  619. if self.advertise_refs:
  620. return []
  621. # Now client will sending want want want commands
  622. want = self.proto.read_pkt_line()
  623. if not want:
  624. return []
  625. line, caps = extract_want_line_capabilities(want)
  626. self.handler.set_client_capabilities(caps)
  627. self.set_ack_type(ack_type(caps))
  628. allowed = (COMMAND_WANT, COMMAND_SHALLOW, COMMAND_DEEPEN, None)
  629. command, sha = _split_proto_line(line, allowed)
  630. want_revs = []
  631. while command == COMMAND_WANT:
  632. if sha not in values:
  633. raise GitProtocolError(f"Client wants invalid object {sha}")
  634. want_revs.append(sha)
  635. command, sha = self.read_proto_line(allowed)
  636. self.set_wants(want_revs)
  637. if command in (COMMAND_SHALLOW, COMMAND_DEEPEN):
  638. self.unread_proto_line(command, sha)
  639. self._handle_shallow_request(want_revs)
  640. if self.stateless_rpc and self.proto.eof():
  641. # The client may close the socket at this point, expecting a
  642. # flush-pkt from the server. We might be ready to send a packfile
  643. # at this point, so we need to explicitly short-circuit in this
  644. # case.
  645. return []
  646. return want_revs
  647. def unread_proto_line(self, command, value) -> None:
  648. """Push a command back to be read again.
  649. Args:
  650. command: Command name
  651. value: Command value
  652. """
  653. if isinstance(value, int):
  654. value = str(value).encode("ascii")
  655. self.proto.unread_pkt_line(command + b" " + value)
  656. def nak(self) -> None:
  657. """Send a NAK response."""
  658. def ack(self, have_ref):
  659. """Acknowledge a have reference.
  660. Args:
  661. have_ref: SHA to acknowledge (40 bytes hex)
  662. Raises:
  663. ValueError: If have_ref is not 40 bytes
  664. """
  665. if len(have_ref) != 40:
  666. raise ValueError(f"invalid sha {have_ref!r}")
  667. return self._impl.ack(have_ref)
  668. def reset(self) -> None:
  669. """Reset the graph walker cache."""
  670. self._cached = True
  671. self._cache_index = 0
  672. def next(self):
  673. """Get the next SHA from the graph walker.
  674. Returns: Next SHA or None if done
  675. """
  676. if not self._cached:
  677. if not self._impl and self.stateless_rpc:
  678. return None
  679. return next(self._impl)
  680. self._cache_index += 1
  681. if self._cache_index > len(self._cache):
  682. return None
  683. return self._cache[self._cache_index]
  684. __next__ = next
  685. def read_proto_line(self, allowed):
  686. """Read a line from the wire.
  687. Args:
  688. allowed: An iterable of command names that should be allowed.
  689. Returns: A tuple of (command, value); see _split_proto_line.
  690. Raises:
  691. UnexpectedCommandError: If an error occurred reading the line.
  692. """
  693. return _split_proto_line(self.proto.read_pkt_line(), allowed)
  694. def _handle_shallow_request(self, wants) -> None:
  695. """Handle shallow clone requests from the client.
  696. Args:
  697. wants: List of wanted object SHAs
  698. """
  699. while True:
  700. command, val = self.read_proto_line((COMMAND_DEEPEN, COMMAND_SHALLOW))
  701. if command == COMMAND_DEEPEN:
  702. depth = val
  703. break
  704. self.client_shallow.add(val)
  705. self.read_proto_line((None,)) # consume client's flush-pkt
  706. shallow, not_shallow = find_shallow(self.store, wants, depth)
  707. # Update self.shallow instead of reassigning it since we passed a
  708. # reference to it before this method was called.
  709. self.shallow.update(shallow - not_shallow)
  710. new_shallow = self.shallow - self.client_shallow
  711. unshallow = self.unshallow = not_shallow & self.client_shallow
  712. self.update_shallow(new_shallow, unshallow)
  713. def update_shallow(self, new_shallow, unshallow):
  714. """Update shallow/unshallow information to the client.
  715. Args:
  716. new_shallow: Set of newly shallow commits
  717. unshallow: Set of commits to unshallow
  718. """
  719. for sha in sorted(new_shallow):
  720. self.proto.write_pkt_line(format_shallow_line(sha))
  721. for sha in sorted(unshallow):
  722. self.proto.write_pkt_line(format_unshallow_line(sha))
  723. self.proto.write_pkt_line(None)
  724. def notify_done(self) -> None:
  725. """Notify that the client sent 'done'."""
  726. # relay the message down to the handler.
  727. self.handler.notify_done()
  728. def send_ack(self, sha, ack_type=b"") -> None:
  729. """Send an ACK to the client.
  730. Args:
  731. sha: SHA to acknowledge
  732. ack_type: Type of ACK (e.g., b'continue', b'ready')
  733. """
  734. self.proto.write_pkt_line(format_ack_line(sha, ack_type))
  735. def send_nak(self) -> None:
  736. """Send a NAK to the client."""
  737. self.proto.write_pkt_line(NAK_LINE)
  738. def handle_done(self, done_required, done_received):
  739. """Handle the 'done' command.
  740. Args:
  741. done_required: Whether done is required
  742. done_received: Whether done was received
  743. Returns: True if done handling succeeded
  744. """
  745. # Delegate this to the implementation.
  746. return self._impl.handle_done(done_required, done_received)
  747. def set_wants(self, wants) -> None:
  748. """Set the list of wanted objects.
  749. Args:
  750. wants: List of wanted object SHAs
  751. """
  752. self._wants = wants
  753. def all_wants_satisfied(self, haves):
  754. """Check whether all the current wants are satisfied by a set of haves.
  755. Args:
  756. haves: A set of commits we know the client has.
  757. Note: Wants are specified with set_wants rather than passed in since
  758. in the current interface they are determined outside this class.
  759. """
  760. return _all_wants_satisfied(self.store, haves, self._wants)
  761. def set_ack_type(self, ack_type) -> None:
  762. """Set the acknowledgment type for the graph walker.
  763. Args:
  764. ack_type: One of SINGLE_ACK, MULTI_ACK, or MULTI_ACK_DETAILED
  765. """
  766. impl_classes: dict[int, type[AckGraphWalkerImpl]] = {
  767. MULTI_ACK: MultiAckGraphWalkerImpl,
  768. MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl,
  769. SINGLE_ACK: SingleAckGraphWalkerImpl,
  770. }
  771. self._impl = impl_classes[ack_type](self)
  772. _GRAPH_WALKER_COMMANDS = (COMMAND_HAVE, COMMAND_DONE, None)
  773. class SingleAckGraphWalkerImpl(AckGraphWalkerImpl):
  774. """Graph walker implementation that speaks the single-ack protocol."""
  775. def __init__(self, walker) -> None:
  776. """Initialize a SingleAckGraphWalkerImpl.
  777. Args:
  778. walker: Parent ProtocolGraphWalker instance
  779. """
  780. self.walker = walker
  781. self._common: list[bytes] = []
  782. def ack(self, have_ref) -> None:
  783. """Acknowledge a have reference.
  784. Args:
  785. have_ref: Object ID to acknowledge
  786. """
  787. if not self._common:
  788. self.walker.send_ack(have_ref)
  789. self._common.append(have_ref)
  790. def next(self):
  791. """Get next SHA from graph walker.
  792. Returns:
  793. SHA bytes or None if done
  794. """
  795. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  796. if command in (None, COMMAND_DONE):
  797. # defer the handling of done
  798. self.walker.notify_done()
  799. return None
  800. elif command == COMMAND_HAVE:
  801. return sha
  802. __next__ = next
  803. def handle_done(self, done_required, done_received) -> bool:
  804. """Handle done command.
  805. Args:
  806. done_required: Whether done is required
  807. done_received: Whether done was received
  808. Returns:
  809. True if handling completed successfully
  810. """
  811. if not self._common:
  812. self.walker.send_nak()
  813. if done_required and not done_received:
  814. # we are not done, especially when done is required; skip
  815. # the pack for this request and especially do not handle
  816. # the done.
  817. return False
  818. if not done_received and not self._common:
  819. # Okay we are not actually done then since the walker picked
  820. # up no haves. This is usually triggered when client attempts
  821. # to pull from a source that has no common base_commit.
  822. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  823. # test_multi_ack_stateless_nodone
  824. return False
  825. return True
  826. class MultiAckGraphWalkerImpl(AckGraphWalkerImpl):
  827. """Graph walker implementation that speaks the multi-ack protocol."""
  828. def __init__(self, walker) -> None:
  829. """Initialize multi-ack graph walker.
  830. Args:
  831. walker: Parent ProtocolGraphWalker instance
  832. """
  833. self.walker = walker
  834. self._found_base = False
  835. self._common: list[bytes] = []
  836. def ack(self, have_ref) -> None:
  837. """Acknowledge a have reference.
  838. Args:
  839. have_ref: Object ID to acknowledge
  840. """
  841. self._common.append(have_ref)
  842. if not self._found_base:
  843. self.walker.send_ack(have_ref, b"continue")
  844. if self.walker.all_wants_satisfied(self._common):
  845. self._found_base = True
  846. # else we blind ack within next
  847. def next(self):
  848. """Get next SHA from graph walker.
  849. Returns:
  850. SHA bytes or None if done
  851. """
  852. while True:
  853. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  854. if command is None:
  855. self.walker.send_nak()
  856. # in multi-ack mode, a flush-pkt indicates the client wants to
  857. # flush but more have lines are still coming
  858. continue
  859. elif command == COMMAND_DONE:
  860. self.walker.notify_done()
  861. return None
  862. elif command == COMMAND_HAVE:
  863. if self._found_base:
  864. # blind ack
  865. self.walker.send_ack(sha, b"continue")
  866. return sha
  867. __next__ = next
  868. def handle_done(self, done_required, done_received) -> bool:
  869. """Handle done command.
  870. Args:
  871. done_required: Whether done is required
  872. done_received: Whether done was received
  873. Returns:
  874. True if handling completed successfully
  875. """
  876. if done_required and not done_received:
  877. # we are not done, especially when done is required; skip
  878. # the pack for this request and especially do not handle
  879. # the done.
  880. return False
  881. if not done_received and not self._common:
  882. # Okay we are not actually done then since the walker picked
  883. # up no haves. This is usually triggered when client attempts
  884. # to pull from a source that has no common base_commit.
  885. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  886. # test_multi_ack_stateless_nodone
  887. return False
  888. # don't nak unless no common commits were found, even if not
  889. # everything is satisfied
  890. if self._common:
  891. self.walker.send_ack(self._common[-1])
  892. else:
  893. self.walker.send_nak()
  894. return True
  895. class MultiAckDetailedGraphWalkerImpl(AckGraphWalkerImpl):
  896. """Graph walker implementation speaking the multi-ack-detailed protocol."""
  897. def __init__(self, walker) -> None:
  898. """Initialize multi-ack-detailed graph walker.
  899. Args:
  900. walker: Parent ProtocolGraphWalker instance
  901. """
  902. self.walker = walker
  903. self._common: list[bytes] = []
  904. def ack(self, have_ref) -> None:
  905. """Acknowledge a have reference.
  906. Args:
  907. have_ref: Object ID to acknowledge
  908. """
  909. # Should only be called iff have_ref is common
  910. self._common.append(have_ref)
  911. self.walker.send_ack(have_ref, b"common")
  912. def next(self):
  913. """Get next SHA from graph walker.
  914. Returns:
  915. SHA bytes or None if done
  916. """
  917. while True:
  918. command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS)
  919. if command is None:
  920. if self.walker.all_wants_satisfied(self._common):
  921. self.walker.send_ack(self._common[-1], b"ready")
  922. self.walker.send_nak()
  923. if self.walker.stateless_rpc:
  924. # The HTTP version of this request a flush-pkt always
  925. # signifies an end of request, so we also return
  926. # nothing here as if we are done (but not really, as
  927. # it depends on whether no-done capability was
  928. # specified and that's handled in handle_done which
  929. # may or may not call post_nodone_check depending on
  930. # that).
  931. return None
  932. elif command == COMMAND_DONE:
  933. # Let the walker know that we got a done.
  934. self.walker.notify_done()
  935. break
  936. elif command == COMMAND_HAVE:
  937. # return the sha and let the caller ACK it with the
  938. # above ack method.
  939. return sha
  940. # don't nak unless no common commits were found, even if not
  941. # everything is satisfied
  942. __next__ = next
  943. def handle_done(self, done_required, done_received) -> bool:
  944. """Handle done command.
  945. Args:
  946. done_required: Whether done is required
  947. done_received: Whether done was received
  948. Returns:
  949. True if handling completed successfully
  950. """
  951. if done_required and not done_received:
  952. # we are not done, especially when done is required; skip
  953. # the pack for this request and especially do not handle
  954. # the done.
  955. return False
  956. if not done_received and not self._common:
  957. # Okay we are not actually done then since the walker picked
  958. # up no haves. This is usually triggered when client attempts
  959. # to pull from a source that has no common base_commit.
  960. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\
  961. # test_multi_ack_stateless_nodone
  962. return False
  963. # don't nak unless no common commits were found, even if not
  964. # everything is satisfied
  965. if self._common:
  966. self.walker.send_ack(self._common[-1])
  967. else:
  968. self.walker.send_nak()
  969. return True
  970. class ReceivePackHandler(PackHandler):
  971. """Protocol handler for downloading a pack from the client."""
  972. def __init__(
  973. self, backend, args, proto, stateless_rpc=False, advertise_refs=False
  974. ) -> None:
  975. """Initialize receive-pack handler.
  976. Args:
  977. backend: Backend instance
  978. args: Command arguments
  979. proto: Protocol instance
  980. stateless_rpc: Whether to use stateless RPC
  981. advertise_refs: Whether to advertise refs
  982. """
  983. super().__init__(backend, proto, stateless_rpc=stateless_rpc)
  984. self.repo = backend.open_repository(args[0])
  985. self.advertise_refs = advertise_refs
  986. @classmethod
  987. def capabilities(cls) -> Iterable[bytes]:
  988. """Return supported capabilities.
  989. Returns:
  990. List of capability names
  991. """
  992. return [
  993. CAPABILITY_REPORT_STATUS,
  994. CAPABILITY_DELETE_REFS,
  995. CAPABILITY_QUIET,
  996. CAPABILITY_OFS_DELTA,
  997. CAPABILITY_SIDE_BAND_64K,
  998. CAPABILITY_NO_DONE,
  999. ]
  1000. def _apply_pack(
  1001. self, refs: list[tuple[ObjectID, ObjectID, Ref]]
  1002. ) -> Iterator[tuple[bytes, bytes]]:
  1003. """Apply received pack to repository.
  1004. Args:
  1005. refs: List of (old_sha, new_sha, ref_name) tuples
  1006. Yields:
  1007. Tuples of (ref_name, error_message) for any errors
  1008. """
  1009. all_exceptions = (
  1010. IOError,
  1011. OSError,
  1012. ChecksumMismatch,
  1013. ApplyDeltaError,
  1014. AssertionError,
  1015. socket.error,
  1016. zlib.error,
  1017. ObjectFormatException,
  1018. )
  1019. will_send_pack = False
  1020. for command in refs:
  1021. if command[1] != ZERO_SHA:
  1022. will_send_pack = True
  1023. if will_send_pack:
  1024. # TODO: more informative error messages than just the exception
  1025. # string
  1026. try:
  1027. recv = getattr(self.proto, "recv", None)
  1028. self.repo.object_store.add_thin_pack(self.proto.read, recv)
  1029. yield (b"unpack", b"ok")
  1030. except all_exceptions as e:
  1031. yield (b"unpack", str(e).replace("\n", "").encode("utf-8"))
  1032. # The pack may still have been moved in, but it may contain
  1033. # broken objects. We trust a later GC to clean it up.
  1034. else:
  1035. # The git protocol want to find a status entry related to unpack
  1036. # process even if no pack data has been sent.
  1037. yield (b"unpack", b"ok")
  1038. for oldsha, sha, ref in refs:
  1039. ref_status = b"ok"
  1040. try:
  1041. if sha == ZERO_SHA:
  1042. if CAPABILITY_DELETE_REFS not in self.capabilities():
  1043. raise GitProtocolError(
  1044. "Attempted to delete refs without delete-refs capability."
  1045. )
  1046. try:
  1047. self.repo.refs.remove_if_equals(ref, oldsha)
  1048. except all_exceptions:
  1049. ref_status = b"failed to delete"
  1050. else:
  1051. try:
  1052. self.repo.refs.set_if_equals(ref, oldsha, sha)
  1053. except all_exceptions:
  1054. ref_status = b"failed to write"
  1055. except KeyError:
  1056. ref_status = b"bad ref"
  1057. yield (ref, ref_status)
  1058. def _report_status(self, status: list[tuple[bytes, bytes]]) -> None:
  1059. """Report status to client.
  1060. Args:
  1061. status: List of (ref_name, status_message) tuples
  1062. """
  1063. if self.has_capability(CAPABILITY_SIDE_BAND_64K):
  1064. writer = BufferedPktLineWriter(
  1065. lambda d: self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, d)
  1066. )
  1067. write = writer.write
  1068. def flush() -> None:
  1069. writer.flush()
  1070. self.proto.write_pkt_line(None)
  1071. else:
  1072. write = self.proto.write_pkt_line
  1073. def flush() -> None:
  1074. pass
  1075. for name, msg in status:
  1076. if name == b"unpack":
  1077. write(b"unpack " + msg + b"\n")
  1078. elif msg == b"ok":
  1079. write(b"ok " + name + b"\n")
  1080. else:
  1081. write(b"ng " + name + b" " + msg + b"\n")
  1082. write(None) # type: ignore
  1083. flush()
  1084. def _on_post_receive(self, client_refs) -> None:
  1085. """Run post-receive hook.
  1086. Args:
  1087. client_refs: Dictionary of ref changes from client
  1088. """
  1089. hook = self.repo.hooks.get("post-receive", None)
  1090. if not hook:
  1091. return
  1092. try:
  1093. output = hook.execute(client_refs)
  1094. if output:
  1095. self.proto.write_sideband(SIDE_BAND_CHANNEL_PROGRESS, output)
  1096. except HookError as err:
  1097. self.proto.write_sideband(SIDE_BAND_CHANNEL_FATAL, str(err).encode("utf-8"))
  1098. def handle(self) -> None:
  1099. """Handle receive-pack request."""
  1100. if self.advertise_refs or not self.stateless_rpc:
  1101. refs = sorted(self.repo.get_refs().items())
  1102. symrefs = sorted(self.repo.refs.get_symrefs().items())
  1103. if not refs:
  1104. refs = [(CAPABILITIES_REF, ZERO_SHA)]
  1105. logger.info("Sending capabilities: %s", self.capabilities())
  1106. self.proto.write_pkt_line(
  1107. format_ref_line(
  1108. refs[0][0],
  1109. refs[0][1],
  1110. list(self.capabilities()) + symref_capabilities(symrefs),
  1111. )
  1112. )
  1113. for i in range(1, len(refs)):
  1114. ref = refs[i]
  1115. self.proto.write_pkt_line(format_ref_line(ref[0], ref[1]))
  1116. self.proto.write_pkt_line(None)
  1117. if self.advertise_refs:
  1118. return
  1119. client_refs = []
  1120. ref = self.proto.read_pkt_line()
  1121. # if ref is none then client doesn't want to send us anything..
  1122. if ref is None:
  1123. return
  1124. ref, caps = extract_capabilities(ref)
  1125. self.set_client_capabilities(caps)
  1126. # client will now send us a list of (oldsha, newsha, ref)
  1127. while ref:
  1128. (oldsha, newsha, ref) = ref.split()
  1129. client_refs.append((oldsha, newsha, ref))
  1130. ref = self.proto.read_pkt_line()
  1131. # backend can now deal with this refs and read a pack using self.read
  1132. status = list(self._apply_pack(client_refs))
  1133. self._on_post_receive(client_refs)
  1134. # when we have read all the pack from the client, send a status report
  1135. # if the client asked for it
  1136. if self.has_capability(CAPABILITY_REPORT_STATUS):
  1137. self._report_status(status)
  1138. class UploadArchiveHandler(Handler):
  1139. """Handler for git-upload-archive requests."""
  1140. def __init__(self, backend, args, proto, stateless_rpc=False) -> None:
  1141. """Initialize upload-archive handler.
  1142. Args:
  1143. backend: Backend instance
  1144. args: Command arguments
  1145. proto: Protocol instance
  1146. stateless_rpc: Whether to use stateless RPC
  1147. """
  1148. super().__init__(backend, proto, stateless_rpc)
  1149. self.repo = backend.open_repository(args[0])
  1150. def handle(self) -> None:
  1151. """Handle upload-archive request."""
  1152. def write(x):
  1153. return self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, x)
  1154. arguments = []
  1155. for pkt in self.proto.read_pkt_seq():
  1156. (key, value) = pkt.split(b" ", 1)
  1157. if key != b"argument":
  1158. raise GitProtocolError(f"unknown command {key}")
  1159. arguments.append(value.rstrip(b"\n"))
  1160. prefix = b""
  1161. format = "tar"
  1162. i = 0
  1163. store: BaseObjectStore = self.repo.object_store
  1164. while i < len(arguments):
  1165. argument = arguments[i]
  1166. if argument == b"--prefix":
  1167. i += 1
  1168. prefix = arguments[i]
  1169. elif argument == b"--format":
  1170. i += 1
  1171. format = arguments[i].decode("ascii")
  1172. else:
  1173. commit_sha = self.repo.refs[argument]
  1174. tree = cast(Tree, store[cast(Commit, store[commit_sha]).tree])
  1175. i += 1
  1176. self.proto.write_pkt_line(b"ACK")
  1177. self.proto.write_pkt_line(None)
  1178. for chunk in tar_stream(
  1179. store,
  1180. tree,
  1181. mtime=int(time.time()),
  1182. prefix=prefix,
  1183. format=format, # type: ignore
  1184. ):
  1185. write(chunk)
  1186. self.proto.write_pkt_line(None)
  1187. # Default handler classes for git services.
  1188. DEFAULT_HANDLERS = {
  1189. b"git-upload-pack": UploadPackHandler,
  1190. b"git-receive-pack": ReceivePackHandler,
  1191. b"git-upload-archive": UploadArchiveHandler,
  1192. }
  1193. class TCPGitRequestHandler(socketserver.StreamRequestHandler):
  1194. """TCP request handler for git protocol."""
  1195. def __init__(self, handlers, *args, **kwargs) -> None:
  1196. """Initialize TCP request handler.
  1197. Args:
  1198. handlers: Dictionary mapping commands to handler classes
  1199. *args: Additional arguments for StreamRequestHandler
  1200. **kwargs: Additional keyword arguments for StreamRequestHandler
  1201. """
  1202. self.handlers = handlers
  1203. socketserver.StreamRequestHandler.__init__(self, *args, **kwargs)
  1204. def handle(self) -> None:
  1205. """Handle TCP git request."""
  1206. proto = ReceivableProtocol(self.connection.recv, self.wfile.write)
  1207. command, args = proto.read_cmd()
  1208. logger.info("Handling %s request, args=%s", command, args)
  1209. cls = self.handlers.get(command, None)
  1210. if not callable(cls):
  1211. raise GitProtocolError(f"Invalid service {command!r}")
  1212. h = cls(self.server.backend, args, proto) # type: ignore
  1213. h.handle()
  1214. class TCPGitServer(socketserver.TCPServer):
  1215. """TCP server for git protocol."""
  1216. allow_reuse_address = True
  1217. serve = socketserver.TCPServer.serve_forever
  1218. def _make_handler(self, *args, **kwargs):
  1219. """Create request handler instance.
  1220. Args:
  1221. *args: Handler arguments
  1222. **kwargs: Handler keyword arguments
  1223. Returns:
  1224. TCPGitRequestHandler instance
  1225. """
  1226. return TCPGitRequestHandler(self.handlers, *args, **kwargs)
  1227. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT, handlers=None) -> None:
  1228. """Initialize TCP git server.
  1229. Args:
  1230. backend: Backend instance
  1231. listen_addr: Address to listen on
  1232. port: Port to listen on (default: TCP_GIT_PORT)
  1233. handlers: Optional dictionary of custom handlers
  1234. """
  1235. self.handlers = dict(DEFAULT_HANDLERS)
  1236. if handlers is not None:
  1237. self.handlers.update(handlers)
  1238. self.backend = backend
  1239. logger.info("Listening for TCP connections on %s:%d", listen_addr, port)
  1240. socketserver.TCPServer.__init__(self, (listen_addr, port), self._make_handler)
  1241. def verify_request(self, request, client_address) -> bool:
  1242. """Verify incoming request.
  1243. Args:
  1244. request: Request socket
  1245. client_address: Client address tuple
  1246. Returns:
  1247. True to accept request
  1248. """
  1249. logger.info("Handling request from %s", client_address)
  1250. return True
  1251. def handle_error(self, request, client_address) -> None:
  1252. """Handle request processing errors.
  1253. Args:
  1254. request: Request socket
  1255. client_address: Client address tuple
  1256. """
  1257. logger.exception(
  1258. "Exception happened during processing of request from %s",
  1259. client_address,
  1260. )
  1261. def main(argv=sys.argv) -> None:
  1262. """Entry point for starting a TCP git server."""
  1263. import optparse
  1264. parser = optparse.OptionParser()
  1265. parser.add_option(
  1266. "-l",
  1267. "--listen_address",
  1268. dest="listen_address",
  1269. default="localhost",
  1270. help="Binding IP address.",
  1271. )
  1272. parser.add_option(
  1273. "-p",
  1274. "--port",
  1275. dest="port",
  1276. type=int,
  1277. default=TCP_GIT_PORT,
  1278. help="Binding TCP port.",
  1279. )
  1280. options, args = parser.parse_args(argv)
  1281. log_utils.default_logging_config()
  1282. if len(args) > 1:
  1283. gitdir = args[1]
  1284. else:
  1285. gitdir = "."
  1286. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  1287. backend = FileSystemBackend(gitdir)
  1288. server = TCPGitServer(backend, options.listen_address, options.port)
  1289. server.serve_forever()
  1290. def serve_command(
  1291. handler_cls, argv=sys.argv, backend=None, inf=sys.stdin, outf=sys.stdout
  1292. ) -> int:
  1293. """Serve a single command.
  1294. This is mostly useful for the implementation of commands used by e.g.
  1295. git+ssh.
  1296. Args:
  1297. handler_cls: `Handler` class to use for the request
  1298. argv: execv-style command-line arguments. Defaults to sys.argv.
  1299. backend: `Backend` to use
  1300. inf: File-like object to read from, defaults to standard input.
  1301. outf: File-like object to write to, defaults to standard output.
  1302. Returns: Exit code for use with sys.exit. 0 on success, 1 on failure.
  1303. """
  1304. if backend is None:
  1305. backend = FileSystemBackend()
  1306. def send_fn(data) -> None:
  1307. outf.write(data)
  1308. outf.flush()
  1309. proto = Protocol(inf.read, send_fn)
  1310. handler = handler_cls(backend, argv[1:], proto)
  1311. # FIXME: Catch exceptions and write a single-line summary to outf.
  1312. handler.handle()
  1313. return 0
  1314. def generate_info_refs(repo):
  1315. """Generate an info refs file."""
  1316. refs = repo.get_refs()
  1317. return write_info_refs(refs, repo.object_store)
  1318. def generate_objects_info_packs(repo):
  1319. """Generate an index for for packs."""
  1320. for pack in repo.object_store.packs:
  1321. yield (b"P " + os.fsencode(pack.data.filename) + b"\n")
  1322. def update_server_info(repo) -> None:
  1323. """Generate server info for dumb file access.
  1324. This generates info/refs and objects/info/packs,
  1325. similar to "git update-server-info".
  1326. """
  1327. repo._put_named_file(
  1328. os.path.join("info", "refs"), b"".join(generate_info_refs(repo))
  1329. )
  1330. repo._put_named_file(
  1331. os.path.join("objects", "info", "packs"),
  1332. b"".join(generate_objects_info_packs(repo)),
  1333. )
  1334. if __name__ == "__main__":
  1335. main()