server.py 48 KB

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