2
0

test_client.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. # test_client.py -- Compatibility tests for git client.
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Compatibility tests between the Dulwich client and the cgit server."""
  21. import copy
  22. import http.server
  23. import os
  24. import select
  25. import signal
  26. import stat
  27. import subprocess
  28. import sys
  29. import tarfile
  30. import tempfile
  31. import threading
  32. from contextlib import suppress
  33. from io import BytesIO
  34. from unittest.mock import patch
  35. from urllib.parse import unquote
  36. from dulwich import client, file, index, objects, protocol, repo
  37. from .. import SkipTest, expectedFailure
  38. from .utils import (
  39. _DEFAULT_GIT,
  40. CompatTestCase,
  41. check_for_daemon,
  42. import_repo_to_dir,
  43. rmtree_ro,
  44. run_git_or_fail,
  45. )
  46. if sys.platform == "win32":
  47. import ctypes
  48. class DulwichClientTestBase:
  49. """Tests for client/server compatibility."""
  50. def setUp(self):
  51. self.gitroot = os.path.dirname(
  52. import_repo_to_dir("server_new.export").rstrip(os.sep)
  53. )
  54. self.dest = os.path.join(self.gitroot, "dest")
  55. file.ensure_dir_exists(self.dest)
  56. run_git_or_fail(["init", "--quiet", "--bare"], cwd=self.dest)
  57. def tearDown(self):
  58. rmtree_ro(self.gitroot)
  59. def assertDestEqualsSrc(self):
  60. repo_dir = os.path.join(self.gitroot, "server_new.export")
  61. dest_repo_dir = os.path.join(self.gitroot, "dest")
  62. with repo.Repo(repo_dir) as src:
  63. with repo.Repo(dest_repo_dir) as dest:
  64. self.assertReposEqual(src, dest)
  65. def _client(self):
  66. raise NotImplementedError
  67. def _build_path(self):
  68. raise NotImplementedError
  69. def _do_send_pack(self):
  70. c = self._client()
  71. srcpath = os.path.join(self.gitroot, "server_new.export")
  72. with repo.Repo(srcpath) as src:
  73. sendrefs = dict(src.get_refs())
  74. del sendrefs[b"HEAD"]
  75. c.send_pack(
  76. self._build_path("/dest"),
  77. lambda _: sendrefs,
  78. src.generate_pack_data,
  79. )
  80. def test_send_pack(self):
  81. self._do_send_pack()
  82. self.assertDestEqualsSrc()
  83. def test_send_pack_nothing_to_send(self):
  84. self._do_send_pack()
  85. self.assertDestEqualsSrc()
  86. # nothing to send, but shouldn't raise either.
  87. self._do_send_pack()
  88. @staticmethod
  89. def _add_file(repo, tree_id, filename, contents):
  90. tree = repo[tree_id]
  91. blob = objects.Blob()
  92. blob.data = contents.encode("utf-8")
  93. repo.object_store.add_object(blob)
  94. tree.add(filename.encode("utf-8"), stat.S_IFREG | 0o644, blob.id)
  95. repo.object_store.add_object(tree)
  96. return tree.id
  97. def test_send_pack_from_shallow_clone(self):
  98. c = self._client()
  99. server_new_path = os.path.join(self.gitroot, "server_new.export")
  100. run_git_or_fail(["config", "http.uploadpack", "true"], cwd=server_new_path)
  101. run_git_or_fail(["config", "http.receivepack", "true"], cwd=server_new_path)
  102. remote_path = self._build_path("/server_new.export")
  103. with repo.Repo(self.dest) as local:
  104. result = c.fetch(remote_path, local, depth=1)
  105. for r in result.refs.items():
  106. local.refs.set_if_equals(r[0], None, r[1])
  107. tree_id = local[local.head()].tree
  108. for filename, contents in [
  109. ("bar", "bar contents"),
  110. ("zop", "zop contents"),
  111. ]:
  112. tree_id = self._add_file(local, tree_id, filename, contents)
  113. commit_id = local.do_commit(
  114. message=b"add " + filename.encode("utf-8"),
  115. committer=b"Joe Example <joe@example.com>",
  116. tree=tree_id,
  117. )
  118. sendrefs = dict(local.get_refs())
  119. del sendrefs[b"HEAD"]
  120. c.send_pack(remote_path, lambda _: sendrefs, local.generate_pack_data)
  121. with repo.Repo(server_new_path) as remote:
  122. self.assertEqual(remote.head(), commit_id)
  123. def test_send_without_report_status(self):
  124. c = self._client()
  125. c._send_capabilities.remove(b"report-status")
  126. srcpath = os.path.join(self.gitroot, "server_new.export")
  127. with repo.Repo(srcpath) as src:
  128. sendrefs = dict(src.get_refs())
  129. del sendrefs[b"HEAD"]
  130. c.send_pack(
  131. self._build_path("/dest"),
  132. lambda _: sendrefs,
  133. src.generate_pack_data,
  134. )
  135. self.assertDestEqualsSrc()
  136. def make_dummy_commit(self, dest):
  137. b = objects.Blob.from_string(b"hi")
  138. dest.object_store.add_object(b)
  139. t = index.commit_tree(dest.object_store, [(b"hi", b.id, 0o100644)])
  140. c = objects.Commit()
  141. c.author = c.committer = b"Foo Bar <foo@example.com>"
  142. c.author_time = c.commit_time = 0
  143. c.author_timezone = c.commit_timezone = 0
  144. c.message = b"hi"
  145. c.tree = t
  146. dest.object_store.add_object(c)
  147. return c.id
  148. def disable_ff_and_make_dummy_commit(self):
  149. # disable non-fast-forward pushes to the server
  150. dest = repo.Repo(os.path.join(self.gitroot, "dest"))
  151. run_git_or_fail(
  152. ["config", "receive.denyNonFastForwards", "true"], cwd=dest.path
  153. )
  154. commit_id = self.make_dummy_commit(dest)
  155. return dest, commit_id
  156. def compute_send(self, src):
  157. sendrefs = dict(src.get_refs())
  158. del sendrefs[b"HEAD"]
  159. return sendrefs, src.generate_pack_data
  160. def test_send_pack_one_error(self):
  161. dest, dummy_commit = self.disable_ff_and_make_dummy_commit()
  162. dest.refs[b"refs/heads/master"] = dummy_commit
  163. repo_dir = os.path.join(self.gitroot, "server_new.export")
  164. with repo.Repo(repo_dir) as src:
  165. sendrefs, gen_pack = self.compute_send(src)
  166. c = self._client()
  167. result = c.send_pack(
  168. self._build_path("/dest"), lambda _: sendrefs, gen_pack
  169. )
  170. self.assertEqual(
  171. {
  172. b"refs/heads/branch": None,
  173. b"refs/heads/master": "non-fast-forward",
  174. },
  175. result.ref_status,
  176. )
  177. def test_send_pack_multiple_errors(self):
  178. dest, dummy = self.disable_ff_and_make_dummy_commit()
  179. # set up for two non-ff errors
  180. branch, master = b"refs/heads/branch", b"refs/heads/master"
  181. dest.refs[branch] = dest.refs[master] = dummy
  182. repo_dir = os.path.join(self.gitroot, "server_new.export")
  183. with repo.Repo(repo_dir) as src:
  184. sendrefs, gen_pack = self.compute_send(src)
  185. c = self._client()
  186. result = c.send_pack(
  187. self._build_path("/dest"), lambda _: sendrefs, gen_pack
  188. )
  189. self.assertEqual(
  190. {branch: "non-fast-forward", master: "non-fast-forward"},
  191. result.ref_status,
  192. )
  193. def test_archive(self):
  194. c = self._client()
  195. f = BytesIO()
  196. c.archive(self._build_path("/server_new.export"), b"HEAD", f.write)
  197. f.seek(0)
  198. tf = tarfile.open(fileobj=f)
  199. self.assertEqual(["baz", "foo"], tf.getnames())
  200. def test_fetch_pack(self):
  201. c = self._client()
  202. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  203. result = c.fetch(self._build_path("/server_new.export"), dest)
  204. for r in result.refs.items():
  205. dest.refs.set_if_equals(r[0], None, r[1])
  206. self.assertDestEqualsSrc()
  207. def test_fetch_pack_depth(self):
  208. c = self._client()
  209. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  210. result = c.fetch(self._build_path("/server_new.export"), dest, depth=1)
  211. for r in result.refs.items():
  212. dest.refs.set_if_equals(r[0], None, r[1])
  213. self.assertEqual(
  214. dest.get_shallow(),
  215. {
  216. b"35e0b59e187dd72a0af294aedffc213eaa4d03ff",
  217. b"514dc6d3fbfe77361bcaef320c4d21b72bc10be9",
  218. },
  219. )
  220. def test_repeat(self):
  221. c = self._client()
  222. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  223. result = c.fetch(self._build_path("/server_new.export"), dest)
  224. for r in result.refs.items():
  225. dest.refs.set_if_equals(r[0], None, r[1])
  226. self.assertDestEqualsSrc()
  227. result = c.fetch(self._build_path("/server_new.export"), dest)
  228. for r in result.refs.items():
  229. dest.refs.set_if_equals(r[0], None, r[1])
  230. self.assertDestEqualsSrc()
  231. def test_fetch_empty_pack(self):
  232. c = self._client()
  233. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  234. result = c.fetch(self._build_path("/server_new.export"), dest)
  235. for r in result.refs.items():
  236. dest.refs.set_if_equals(r[0], None, r[1])
  237. self.assertDestEqualsSrc()
  238. def dw(refs, **kwargs):
  239. return list(refs.values())
  240. result = c.fetch(
  241. self._build_path("/server_new.export"),
  242. dest,
  243. determine_wants=dw,
  244. )
  245. for r in result.refs.items():
  246. dest.refs.set_if_equals(r[0], None, r[1])
  247. self.assertDestEqualsSrc()
  248. def test_incremental_fetch_pack(self):
  249. self.test_fetch_pack()
  250. dest, dummy = self.disable_ff_and_make_dummy_commit()
  251. dest.refs[b"refs/heads/master"] = dummy
  252. c = self._client()
  253. repo_dir = os.path.join(self.gitroot, "server_new.export")
  254. with repo.Repo(repo_dir) as dest:
  255. result = c.fetch(self._build_path("/dest"), dest)
  256. for r in result.refs.items():
  257. dest.refs.set_if_equals(r[0], None, r[1])
  258. self.assertDestEqualsSrc()
  259. def test_fetch_pack_no_side_band_64k(self):
  260. if protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH >= 2:
  261. raise SkipTest("side-band-64k cannot be disabled with git protocol v2")
  262. c = self._client()
  263. c._fetch_capabilities.remove(b"side-band-64k")
  264. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  265. result = c.fetch(self._build_path("/server_new.export"), dest)
  266. for r in result.refs.items():
  267. dest.refs.set_if_equals(r[0], None, r[1])
  268. self.assertDestEqualsSrc()
  269. def test_fetch_pack_zero_sha(self):
  270. # zero sha1s are already present on the client, and should
  271. # be ignored
  272. c = self._client()
  273. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  274. result = c.fetch(
  275. self._build_path("/server_new.export"),
  276. dest,
  277. lambda refs, **kwargs: [protocol.ZERO_SHA],
  278. )
  279. for r in result.refs.items():
  280. dest.refs.set_if_equals(r[0], None, r[1])
  281. def test_send_remove_branch(self):
  282. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  283. dummy_commit = self.make_dummy_commit(dest)
  284. dest.refs[b"refs/heads/master"] = dummy_commit
  285. dest.refs[b"refs/heads/abranch"] = dummy_commit
  286. sendrefs = dict(dest.refs)
  287. sendrefs[b"refs/heads/abranch"] = b"00" * 20
  288. del sendrefs[b"HEAD"]
  289. def gen_pack(have, want, ofs_delta=False, progress=None):
  290. return 0, []
  291. c = self._client()
  292. self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit)
  293. c.send_pack(self._build_path("/dest"), lambda _: sendrefs, gen_pack)
  294. self.assertNotIn(b"refs/heads/abranch", dest.refs)
  295. def test_send_new_branch_empty_pack(self):
  296. with repo.Repo(os.path.join(self.gitroot, "dest")) as dest:
  297. dummy_commit = self.make_dummy_commit(dest)
  298. dest.refs[b"refs/heads/master"] = dummy_commit
  299. dest.refs[b"refs/heads/abranch"] = dummy_commit
  300. sendrefs = {b"refs/heads/bbranch": dummy_commit}
  301. def gen_pack(have, want, ofs_delta=False, progress=None):
  302. return 0, []
  303. c = self._client()
  304. self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit)
  305. c.send_pack(self._build_path("/dest"), lambda _: sendrefs, gen_pack)
  306. self.assertEqual(dummy_commit, dest.refs[b"refs/heads/abranch"])
  307. def test_get_refs(self):
  308. c = self._client()
  309. refs = c.get_refs(self._build_path("/server_new.export"))
  310. repo_dir = os.path.join(self.gitroot, "server_new.export")
  311. with repo.Repo(repo_dir) as dest:
  312. self.assertDictEqual(dest.refs.as_dict(), refs)
  313. class DulwichTCPClientTest(CompatTestCase, DulwichClientTestBase):
  314. def setUp(self):
  315. CompatTestCase.setUp(self)
  316. DulwichClientTestBase.setUp(self)
  317. if check_for_daemon(limit=1):
  318. raise SkipTest(
  319. f"git-daemon was already running on port {protocol.TCP_GIT_PORT}"
  320. )
  321. fd, self.pidfile = tempfile.mkstemp(
  322. prefix="dulwich-test-git-client", suffix=".pid"
  323. )
  324. os.fdopen(fd).close()
  325. args = [
  326. _DEFAULT_GIT,
  327. "daemon",
  328. "--verbose",
  329. "--export-all",
  330. f"--pid-file={self.pidfile}",
  331. f"--base-path={self.gitroot}",
  332. "--enable=receive-pack",
  333. "--enable=upload-archive",
  334. "--listen=localhost",
  335. "--reuseaddr",
  336. self.gitroot,
  337. ]
  338. self.process = subprocess.Popen(
  339. args,
  340. cwd=self.gitroot,
  341. stdout=subprocess.PIPE,
  342. stderr=subprocess.PIPE,
  343. )
  344. if not check_for_daemon():
  345. raise SkipTest("git-daemon failed to start")
  346. def tearDown(self):
  347. with open(self.pidfile) as f:
  348. pid = int(f.read().strip())
  349. if sys.platform == "win32":
  350. PROCESS_TERMINATE = 1
  351. handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, pid)
  352. ctypes.windll.kernel32.TerminateProcess(handle, -1)
  353. ctypes.windll.kernel32.CloseHandle(handle)
  354. else:
  355. with suppress(OSError):
  356. os.kill(pid, signal.SIGKILL)
  357. os.unlink(self.pidfile)
  358. self.process.wait()
  359. self.process.stdout.close()
  360. self.process.stderr.close()
  361. DulwichClientTestBase.tearDown(self)
  362. CompatTestCase.tearDown(self)
  363. def _client(self):
  364. return client.TCPGitClient("localhost")
  365. def _build_path(self, path):
  366. return path
  367. if sys.platform == "win32" and protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH < 2:
  368. @expectedFailure
  369. def test_fetch_pack_no_side_band_64k(self):
  370. DulwichClientTestBase.test_fetch_pack_no_side_band_64k(self)
  371. def test_send_remove_branch(self):
  372. # This test fails intermittently on my machine, probably due to some sort
  373. # of race condition. Probably also related to #1015
  374. self.skipTest("skip flaky test; see #1015")
  375. @patch("dulwich.protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH", new=0)
  376. class DulwichTCPClientTestGitProtov0(DulwichTCPClientTest):
  377. pass
  378. class TestSSHVendor:
  379. @staticmethod
  380. def run_command(
  381. host,
  382. command,
  383. username=None,
  384. port=None,
  385. password=None,
  386. key_filename=None,
  387. protocol_version=None,
  388. ):
  389. cmd, path = command.split(" ")
  390. cmd = cmd.split("-", 1)
  391. path = path.replace("'", "")
  392. env = dict(os.environ)
  393. if protocol_version is None:
  394. protocol_version = protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  395. if protocol_version > 0:
  396. env["GIT_PROTOCOL"] = f"version={protocol_version}"
  397. p = subprocess.Popen(
  398. [*cmd, path],
  399. bufsize=0,
  400. stdin=subprocess.PIPE,
  401. stdout=subprocess.PIPE,
  402. stderr=subprocess.PIPE,
  403. env=env,
  404. )
  405. return client.SubprocessWrapper(p)
  406. class DulwichMockSSHClientTest(CompatTestCase, DulwichClientTestBase):
  407. def setUp(self):
  408. CompatTestCase.setUp(self)
  409. DulwichClientTestBase.setUp(self)
  410. self.real_vendor = client.get_ssh_vendor
  411. client.get_ssh_vendor = TestSSHVendor
  412. def tearDown(self):
  413. DulwichClientTestBase.tearDown(self)
  414. CompatTestCase.tearDown(self)
  415. client.get_ssh_vendor = self.real_vendor
  416. def _client(self):
  417. return client.SSHGitClient("localhost")
  418. def _build_path(self, path):
  419. return self.gitroot + path
  420. @patch("dulwich.protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH", new=0)
  421. class DulwichMockSSHClientTestGitProtov0(DulwichMockSSHClientTest):
  422. pass
  423. class DulwichSubprocessClientTest(CompatTestCase, DulwichClientTestBase):
  424. def setUp(self):
  425. CompatTestCase.setUp(self)
  426. DulwichClientTestBase.setUp(self)
  427. def tearDown(self):
  428. DulwichClientTestBase.tearDown(self)
  429. CompatTestCase.tearDown(self)
  430. def _client(self):
  431. return client.SubprocessGitClient()
  432. def _build_path(self, path):
  433. return self.gitroot + path
  434. @patch("dulwich.protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH", new=0)
  435. class DulwichSubprocessClientTestGitProtov0(DulwichSubprocessClientTest):
  436. pass
  437. class GitHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
  438. """HTTP Request handler that calls out to 'git http-backend'."""
  439. # Make rfile unbuffered -- we need to read one line and then pass
  440. # the rest to a subprocess, so we can't use buffered input.
  441. rbufsize = 0
  442. def do_POST(self):
  443. self.run_backend()
  444. def do_GET(self):
  445. self.run_backend()
  446. def send_head(self):
  447. return self.run_backend()
  448. def log_request(self, code="-", size="-"):
  449. # Let's be quiet, the test suite is noisy enough already
  450. pass
  451. def run_backend(self):
  452. """Call out to git http-backend."""
  453. # Based on CGIHTTPServer.CGIHTTPRequestHandler.run_cgi:
  454. # Copyright (c) 2001-2010 Python Software Foundation;
  455. # All Rights Reserved
  456. # Licensed under the Python Software Foundation License.
  457. rest = self.path
  458. # find an explicit query string, if present.
  459. i = rest.rfind("?")
  460. if i >= 0:
  461. rest, query = rest[:i], rest[i + 1 :]
  462. else:
  463. query = ""
  464. env = copy.deepcopy(os.environ)
  465. env["SERVER_SOFTWARE"] = self.version_string()
  466. env["SERVER_NAME"] = self.server.server_name
  467. env["GATEWAY_INTERFACE"] = "CGI/1.1"
  468. env["SERVER_PROTOCOL"] = self.protocol_version
  469. env["SERVER_PORT"] = str(self.server.server_port)
  470. env["GIT_PROJECT_ROOT"] = self.server.root_path
  471. env["GIT_HTTP_EXPORT_ALL"] = "1"
  472. env["REQUEST_METHOD"] = self.command
  473. uqrest = unquote(rest)
  474. env["PATH_INFO"] = uqrest
  475. env["SCRIPT_NAME"] = "/"
  476. if query:
  477. env["QUERY_STRING"] = query
  478. host = self.address_string()
  479. if host != self.client_address[0]:
  480. env["REMOTE_HOST"] = host
  481. env["REMOTE_ADDR"] = self.client_address[0]
  482. authorization = self.headers.get("authorization")
  483. if authorization:
  484. authorization = authorization.split()
  485. if len(authorization) == 2:
  486. import base64
  487. import binascii
  488. env["AUTH_TYPE"] = authorization[0]
  489. if authorization[0].lower() == "basic":
  490. try:
  491. authorization = base64.decodestring(authorization[1])
  492. except binascii.Error:
  493. pass
  494. else:
  495. authorization = authorization.split(":")
  496. if len(authorization) == 2:
  497. env["REMOTE_USER"] = authorization[0]
  498. # XXX REMOTE_IDENT
  499. content_type = self.headers.get("content-type")
  500. if content_type:
  501. env["CONTENT_TYPE"] = content_type
  502. length = self.headers.get("content-length")
  503. if length:
  504. env["CONTENT_LENGTH"] = length
  505. referer = self.headers.get("referer")
  506. if referer:
  507. env["HTTP_REFERER"] = referer
  508. accept = []
  509. for line in self.headers.getallmatchingheaders("accept"):
  510. if line[:1] in "\t\n\r ":
  511. accept.append(line.strip())
  512. else:
  513. accept = accept + line[7:].split(",")
  514. env["HTTP_ACCEPT"] = ",".join(accept)
  515. ua = self.headers.get("user-agent")
  516. if ua:
  517. env["HTTP_USER_AGENT"] = ua
  518. co = self.headers.get("cookie")
  519. if co:
  520. env["HTTP_COOKIE"] = co
  521. proto = self.headers.get("Git-Protocol")
  522. if proto:
  523. env["GIT_PROTOCOL"] = proto
  524. # XXX Other HTTP_* headers
  525. # Since we're setting the env in the parent, provide empty
  526. # values to override previously set values
  527. for k in (
  528. "QUERY_STRING",
  529. "REMOTE_HOST",
  530. "CONTENT_LENGTH",
  531. "HTTP_USER_AGENT",
  532. "HTTP_COOKIE",
  533. "HTTP_REFERER",
  534. ):
  535. env.setdefault(k, "")
  536. self.wfile.write(b"HTTP/1.1 200 Script output follows\r\n")
  537. self.wfile.write((f"Server: {self.server.server_name}\r\n").encode("ascii"))
  538. self.wfile.write((f"Date: {self.date_time_string()}\r\n").encode("ascii"))
  539. decoded_query = query.replace("+", " ")
  540. try:
  541. nbytes = int(length)
  542. except (TypeError, ValueError):
  543. nbytes = -1
  544. if self.command.lower() == "post":
  545. if nbytes > 0:
  546. data = self.rfile.read(nbytes)
  547. elif self.headers.get("transfer-encoding") == "chunked":
  548. chunks = []
  549. while True:
  550. line = self.rfile.readline()
  551. length = int(line.rstrip(), 16)
  552. chunk = self.rfile.read(length + 2)
  553. chunks.append(chunk[:-2])
  554. if length == 0:
  555. break
  556. data = b"".join(chunks)
  557. env["CONTENT_LENGTH"] = str(len(data))
  558. else:
  559. raise AssertionError
  560. else:
  561. data = None
  562. env["CONTENT_LENGTH"] = "0"
  563. # throw away additional data [see bug #427345]
  564. while select.select([self.rfile._sock], [], [], 0)[0]:
  565. if not self.rfile._sock.recv(1):
  566. break
  567. args = ["http-backend"]
  568. if "=" not in decoded_query:
  569. args.append(decoded_query)
  570. stdout = run_git_or_fail(args, input=data, env=env, stderr=subprocess.PIPE)
  571. self.wfile.write(stdout)
  572. class HTTPGitServer(http.server.HTTPServer):
  573. allow_reuse_address = True
  574. def __init__(self, server_address, root_path) -> None:
  575. http.server.HTTPServer.__init__(self, server_address, GitHTTPRequestHandler)
  576. self.root_path = root_path
  577. self.server_name = "localhost"
  578. def get_url(self):
  579. return f"http://{self.server_name}:{self.server_port}/"
  580. class DulwichHttpClientTest(CompatTestCase, DulwichClientTestBase):
  581. min_git_version = (1, 7, 0, 2)
  582. def setUp(self):
  583. CompatTestCase.setUp(self)
  584. DulwichClientTestBase.setUp(self)
  585. self._httpd = HTTPGitServer(("localhost", 0), self.gitroot)
  586. self.addCleanup(self._httpd.shutdown)
  587. threading.Thread(target=self._httpd.serve_forever).start()
  588. run_git_or_fail(["config", "http.uploadpack", "true"], cwd=self.dest)
  589. run_git_or_fail(["config", "http.receivepack", "true"], cwd=self.dest)
  590. def tearDown(self):
  591. DulwichClientTestBase.tearDown(self)
  592. CompatTestCase.tearDown(self)
  593. self._httpd.shutdown()
  594. self._httpd.socket.close()
  595. def _client(self):
  596. return client.HttpGitClient(self._httpd.get_url())
  597. def _build_path(self, path):
  598. return path
  599. def test_archive(self):
  600. raise SkipTest("exporting archives not supported over http")
  601. @patch("dulwich.protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH", new=0)
  602. class DulwichHttpClientTestGitProtov0(DulwichHttpClientTest):
  603. pass