server.py 34 KB

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