server.py 42 KB

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