server.py 32 KB

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