server.py 38 KB

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