server.py 40 KB

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