server.py 36 KB

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