server.py 44 KB

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