server.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. # server.py -- Implementation of the server side git protocols
  2. # Copryight (C) 2008 John Carr <john.carr@unrouted.co.uk>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # or (at your option) any later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Git smart network protocol server implementation.
  19. For more detailed implementation on the network protocol, see the
  20. Documentation/technical directory in the cgit distribution, and in particular:
  21. Documentation/technical/protocol-capabilities.txt
  22. Documentation/technical/pack-protocol.txt
  23. """
  24. import collections
  25. from cStringIO import StringIO
  26. import os
  27. import SocketServer
  28. from dulwich.errors import (
  29. ApplyDeltaError,
  30. ChecksumMismatch,
  31. GitProtocolError,
  32. )
  33. from dulwich.misc import (
  34. make_sha,
  35. )
  36. from dulwich.objects import (
  37. hex_to_sha,
  38. sha_to_hex,
  39. )
  40. from dulwich.pack import (
  41. read_pack_header,
  42. unpack_object,
  43. write_pack_data,
  44. )
  45. from dulwich.protocol import (
  46. MULTI_ACK,
  47. MULTI_ACK_DETAILED,
  48. ProtocolFile,
  49. ReceivableProtocol,
  50. SINGLE_ACK,
  51. TCP_GIT_PORT,
  52. ZERO_SHA,
  53. extract_capabilities,
  54. extract_want_line_capabilities,
  55. ack_type,
  56. )
  57. class Backend(object):
  58. """A backend for the Git smart server implementation."""
  59. def open_repository(self, path):
  60. """Open the repository at a path."""
  61. raise NotImplementedError(self.open_repository)
  62. class BackendRepo(object):
  63. """Repository abstraction used by the Git server.
  64. Please note that the methods required here are a
  65. subset of those provided by dulwich.repo.Repo.
  66. """
  67. object_store = None
  68. refs = None
  69. def get_refs(self):
  70. """
  71. Get all the refs in the repository
  72. :return: dict of name -> sha
  73. """
  74. raise NotImplementedError
  75. def get_peeled(self, name):
  76. """Return the cached peeled value of a ref, if available.
  77. :param name: Name of the ref to peel
  78. :return: The peeled value of the ref. If the ref is known not point to
  79. a tag, this will be the SHA the ref refers to. If no cached
  80. information about a tag is available, this method may return None,
  81. but it should attempt to peel the tag if possible.
  82. """
  83. return None
  84. def fetch_objects(self, determine_wants, graph_walker, progress,
  85. get_tagged=None):
  86. """
  87. Yield the objects required for a list of commits.
  88. :param progress: is a callback to send progress messages to the client
  89. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  90. sha for including tags.
  91. """
  92. raise NotImplementedError
  93. class PackStreamReader(object):
  94. """Class to read a pack stream.
  95. The pack is read from a ReceivableProtocol using read() or recv() as
  96. appropriate.
  97. """
  98. def __init__(self, read_all, read_some=None):
  99. self.read_all = read_all
  100. if read_some is None:
  101. self.read_some = read_all
  102. else:
  103. self.read_some = read_some
  104. self.sha = make_sha()
  105. self._rbuf = StringIO()
  106. # trailer is a deque to avoid memory allocation on small reads
  107. self._trailer = collections.deque()
  108. def _read(self, read, size):
  109. """Read up to size bytes using the given callback.
  110. As a side effect, update the verifier's hash (excluding the last 20
  111. bytes read) and write through to the output file.
  112. :param read: The read callback to read from.
  113. :param size: The maximum number of bytes to read; the particular
  114. behavior is callback-specific.
  115. """
  116. data = read(size)
  117. # maintain a trailer of the last 20 bytes we've read
  118. n = len(data)
  119. tn = len(self._trailer)
  120. if n >= 20:
  121. to_pop = tn
  122. to_add = 20
  123. else:
  124. to_pop = max(n + tn - 20, 0)
  125. to_add = n
  126. for _ in xrange(to_pop):
  127. self.sha.update(self._trailer.popleft())
  128. self._trailer.extend(data[-to_add:])
  129. # hash everything but the trailer
  130. self.sha.update(data[:-to_add])
  131. return data
  132. def _buf_len(self):
  133. buf = self._rbuf
  134. start = buf.tell()
  135. buf.seek(0, os.SEEK_END)
  136. end = buf.tell()
  137. buf.seek(start)
  138. return end - start
  139. def read(self, size):
  140. """Read, blocking until size bytes are read."""
  141. buf_len = self._buf_len()
  142. if buf_len >= size:
  143. return self._rbuf.read(size)
  144. buf_data = self._rbuf.read()
  145. self._rbuf = StringIO()
  146. return buf_data + self._read(self.read_all, size - buf_len)
  147. def recv(self, size):
  148. """Read up to size bytes, blocking until one byte is read."""
  149. buf_len = self._buf_len()
  150. if buf_len:
  151. data = self._rbuf.read(size)
  152. if size >= buf_len:
  153. self._rbuf = StringIO()
  154. return data
  155. return self._read(self.read_some, size)
  156. def read_objects(self):
  157. """Read the objects in this pack file.
  158. :raise AssertionError: if there is an error in the pack format.
  159. :raise ChecksumMismatch: if the checksum of the pack contents does not
  160. match the checksum in the pack trailer.
  161. :raise zlib.error: if an error occurred during zlib decompression.
  162. :raise IOError: if an error occurred writing to the output file.
  163. """
  164. pack_version, num_objects = read_pack_header(self.read)
  165. for i in xrange(num_objects):
  166. type, uncomp, comp_len, unused = unpack_object(self.read, self.recv)
  167. yield type, uncomp, comp_len
  168. # prepend any unused data to current read buffer
  169. buf = StringIO()
  170. buf.write(unused)
  171. buf.write(self._rbuf.read())
  172. buf.seek(0)
  173. self._rbuf = buf
  174. pack_sha = sha_to_hex(''.join([c for c in self._trailer]))
  175. calculated_sha = self.sha.hexdigest()
  176. if pack_sha != calculated_sha:
  177. raise ChecksumMismatch(pack_sha, calculated_sha)
  178. class PackStreamCopier(PackStreamReader):
  179. """Class to verify a pack stream as it is being read.
  180. The pack is read from a ReceivableProtocol using read() or recv() as
  181. appropriate and written out to the given file-like object.
  182. """
  183. def __init__(self, read_all, read_some, outfile):
  184. super(PackStreamCopier, self).__init__(read_all, read_some)
  185. self.outfile = outfile
  186. def _read(self, read, size):
  187. data = super(PackStreamCopier, self)._read(read, size)
  188. self.outfile.write(data)
  189. return data
  190. def verify(self):
  191. """Verify a pack stream and write it to the output file.
  192. See PackStreamReader.iterobjects for a list of exceptions this may throw.
  193. """
  194. for _, _, _, _ in self.iterobjects():
  195. pass
  196. class DictBackend(Backend):
  197. """Trivial backend that looks up Git repositories in a dictionary."""
  198. def __init__(self, repos):
  199. self.repos = repos
  200. def open_repository(self, path):
  201. # FIXME: What to do in case there is no repo ?
  202. return self.repos[path]
  203. class Handler(object):
  204. """Smart protocol command handler base class."""
  205. def __init__(self, backend, proto):
  206. self.backend = backend
  207. self.proto = proto
  208. self._client_capabilities = None
  209. def capability_line(self):
  210. return " ".join(self.capabilities())
  211. def capabilities(self):
  212. raise NotImplementedError(self.capabilities)
  213. def innocuous_capabilities(self):
  214. return ("include-tag", "thin-pack", "no-progress", "ofs-delta")
  215. def required_capabilities(self):
  216. """Return a list of capabilities that we require the client to have."""
  217. return []
  218. def set_client_capabilities(self, caps):
  219. allowable_caps = set(self.innocuous_capabilities())
  220. allowable_caps.update(self.capabilities())
  221. for cap in caps:
  222. if cap not in allowable_caps:
  223. raise GitProtocolError('Client asked for capability %s that '
  224. 'was not advertised.' % cap)
  225. for cap in self.required_capabilities():
  226. if cap not in caps:
  227. raise GitProtocolError('Client does not support required '
  228. 'capability %s.' % cap)
  229. self._client_capabilities = set(caps)
  230. def has_capability(self, cap):
  231. if self._client_capabilities is None:
  232. raise GitProtocolError('Server attempted to access capability %s '
  233. 'before asking client' % cap)
  234. return cap in self._client_capabilities
  235. class UploadPackHandler(Handler):
  236. """Protocol handler for uploading a pack to the server."""
  237. def __init__(self, backend, args, proto,
  238. stateless_rpc=False, advertise_refs=False):
  239. Handler.__init__(self, backend, proto)
  240. self.repo = backend.open_repository(args[0])
  241. self._graph_walker = None
  242. self.stateless_rpc = stateless_rpc
  243. self.advertise_refs = advertise_refs
  244. def capabilities(self):
  245. return ("multi_ack_detailed", "multi_ack", "side-band-64k", "thin-pack",
  246. "ofs-delta", "no-progress", "include-tag")
  247. def required_capabilities(self):
  248. return ("side-band-64k", "thin-pack", "ofs-delta")
  249. def progress(self, message):
  250. if self.has_capability("no-progress"):
  251. return
  252. self.proto.write_sideband(2, message)
  253. def get_tagged(self, refs=None, repo=None):
  254. """Get a dict of peeled values of tags to their original tag shas.
  255. :param refs: dict of refname -> sha of possible tags; defaults to all of
  256. the backend's refs.
  257. :param repo: optional Repo instance for getting peeled refs; defaults to
  258. the backend's repo, if available
  259. :return: dict of peeled_sha -> tag_sha, where tag_sha is the sha of a
  260. tag whose peeled value is peeled_sha.
  261. """
  262. if not self.has_capability("include-tag"):
  263. return {}
  264. if refs is None:
  265. refs = self.repo.get_refs()
  266. if repo is None:
  267. repo = getattr(self.repo, "repo", None)
  268. if repo is None:
  269. # Bail if we don't have a Repo available; this is ok since
  270. # clients must be able to handle if the server doesn't include
  271. # all relevant tags.
  272. # TODO: fix behavior when missing
  273. return {}
  274. tagged = {}
  275. for name, sha in refs.iteritems():
  276. peeled_sha = repo.get_peeled(name)
  277. if peeled_sha != sha:
  278. tagged[peeled_sha] = sha
  279. return tagged
  280. def handle(self):
  281. write = lambda x: self.proto.write_sideband(1, x)
  282. graph_walker = ProtocolGraphWalker(self, self.repo.object_store,
  283. self.repo.get_peeled)
  284. objects_iter = self.repo.fetch_objects(
  285. graph_walker.determine_wants, graph_walker, self.progress,
  286. get_tagged=self.get_tagged)
  287. # Do they want any objects?
  288. if len(objects_iter) == 0:
  289. return
  290. self.progress("dul-daemon says what\n")
  291. self.progress("counting objects: %d, done.\n" % len(objects_iter))
  292. write_pack_data(ProtocolFile(None, write), objects_iter,
  293. len(objects_iter))
  294. self.progress("how was that, then?\n")
  295. # we are done
  296. self.proto.write("0000")
  297. class ProtocolGraphWalker(object):
  298. """A graph walker that knows the git protocol.
  299. As a graph walker, this class implements ack(), next(), and reset(). It
  300. also contains some base methods for interacting with the wire and walking
  301. the commit tree.
  302. The work of determining which acks to send is passed on to the
  303. implementation instance stored in _impl. The reason for this is that we do
  304. not know at object creation time what ack level the protocol requires. A
  305. call to set_ack_level() is required to set up the implementation, before any
  306. calls to next() or ack() are made.
  307. """
  308. def __init__(self, handler, object_store, get_peeled):
  309. self.handler = handler
  310. self.store = object_store
  311. self.get_peeled = get_peeled
  312. self.proto = handler.proto
  313. self.stateless_rpc = handler.stateless_rpc
  314. self.advertise_refs = handler.advertise_refs
  315. self._wants = []
  316. self._cached = False
  317. self._cache = []
  318. self._cache_index = 0
  319. self._impl = None
  320. def determine_wants(self, heads):
  321. """Determine the wants for a set of heads.
  322. The given heads are advertised to the client, who then specifies which
  323. refs he wants using 'want' lines. This portion of the protocol is the
  324. same regardless of ack type, and in fact is used to set the ack type of
  325. the ProtocolGraphWalker.
  326. :param heads: a dict of refname->SHA1 to advertise
  327. :return: a list of SHA1s requested by the client
  328. """
  329. if not heads:
  330. raise GitProtocolError('No heads found')
  331. values = set(heads.itervalues())
  332. if self.advertise_refs or not self.stateless_rpc:
  333. for i, (ref, sha) in enumerate(heads.iteritems()):
  334. line = "%s %s" % (sha, ref)
  335. if not i:
  336. line = "%s\x00%s" % (line, self.handler.capability_line())
  337. self.proto.write_pkt_line("%s\n" % line)
  338. peeled_sha = self.get_peeled(ref)
  339. if peeled_sha != sha:
  340. self.proto.write_pkt_line('%s %s^{}\n' %
  341. (peeled_sha, ref))
  342. # i'm done..
  343. self.proto.write_pkt_line(None)
  344. if self.advertise_refs:
  345. return []
  346. # Now client will sending want want want commands
  347. want = self.proto.read_pkt_line()
  348. if not want:
  349. return []
  350. line, caps = extract_want_line_capabilities(want)
  351. self.handler.set_client_capabilities(caps)
  352. self.set_ack_type(ack_type(caps))
  353. command, sha = self._split_proto_line(line)
  354. want_revs = []
  355. while command != None:
  356. if command != 'want':
  357. raise GitProtocolError(
  358. 'Protocol got unexpected command %s' % command)
  359. if sha not in values:
  360. raise GitProtocolError(
  361. 'Client wants invalid object %s' % sha)
  362. want_revs.append(sha)
  363. command, sha = self.read_proto_line()
  364. self.set_wants(want_revs)
  365. return want_revs
  366. def ack(self, have_ref):
  367. return self._impl.ack(have_ref)
  368. def reset(self):
  369. self._cached = True
  370. self._cache_index = 0
  371. def next(self):
  372. if not self._cached:
  373. if not self._impl and self.stateless_rpc:
  374. return None
  375. return self._impl.next()
  376. self._cache_index += 1
  377. if self._cache_index > len(self._cache):
  378. return None
  379. return self._cache[self._cache_index]
  380. def _split_proto_line(self, line):
  381. fields = line.rstrip('\n').split(' ', 1)
  382. if len(fields) == 1 and fields[0] == 'done':
  383. return ('done', None)
  384. elif len(fields) == 2 and fields[0] in ('want', 'have'):
  385. try:
  386. hex_to_sha(fields[1])
  387. return tuple(fields)
  388. except (TypeError, AssertionError), e:
  389. raise GitProtocolError(e)
  390. raise GitProtocolError('Received invalid line from client:\n%s' % line)
  391. def read_proto_line(self):
  392. """Read a line from the wire.
  393. :return: a tuple having one of the following forms:
  394. ('want', obj_id)
  395. ('have', obj_id)
  396. ('done', None)
  397. (None, None) (for a flush-pkt)
  398. :raise GitProtocolError: if the line cannot be parsed into one of the
  399. possible return values.
  400. """
  401. line = self.proto.read_pkt_line()
  402. if not line:
  403. return (None, None)
  404. return self._split_proto_line(line)
  405. def send_ack(self, sha, ack_type=''):
  406. if ack_type:
  407. ack_type = ' %s' % ack_type
  408. self.proto.write_pkt_line('ACK %s%s\n' % (sha, ack_type))
  409. def send_nak(self):
  410. self.proto.write_pkt_line('NAK\n')
  411. def set_wants(self, wants):
  412. self._wants = wants
  413. def _is_satisfied(self, haves, want, earliest):
  414. """Check whether a want is satisfied by a set of haves.
  415. A want, typically a branch tip, is "satisfied" only if there exists a
  416. path back from that want to one of the haves.
  417. :param haves: A set of commits we know the client has.
  418. :param want: The want to check satisfaction for.
  419. :param earliest: A timestamp beyond which the search for haves will be
  420. terminated, presumably because we're searching too far down the
  421. wrong branch.
  422. """
  423. o = self.store[want]
  424. pending = collections.deque([o])
  425. while pending:
  426. commit = pending.popleft()
  427. if commit.id in haves:
  428. return True
  429. if commit.type_name != "commit":
  430. # non-commit wants are assumed to be satisfied
  431. continue
  432. for parent in commit.parents:
  433. parent_obj = self.store[parent]
  434. # TODO: handle parents with later commit times than children
  435. if parent_obj.commit_time >= earliest:
  436. pending.append(parent_obj)
  437. return False
  438. def all_wants_satisfied(self, haves):
  439. """Check whether all the current wants are satisfied by a set of haves.
  440. :param haves: A set of commits we know the client has.
  441. :note: Wants are specified with set_wants rather than passed in since
  442. in the current interface they are determined outside this class.
  443. """
  444. haves = set(haves)
  445. earliest = min([self.store[h].commit_time for h in haves])
  446. for want in self._wants:
  447. if not self._is_satisfied(haves, want, earliest):
  448. return False
  449. return True
  450. def set_ack_type(self, ack_type):
  451. impl_classes = {
  452. MULTI_ACK: MultiAckGraphWalkerImpl,
  453. MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl,
  454. SINGLE_ACK: SingleAckGraphWalkerImpl,
  455. }
  456. self._impl = impl_classes[ack_type](self)
  457. class SingleAckGraphWalkerImpl(object):
  458. """Graph walker implementation that speaks the single-ack protocol."""
  459. def __init__(self, walker):
  460. self.walker = walker
  461. self._sent_ack = False
  462. def ack(self, have_ref):
  463. if not self._sent_ack:
  464. self.walker.send_ack(have_ref)
  465. self._sent_ack = True
  466. def next(self):
  467. command, sha = self.walker.read_proto_line()
  468. if command in (None, 'done'):
  469. if not self._sent_ack:
  470. self.walker.send_nak()
  471. return None
  472. elif command == 'have':
  473. return sha
  474. class MultiAckGraphWalkerImpl(object):
  475. """Graph walker implementation that speaks the multi-ack protocol."""
  476. def __init__(self, walker):
  477. self.walker = walker
  478. self._found_base = False
  479. self._common = []
  480. def ack(self, have_ref):
  481. self._common.append(have_ref)
  482. if not self._found_base:
  483. self.walker.send_ack(have_ref, 'continue')
  484. if self.walker.all_wants_satisfied(self._common):
  485. self._found_base = True
  486. # else we blind ack within next
  487. def next(self):
  488. while True:
  489. command, sha = self.walker.read_proto_line()
  490. if command is None:
  491. self.walker.send_nak()
  492. # in multi-ack mode, a flush-pkt indicates the client wants to
  493. # flush but more have lines are still coming
  494. continue
  495. elif command == 'done':
  496. # don't nak unless no common commits were found, even if not
  497. # everything is satisfied
  498. if self._common:
  499. self.walker.send_ack(self._common[-1])
  500. else:
  501. self.walker.send_nak()
  502. return None
  503. elif command == 'have':
  504. if self._found_base:
  505. # blind ack
  506. self.walker.send_ack(sha, 'continue')
  507. return sha
  508. class MultiAckDetailedGraphWalkerImpl(object):
  509. """Graph walker implementation speaking the multi-ack-detailed protocol."""
  510. def __init__(self, walker):
  511. self.walker = walker
  512. self._found_base = False
  513. self._common = []
  514. def ack(self, have_ref):
  515. self._common.append(have_ref)
  516. if not self._found_base:
  517. self.walker.send_ack(have_ref, 'common')
  518. if self.walker.all_wants_satisfied(self._common):
  519. self._found_base = True
  520. self.walker.send_ack(have_ref, 'ready')
  521. # else we blind ack within next
  522. def next(self):
  523. while True:
  524. command, sha = self.walker.read_proto_line()
  525. if command is None:
  526. self.walker.send_nak()
  527. if self.walker.stateless_rpc:
  528. return None
  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; can happen if the client has more requests
  541. # inflight
  542. self.walker.send_ack(sha, 'ready')
  543. return sha
  544. class ReceivePackHandler(Handler):
  545. """Protocol handler for downloading a pack from the client."""
  546. def __init__(self, backend, args, proto,
  547. stateless_rpc=False, advertise_refs=False):
  548. Handler.__init__(self, backend, proto)
  549. self.repo = backend.open_repository(args[0])
  550. self.stateless_rpc = stateless_rpc
  551. self.advertise_refs = advertise_refs
  552. def capabilities(self):
  553. return ("report-status", "delete-refs")
  554. def _apply_pack(self, refs):
  555. f, commit = self.repo.object_store.add_thin_pack()
  556. all_exceptions = (IOError, OSError, ChecksumMismatch, ApplyDeltaError)
  557. status = []
  558. unpack_error = None
  559. # TODO: more informative error messages than just the exception string
  560. try:
  561. PackStreamCopier(self.proto.read, self.proto.recv, f).verify()
  562. except all_exceptions, e:
  563. unpack_error = str(e).replace('\n', '')
  564. try:
  565. commit()
  566. except all_exceptions, e:
  567. if not unpack_error:
  568. unpack_error = str(e).replace('\n', '')
  569. if unpack_error:
  570. status.append(('unpack', unpack_error))
  571. else:
  572. status.append(('unpack', 'ok'))
  573. for oldsha, sha, ref in refs:
  574. ref_error = None
  575. try:
  576. if sha == ZERO_SHA:
  577. if not self.has_capability('delete-refs'):
  578. raise GitProtocolError(
  579. 'Attempted to delete refs without delete-refs '
  580. 'capability.')
  581. try:
  582. del self.repo.refs[ref]
  583. except all_exceptions:
  584. ref_error = 'failed to delete'
  585. else:
  586. try:
  587. self.repo.refs[ref] = sha
  588. except all_exceptions:
  589. ref_error = 'failed to write'
  590. except KeyError, e:
  591. ref_error = 'bad ref'
  592. if ref_error:
  593. status.append((ref, ref_error))
  594. else:
  595. status.append((ref, 'ok'))
  596. return status
  597. def handle(self):
  598. refs = self.repo.get_refs().items()
  599. if self.advertise_refs or not self.stateless_rpc:
  600. if refs:
  601. self.proto.write_pkt_line(
  602. "%s %s\x00%s\n" % (refs[0][1], refs[0][0],
  603. self.capability_line()))
  604. for i in range(1, len(refs)):
  605. ref = refs[i]
  606. self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
  607. else:
  608. self.proto.write_pkt_line("%s capabilities^{} %s" % (
  609. ZERO_SHA, self.capability_line()))
  610. self.proto.write("0000")
  611. if self.advertise_refs:
  612. return
  613. client_refs = []
  614. ref = self.proto.read_pkt_line()
  615. # if ref is none then client doesnt want to send us anything..
  616. if ref is None:
  617. return
  618. ref, caps = extract_capabilities(ref)
  619. self.set_client_capabilities(caps)
  620. # client will now send us a list of (oldsha, newsha, ref)
  621. while ref:
  622. client_refs.append(ref.split())
  623. ref = self.proto.read_pkt_line()
  624. # backend can now deal with this refs and read a pack using self.read
  625. status = self._apply_pack(client_refs)
  626. # when we have read all the pack from the client, send a status report
  627. # if the client asked for it
  628. if self.has_capability('report-status'):
  629. for name, msg in status:
  630. if name == 'unpack':
  631. self.proto.write_pkt_line('unpack %s\n' % msg)
  632. elif msg == 'ok':
  633. self.proto.write_pkt_line('ok %s\n' % name)
  634. else:
  635. self.proto.write_pkt_line('ng %s %s\n' % (name, msg))
  636. self.proto.write_pkt_line(None)
  637. class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
  638. def handle(self):
  639. proto = ReceivableProtocol(self.connection.recv, self.wfile.write)
  640. command, args = proto.read_cmd()
  641. # switch case to handle the specific git command
  642. if command == 'git-upload-pack':
  643. cls = UploadPackHandler
  644. elif command == 'git-receive-pack':
  645. cls = ReceivePackHandler
  646. else:
  647. return
  648. h = cls(self.server.backend, args, proto)
  649. h.handle()
  650. class TCPGitServer(SocketServer.TCPServer):
  651. allow_reuse_address = True
  652. serve = SocketServer.TCPServer.serve_forever
  653. def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
  654. self.backend = backend
  655. SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)