server.py 38 KB

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