server.py 39 KB

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