server.py 43 KB

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