server.py 36 KB

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