server.py 43 KB

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