server.py 39 KB

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