server.py 39 KB

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