server.py 39 KB

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