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