server.py 41 KB

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