server.py 43 KB

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