server.py 42 KB

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