test_client.py 24 KB

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