server.py 32 KB

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