server.py 43 KB

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