server.py 41 KB

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