Repositories | Polyback | Log in to see private repositories


polyback-website / db9a7ac7345e94204336a2a121c1338c5462f5f6 / directory_git/index.php

33,982 bytes | parent directory

<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';

// Polyback git server: plain-HTML repository browser + git smart HTTP (via `git http-backend`).
//
// nginx sends every /git/... request here (see container/nginx.conf). URL layout:
//   /git/                              repository list (+ admin "create repo" form, git token form)
//   /git/<repo>                        clone URL, branches, latest commits, root file list
//   /git/<repo>/tree/<ref>/<path>      directory listing
//   /git/<repo>/blob/<ref>/<path>      file contents
//   /git/<repo>.git/info/refs          \
//   /git/<repo>.git/git-upload-pack     > git smart HTTP, handed to `git http-backend`
//   /git/<repo>.git/git-receive-pack   /
//
// Access rules:
//   public repo     - anyone may clone/browse, no login
//   private repo    - clone/browse needs any Polyback account that isn't banned
//   admin-only repo - clone/browse needs an administrator (the same ones who may push)
//   push          - always needs an administrator (Users::STAFF_ADMINISTRATOR by default, with 2FA enabled)
//   create/delete/change visibility - administrators, through the HTML forms below (CSRF protected)
//
// git clients authenticate with HTTP Basic: Polyback username + either the site password (accounts
// without 2FA only) or a git access token generated on /git/ (required for accounts with 2FA, which
// includes every administrator). Credentials are only accepted over HTTPS (or plain HTTP from localhost).
//
// Optional settings in polygonshared/config.php:
//   'git' => [
//       'root' => '/var/www/polygondata/git',   // where the bare repos live (outside the web root)
//       'public' => ['polyback-website'],        // repos that are public unless an admin changed it
//       'adminLevels' => [2],                    // users.adminlevel values that may push / manage repos
//       'binary' => 'git',
//   ],

use pizzaboxer\ProjectPolygon\Polygon;
use pizzaboxer\ProjectPolygon\Users;
use pizzaboxer\ProjectPolygon\Password;
use pizzaboxer\ProjectPolygon\Database;

define("GIT_ROOT", rtrim(SITE_CONFIG["git"]["root"] ?? "/var/www/polygondata/git", "/"));
define("GIT_BIN", SITE_CONFIG["git"]["binary"] ?? "git");
define("GIT_DEFAULT_PUBLIC", SITE_CONFIG["git"]["public"] ?? ["polyback-website"]);
define("GIT_ADMIN_LEVELS", array_map("intval", SITE_CONFIG["git"]["adminLevels"] ?? [Users::STAFF_ADMINISTRATOR, Users::STAFF_SUPERADMIN]));
// server-side hooks for every repo (pre-receive refuses force pushes/deletions except by super admins)
define("GIT_HOOKS_DIR", __DIR__ . "/hooks");
define("GIT_VISIBILITY_FILE", "polyback-visibility");
define("GIT_MAX_BLOB", 1024 * 1024);

/* ---------- helpers ---------- */

function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"); }

function git_valid_name($name)
{
	// [A-Za-z0-9._-]{1,64}; no leading dot or dash, not ending in ".git" (that suffix is the smart HTTP URL)
	return is_string($name) && preg_match('/^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}$/', $name) && !str_ends_with(strtolower($name), ".git");
}

function git_valid_ref($ref)
{
	return is_string($ref) && preg_match('#^[A-Za-z0-9_][A-Za-z0-9._/-]{0,199}$#', $ref)
		&& !str_contains($ref, "..") && !str_contains($ref, "//") && !str_ends_with($ref, "/") && !str_ends_with($ref, ".lock");
}

// $segments are already url-decoded path segments; returns "a/b/c" or false
function git_valid_path(array $segments)
{
	foreach ($segments as $seg)
	{
		if ($seg === "" || $seg === "." || $seg === ".." || preg_match('/[\x00-\x1f\x7f]/', $seg)) return false;
	}
	return implode("/", $segments);
}

function git_repo_dir($name) { return GIT_ROOT . "/" . $name . ".git"; }

function git_repo_exists($name)
{
	return git_valid_name($name) && is_dir(git_repo_dir($name)) && is_file(git_repo_dir($name) . "/HEAD");
}

const GIT_VISIBILITIES = ["public" => "Public", "private" => "Private", "admin" => "Admin only"];

// "public", "private" or "admin": what the repo's flag file says (set when created or changed
// by an admin); repos without one are public if config lists them, else private
function git_repo_visibility($name)
{
	$flag = @file_get_contents(git_repo_dir($name) . "/" . GIT_VISIBILITY_FILE);
	if ($flag !== false && isset(GIT_VISIBILITIES[trim($flag)])) return trim($flag);
	return in_array($name, GIT_DEFAULT_PUBLIC, true) ? "public" : "private";
}

function git_repo_public($name) { return git_repo_visibility($name) === "public"; }

// May this reader (null: anonymous) read a repo with this visibility?
function git_may_read($visibility, $isUser, $isAdmin)
{
	if ($visibility === "public") return true;
	if ($visibility === "private") return $isUser;
	return $isAdmin;
}

function git_visibility_text($visibility)
{
	return [
		"public" => "Public: anyone can clone it.",
		"private" => "Private: only logged-in Polyback users can clone it.",
		"admin" => "Admin only: only administrators can clone or browse it.",
	][$visibility];
}

// Link the repo's server-side hooks to the shared ones (pre-receive: force pushes and ref
// deletions only for super admins). Done at creation and before every push, so repos created
// before the hook existed get it too.
function git_install_hooks($dir)
{
	$target = GIT_HOOKS_DIR . "/pre-receive";
	$link = "$dir/hooks/pre-receive";
	if (is_link($link) && readlink($link) === $target) return true;
	if (!is_dir("$dir/hooks")) @mkdir("$dir/hooks", 0755);
	@unlink($link);
	return @symlink($target, $link);
}

// Create a bare repo (initial branch master) with a visibility; logged as a staff action.
// Returns null on success or an error message.
function git_create_repo($name, $visibility, $adminId, $how)
{
	if (!git_valid_name($name)) return "Invalid repository name.";
	$dir = git_repo_dir($name);
	if (!is_dir(GIT_ROOT) && !@mkdir(GIT_ROOT, 0755, true)) return "Could not create " . GIT_ROOT . ".";
	[$code] = git_run(["init", "--quiet", "--bare", "--initial-branch=master", "--end-of-options", $dir]);
	if ($code !== 0) return "git init failed.";
	if (!git_install_hooks($dir)) return "Could not install the repository's hooks.";
	if (!isset(GIT_VISIBILITIES[$visibility])) $visibility = "private";
	file_put_contents("$dir/" . GIT_VISIBILITY_FILE, "$visibility\n");
	Database::singleton()->run(
		"INSERT INTO stafflogs (time, adminId, action) VALUES (UNIX_TIMESTAMP(), :uid, :action)",
		[":uid" => $adminId, ":action" => "[ Git ] Created repository $name (" . GIT_VISIBILITIES[$visibility] . ", from $how)"]
	);
	return null;
}

function git_list_repos()
{
	$repos = [];
	foreach (@scandir(GIT_ROOT) ?: [] as $entry)
	{
		if (!str_ends_with($entry, ".git")) continue;
		$name = substr($entry, 0, -4);
		if (git_repo_exists($name)) $repos[] = $name;
	}
	natcasesort($repos);
	return array_values($repos);
}

function git_env()
{
	return [
		"PATH" => "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
		"GIT_CONFIG_GLOBAL" => "/dev/null",
		"GIT_TERMINAL_PROMPT" => "0",
		"LANG" => "C.UTF-8",
	];
}

// runs git with an argument array (no shell); returns [exitCode, stdout]
function git_run(array $args, $repo = null, $maxBytes = 8 * 1024 * 1024)
{
	$cmd = [GIT_BIN];
	if ($repo !== null) $cmd[] = "--git-dir=" . git_repo_dir($repo);
	$cmd = array_merge($cmd, $args);

	$proc = @proc_open($cmd, [0 => ["file", "/dev/null", "r"], 1 => ["pipe", "w"], 2 => ["file", "/dev/null", "w"]], $pipes, GIT_ROOT, git_env());
	if (!is_resource($proc)) return [-1, ""];

	$out = stream_get_contents($pipes[1], $maxBytes);
	fclose($pipes[1]);
	return [proc_close($proc), $out === false ? "" : $out];
}

function git_resolve_commit($repo, $ref)
{
	if (!git_valid_ref($ref)) return false;
	[$code, $out] = git_run(["rev-parse", "--verify", "--quiet", "--end-of-options", $ref . "^{commit}"], $repo);
	$sha = trim($out);
	return ($code === 0 && preg_match('/^[0-9a-f]{40,64}$/', $sha)) ? $sha : false;
}

function git_branches($repo)
{
	[, $out] = git_run(["for-each-ref", "--sort=-committerdate", "--format=%(refname:strip=2)%09%(committerdate:iso-strict)", "refs/heads/"], $repo);
	$branches = [];
	foreach (explode("\n", trim($out)) as $line)
	{
		if ($line === "") continue;
		[$name, $date] = array_pad(explode("\t", $line, 2), 2, "");
		$branches[$name] = $date;
	}
	return $branches;
}

function git_default_branch($repo, array $branches)
{
	[$code, $out] = git_run(["symbolic-ref", "--quiet", "--short", "HEAD"], $repo);
	$head = trim($out);
	if ($code === 0 && isset($branches[$head])) return $head;
	return array_key_first($branches); // HEAD points at a branch nobody pushed: use the newest one
}

function git_last_commit_date($repo)
{
	[, $out] = git_run(["for-each-ref", "--count=1", "--sort=-committerdate", "--format=%(committerdate:iso-strict)", "refs/heads/"], $repo);
	return trim($out);
}

// entries of a tree object: [[mode, type, name], ...], directories first
function git_ls_tree($repo, $commit, $path)
{
	[$code, $out] = git_run(["ls-tree", "-z", "--end-of-options", $commit . ":" . $path], $repo);
	if ($code !== 0) return false;
	$entries = [];
	foreach (explode("\0", $out) as $record)
	{
		if ($record === "" || !str_contains($record, "\t")) continue;
		[$meta, $name] = explode("\t", $record, 2);
		[$mode, $type] = explode(" ", $meta);
		$entries[] = [$mode, $type, $name];
	}
	usort($entries, fn($a, $b) => [$a[1] !== "tree", $a[2]] <=> [$b[1] !== "tree", $b[2]]);
	return $entries;
}

function git_object_type($repo, $commit, $path)
{
	[$code, $out] = git_run(["cat-file", "-t", "--end-of-options", $commit . ":" . $path], $repo);
	return $code === 0 ? trim($out) : false;
}

function git_rmtree($dir)
{
	$items = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
	foreach ($items as $item)
	{
		if ($item->isDir() && !$item->isLink()) rmdir($item->getPathname());
		else unlink($item->getPathname());
	}
	return rmdir($dir);
}

/* ---------- auth ---------- */

// Basic credentials travel in clear text, so only accept them over HTTPS (HTTPS=on is set by nginx from
// X-Forwarded-Proto) or from a direct, non-proxied localhost connection.
function git_secure_transport()
{
	if (($_SERVER["HTTPS"] ?? "") === "on") return true;
	if (isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) || isset($_SERVER["HTTP_X_FORWARDED_FOR"])) return false;
	return in_array($_SERVER["REMOTE_ADDR"] ?? "", ["127.0.0.1", "::1"], true);
}

function git_is_admin($user)
{
	$user = (object)$user;
	return in_array((int)$user->adminlevel, GIT_ADMIN_LEVELS, true) && $user->twofa; // same 2FA rule as Users::RequireAdmin
}

// Super admins alone may do the irreversible: delete repos, force push, delete branches/tags.
function git_is_superadmin($user)
{
	$user = (object)$user;
	return (int)$user->adminlevel === Users::STAFF_SUPERADMIN && $user->twofa;
}

function git_token_file($userId) { return GIT_ROOT . "/.tokens/" . (int)$userId; }

function git_check_token($userId, $token)
{
	if (strlen($token) !== 64 || !ctype_xdigit($token)) return false;
	$stored = @file_get_contents(git_token_file($userId));
	return $stored !== false && hash_equals(trim($stored), hash("sha256", strtolower($token)));
}

function git_basic_credentials()
{
	if (isset($_SERVER["PHP_AUTH_USER"])) return [$_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"] ?? ""];
	$header = $_SERVER["HTTP_AUTHORIZATION"] ?? $_SERVER["REDIRECT_HTTP_AUTHORIZATION"] ?? "";
	if (stripos($header, "basic ") !== 0) return null;
	$decoded = base64_decode(substr($header, 6), true);
	if ($decoded === false || !str_contains($decoded, ":")) return null;
	return explode(":", $decoded, 2);
}

// verifies like the site login does; returns the user row, "banned", or false
function git_authenticate($username, $password)
{
	if ($username === "" || $password === "") return false;
	$user = Users::GetInfoFromName($username);
	if (!$user) return false;
	if (Polygon::IsDevSite() && !in_array($user->id, SITE_CONFIG["DevWhitelist"])) return false;

	$ok = git_check_token($user->id, $password);
	// the site password alone can't satisfy 2FA, so 2FA accounts must use a git token
	if (!$ok && !$user->twofa && $user->password) $ok = (bool)(new Password($password))->verify($user->password);
	if (!$ok) return false;

	if ($user->Banned) return "banned";
	return $user;
}

function git_plain_error($code, $message, $challenge = false)
{
	http_response_code($code);
	if ($challenge) header('WWW-Authenticate: Basic realm="Polyback Git", charset="UTF-8"');
	header("Content-Type: text/plain; charset=utf-8");
	header("Cache-Control: no-cache");
	echo $message, "\n";
	exit;
}

/* ---------- git smart HTTP ---------- */

function git_smart_http($name, $sub)
{
	$method = $_SERVER["REQUEST_METHOD"];
	$service = null;

	if ($sub === "info/refs" && $method === "GET") $service = $_GET["service"] ?? "";
	else if (($sub === "git-upload-pack" || $sub === "git-receive-pack") && $method === "POST") $service = $sub;

	// only the smart protocol is served (no dumb HTTP object downloads)
	if ($service !== "git-upload-pack" && $service !== "git-receive-pack")
		git_plain_error(404, "Not found (only git smart HTTP is supported)");

	$push = $service === "git-receive-pack";
	$exists = git_repo_exists($name);
	$public = $exists && git_repo_public($name);
	$secure = git_secure_transport();
	$user = null;

	$credentials = git_basic_credentials();
	if ($credentials !== null)
	{
		if (!$secure) git_plain_error(403, "Credentials are only accepted over HTTPS. Use the https:// clone URL.");
		$user = git_authenticate($credentials[0], $credentials[1]);
		if ($user === "banned") git_plain_error(403, "This account is banned.");
		if (!$user) git_plain_error(401, "Invalid username, password or git token. Accounts with 2FA must use a git token from /git/.", true);
	}

	// anonymous users may only read public repos; never push
	if (!$user && ($push || !$public))
	{
		if (!$secure) git_plain_error(403, "This needs a Polyback login, which is only accepted over HTTPS.");
		git_plain_error(401, "Log in with your Polyback username and password (or git token).", true);
	}

	if ($push && !git_is_admin($user)) git_plain_error(403, "Only administrators can push.");
	// an administrator pushing to a repo that doesn't exist yet creates it (private)
	if (!$exists && $push)
	{
		$error = git_create_repo($name, "private", (int) ((object) $user)->id, "a push");
		if ($error !== null) git_plain_error(500, $error);
		$exists = true;
	}
	if (!$exists) git_plain_error(404, "Repository not found.");
	// no push without the history-protecting hook in place
	if ($push && !git_install_hooks(git_repo_dir($name))) git_plain_error(500, "The repository's hooks could not be installed.");
	// admin-only repos: reading needs an administrator too (said as "not found" to others)
	if (!$push && !git_may_read(git_repo_visibility($name), $user !== null, $user !== null && git_is_admin($user))) git_plain_error(404, "Repository not found.");

	set_time_limit(0);
	ignore_user_abort(false);
	while (ob_get_level()) ob_end_clean();

	$env = git_env() + [
		"GIT_PROJECT_ROOT" => GIT_ROOT,
		"GIT_HTTP_EXPORT_ALL" => "1",
		"PATH_INFO" => "/" . $name . ".git/" . $sub,
		"REQUEST_METHOD" => $method,
		"QUERY_STRING" => $_SERVER["QUERY_STRING"] ?? "",
		"CONTENT_TYPE" => $_SERVER["CONTENT_TYPE"] ?? "",
		"REMOTE_ADDR" => $_SERVER["REMOTE_ADDR"] ?? "",
		// read by the repo's pre-receive hook: only super admins may force push or delete refs
		"POLYBACK_GIT_SUPERADMIN" => ($user !== null && git_is_superadmin($user)) ? "1" : "0",
	];
	if (($_SERVER["CONTENT_LENGTH"] ?? "") !== "") $env["CONTENT_LENGTH"] = (string)(int)$_SERVER["CONTENT_LENGTH"];
	if (isset($_SERVER["HTTP_CONTENT_ENCODING"])) $env["HTTP_CONTENT_ENCODING"] = $_SERVER["HTTP_CONTENT_ENCODING"];
	if (isset($_SERVER["HTTP_GIT_PROTOCOL"])) $env["HTTP_GIT_PROTOCOL"] = $_SERVER["HTTP_GIT_PROTOCOL"];
	// http-backend enables receive-pack only when REMOTE_USER is set; we only get here for pushes by admins
	if ($user) $env["REMOTE_USER"] = $user->username;

	$proc = @proc_open([GIT_BIN, "http-backend"], [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => ["pipe", "w"]], $pipes, GIT_ROOT, $env);
	if (!is_resource($proc)) git_plain_error(500, "Could not start git http-backend.");

	[$stdin, $stdout, $stderr] = $pipes;
	stream_set_blocking($stdin, false);
	stream_set_blocking($stdout, false);
	stream_set_blocking($stderr, false);

	// stream the request body to the backend and its response to the client in 64 KiB pieces
	$input = fopen("php://input", "rb");
	$inBuf = "";
	$inEof = $method !== "POST";
	$stdinOpen = true;
	$open = [(int)$stdout => $stdout, (int)$stderr => $stderr];
	$headersDone = false;
	$headBuf = "";
	$errBuf = "";

	while ($open)
	{
		if (!$inEof && $inBuf === "")
		{
			$chunk = fread($input, 65536);
			if ($chunk === false || $chunk === "") $inEof = true; // blocking read: empty means end of body
			else $inBuf = $chunk;
		}
		if ($stdinOpen && $inEof && $inBuf === "") { fclose($stdin); $stdinOpen = false; }

		$read = array_values($open);
		$write = ($stdinOpen && $inBuf !== "") ? [$stdin] : [];
		$except = null;
		$ready = @stream_select($read, $write, $except, 600);
		if ($ready === false || $ready === 0) break;

		if ($write)
		{
			$n = @fwrite($stdin, $inBuf);
			if ($n === false) { $inBuf = ""; $inEof = true; } // backend stopped reading
			else $inBuf = (string)substr($inBuf, $n);
		}

		foreach ($read as $stream)
		{
			$data = @fread($stream, 65536);
			if ($data === false || ($data === "" && feof($stream)))
			{
				fclose($stream);
				unset($open[(int)$stream]);
				continue;
			}
			if ($stream === $stderr) { if (strlen($errBuf) < 8192) $errBuf .= $data; continue; }

			if (!$headersDone)
			{
				$headBuf .= $data;
				$pos = strpos($headBuf, "\r\n\r\n"); $sep = 4;
				$lf = strpos($headBuf, "\n\n");
				if ($lf !== false && ($pos === false || $lf < $pos)) { $pos = $lf; $sep = 2; }
				if ($pos === false) { if (strlen($headBuf) > 65536) break 2; continue; }

				foreach (preg_split('/\r?\n/', substr($headBuf, 0, $pos)) as $line)
				{
					if (!str_contains($line, ":")) continue;
					[$hname, $hvalue] = array_map("trim", explode(":", $line, 2));
					if (strcasecmp($hname, "Status") === 0) http_response_code((int)$hvalue);
					else header("$hname: $hvalue");
				}
				header("X-Accel-Buffering: no");
				$headersDone = true;
				$data = (string)substr($headBuf, $pos + $sep);
				$headBuf = "";
			}

			if ($data !== "") { echo $data; flush(); }
		}
	}

	if ($stdinOpen) fclose($stdin);
	foreach ($open as $stream) fclose($stream);
	$code = proc_close($proc);
	if ($errBuf !== "") error_log("git http-backend ($name/$sub, exit $code): " . trim($errBuf));
	if (!$headersDone) git_plain_error(502, "git http-backend failed.");
	exit;
}

/* ---------- HTML ---------- */

function page_start($title)
{
	header("Content-Type: text/html; charset=utf-8");
	header("X-Content-Type-Options: nosniff");
	echo "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>", h($title), "</title>\n</head>\n<body>\n";
	echo "<p><a href=\"/git/\">Repositories</a> | <a href=\"/\">", h(SITE_CONFIG["site"]["name"]), "</a> | ";
	if (SESSION) echo "Logged in as <b>", h(SESSION["user"]["username"]), "</b>", git_session_admin() ? " (admin)" : "";
	else echo "<a href=\"/login?ReturnUrl=", h(urlencode($_SERVER["REQUEST_URI"])), "\">Log in</a> to see private repositories";
	echo "</p>\n<hr>\n";
}

function page_end() { echo "</body>\n</html>\n"; exit; }

function page_error($code, $title, $text)
{
	http_response_code($code);
	page_start($title);
	echo "<h1>", h($title), "</h1>\n<p>", h($text), "</p>\n";
	page_end();
}

function page_not_found()
{
	page_error(404, "Not found", SESSION ? "That repository or path does not exist." : "That repository or path does not exist, or you need to log in to see it.");
}

function git_session_admin() { return SESSION && git_is_admin(SESSION["user"]); }
function git_session_superadmin() { return SESSION && git_is_superadmin(SESSION["user"]); }

function git_clone_url($name)
{
	$scheme = (($_SERVER["HTTPS"] ?? "") === "on") ? "https" : "http";
	return $scheme . "://" . $_SERVER["HTTP_HOST"] . "/git/" . rawurlencode($name) . ".git";
}

function git_can_view($name) { return git_repo_exists($name) && git_may_read(git_repo_visibility($name), (bool) SESSION, SESSION && git_session_admin()); }

function csrf_field() { return "<input type=\"hidden\" name=\"csrf\" value=\"" . h(SESSION["csrfToken"]) . "\">"; }

// /git/ forms are plain urlencoded posts; PHP normally parses them into $_POST, but fall back to
// reading the body ourselves in case enable_post_data_reading is off for this location
function form_post()
{
	if ($_POST) return $_POST;
	if (stripos($_SERVER["CONTENT_TYPE"] ?? "", "application/x-www-form-urlencoded") !== 0) return [];
	if ((int)($_SERVER["CONTENT_LENGTH"] ?? 0) > 65536) page_error(413, "Too large", "Form submission too large.");
	parse_str((string)stream_get_contents(fopen("php://input", "rb"), 65536), $fields);
	return array_map(fn($v) => is_string($v) ? trim($v) : "", $fields);
}

function link_tree($repo, $ref, $path, $label, $kind = "tree")
{
	$url = "/git/" . rawurlencode($repo) . "/$kind/" . rawurlencode($ref);
	if ($path !== "") $url .= "/" . implode("/", array_map("rawurlencode", explode("/", $path)));
	return "<a href=\"" . h($url) . "\">" . h($label) . "</a>";
}

function tree_table($repo, $ref, $path, array $entries)
{
	echo "<table>\n<tr><th>Name</th><th>Type</th></tr>\n";
	if ($path !== "")
	{
		$parent = str_contains($path, "/") ? substr($path, 0, strrpos($path, "/")) : "";
		echo "<tr><td>", link_tree($repo, $ref, $parent, ".."), "</td><td>parent directory</td></tr>\n";
	}
	foreach ($entries as [$mode, $type, $name])
	{
		$full = $path === "" ? $name : "$path/$name";
		if ($type === "tree") echo "<tr><td>", link_tree($repo, $ref, $full, "$name/"), "</td><td>directory</td></tr>\n";
		else if ($type === "blob") echo "<tr><td>", link_tree($repo, $ref, $full, $name, "blob"), "</td><td>", $mode === "120000" ? "symlink" : "file", "</td></tr>\n";
		else echo "<tr><td>", h($name), "</td><td>submodule</td></tr>\n";
	}
	echo "</table>\n";
}

function auth_help()
{
	echo "<h2>Cloning and pushing</h2>\n";
	echo "<p>Public repositories can be cloned by anyone. Private repositories need a Polyback account; pushing needs an administrator account.</p>\n";
	echo "<p>git asks for a username and password: use your Polyback username, and either your Polyback password (accounts without two-factor authentication) or a git token from <a href=\"/git/\">this page</a> (required if your account has 2FA, which includes all administrators).</p>\n";
	echo "<p><b>Logins are only accepted over HTTPS</b>, because git sends them with HTTP Basic authentication, which is readable by anyone on the network over plain HTTP. Plain HTTP only works for public repositories (and from the server itself).</p>\n";
}

/* ---------- POST actions (repo management and tokens) ---------- */

function handle_post()
{
	$post = form_post();
	if (!SESSION) page_error(403, "Not logged in", "You need to log in first.");
	if (!hash_equals((string)SESSION["csrfToken"], (string)($post["csrf"] ?? ""))) page_error(403, "Invalid request", "The form expired or did not come from this site. Go back, reload and try again.");

	$action = $post["action"] ?? "";

	if ($action === "token-new")
	{
		$token = bin2hex(random_bytes(32));
		$dir = GIT_ROOT . "/.tokens";
		if (!is_dir($dir) && !@mkdir($dir, 0700, true)) page_error(500, "Error", "Could not create the token store.");
		if (@file_put_contents(git_token_file(SESSION["user"]["id"]), hash("sha256", $token), LOCK_EX) === false) page_error(500, "Error", "Could not save the token.");
		@chmod(git_token_file(SESSION["user"]["id"]), 0600);

		page_start("Your new git token");
		echo "<h1>Your new git token</h1>\n";
		echo "<p>Copy it now; it will not be shown again. Generating another token replaces this one.</p>\n";
		echo "<p>Username: <code>", h(SESSION["user"]["username"]), "</code></p>\n";
		echo "<p>Token (use it as the password): <code>", h($token), "</code></p>\n";
		echo "<p>To keep git from asking every time: <code>git config --global credential.helper store</code> (stores it in plain text in ~/.git-credentials) or use your system's credential manager.</p>\n";
		echo "<p><a href=\"/git/\">Back to repositories</a></p>\n";
		page_end();
	}

	if ($action === "token-revoke")
	{
		@unlink(git_token_file(SESSION["user"]["id"]));
		redirect("/git/");
	}

	if (!git_session_admin()) page_error(403, "Forbidden", "Only administrators (with 2FA enabled) can manage repositories.");

	$name = $post["name"] ?? "";
	if (!git_valid_name($name)) page_error(400, "Invalid name", "Repository names are 1-64 characters of A-Z a-z 0-9 . _ - (not starting with a dot or dash, not ending in .git).");
	$dir = git_repo_dir($name);

	if ($action === "create")
	{
		if (file_exists($dir)) page_error(409, "Already exists", "A repository with that name already exists.");
		$error = git_create_repo($name, $post["visibility"] ?? "private", (int) SESSION["user"]["id"], "the admin page");
		if ($error !== null) page_error(500, "Error", $error);
		redirect("/git/" . rawurlencode($name));
	}

	if (!git_repo_exists($name)) page_not_found();

	if ($action === "visibility")
	{
		$visibility = $post["visibility"] ?? "";
		if (!isset(GIT_VISIBILITIES[$visibility])) page_error(400, "Invalid request", "Visibility must be public, private or admin only.");
		file_put_contents("$dir/" . GIT_VISIBILITY_FILE, "$visibility\n", LOCK_EX);
		Users::LogStaffAction("[ Git ] Made repository $name " . GIT_VISIBILITIES[$visibility]);
		redirect("/git/" . rawurlencode($name));
	}

	if ($action === "delete")
	{
		if (!git_session_superadmin()) page_error(403, "Not allowed", "Only super admins can delete repositories.");
		if (($post["confirm"] ?? "") !== $name) page_error(400, "Not deleted", "Type the repository name exactly to confirm deletion.");
		if (!git_rmtree($dir)) page_error(500, "Error", "Could not fully delete the repository.");
		Users::LogStaffAction("[ Git ] Deleted repository $name");
		redirect("/git/");
	}

	page_error(400, "Invalid request", "Unknown action.");
}

/* ---------- pages ---------- */

function page_index()
{
	page_start("Git repositories");
	echo "<h1>Git repositories</h1>\n";

	$repos = array_values(array_filter(git_list_repos(), fn($r) => git_can_view($r)));
	if (!$repos) echo "<p>No repositories", SESSION ? "" : " visible to you", " yet.</p>\n";
	else
	{
		echo "<table>\n<tr><th>Name</th><th>Visibility</th><th>Last commit</th><th>Clone URL</th></tr>\n";
		foreach ($repos as $repo)
		{
			$date = git_last_commit_date($repo);
			echo "<tr><td><a href=\"/git/", h(rawurlencode($repo)), "\">", h($repo), "</a></td><td>", h(GIT_VISIBILITIES[git_repo_visibility($repo)]),
				"</td><td>", $date === "" ? "empty" : h($date), "</td><td><code>", h(git_clone_url($repo)), "</code></td></tr>\n";
		}
		echo "</table>\n";
	}

	auth_help();

	if (SESSION)
	{
		$hasToken = is_file(git_token_file(SESSION["user"]["id"]));
		echo "<h2>Git token</h2>\n";
		echo "<p>", $hasToken ? "You have a git token." : "You have no git token.", " A token works as your git password; it can't be used to log in to the website.</p>\n";
		echo "<form method=\"post\" action=\"/git/\">", csrf_field(), "<input type=\"hidden\" name=\"action\" value=\"token-new\"><button type=\"submit\">", $hasToken ? "Replace my token" : "Generate a token", "</button></form>\n";
		if ($hasToken) echo "<form method=\"post\" action=\"/git/\">", csrf_field(), "<input type=\"hidden\" name=\"action\" value=\"token-revoke\"><button type=\"submit\">Revoke my token</button></form>\n";
	}

	if (git_session_admin())
	{
		echo "<h2>Create a repository</h2>\n";
		echo "<form method=\"post\" action=\"/git/\">", csrf_field(), "<input type=\"hidden\" name=\"action\" value=\"create\">\n";
		echo "<p><label>Name: <input type=\"text\" name=\"name\" required maxlength=\"64\" pattern=\"[A-Za-z0-9_][A-Za-z0-9._\-]{0,63}\"></label></p>\n";
		echo "<fieldset><legend>Visibility</legend>\n";
		echo "<label><input type=\"radio\" name=\"visibility\" value=\"public\"> Public: anyone can clone and browse</label><br>\n";
		echo "<label><input type=\"radio\" name=\"visibility\" value=\"private\" checked> Private: logged-in users only</label><br>\n";
		echo "<label><input type=\"radio\" name=\"visibility\" value=\"admin\"> Admin only: administrators only</label>\n</fieldset>\n";
		echo "<p><button type=\"submit\">Create</button></p>\n</form>\n";
	}

	page_end();
}

function page_repo($repo)
{
	if (!git_can_view($repo)) page_not_found();

	$visibility = git_repo_visibility($repo);
	$branches = git_branches($repo);
	$default = git_default_branch($repo, $branches);

	page_start("$repo - Git");
	echo "<h1>", h($repo), "</h1>\n";
	echo "<p>", git_visibility_text($visibility), " Only administrators can push.</p>\n";
	echo "<p>Clone: <code>git clone ", h(git_clone_url($repo)), "</code></p>\n";

	if (!$branches)
	{
		echo "<p>This repository is empty. Push to it with:</p>\n<pre>git remote add polyback ", h(git_clone_url($repo)), "\ngit push polyback main</pre>\n";
	}
	else
	{
		echo "<h2>Branches</h2>\n<ul>\n";
		foreach ($branches as $branch => $date)
			echo "<li>", link_tree($repo, $branch, "", $branch), $branch === $default ? " (default)" : "", " - ", h($date), "</li>\n";
		echo "</ul>\n";

		echo "<h2>Latest commits on ", h($default), "</h2>\n";
		[, $log] = git_run(["log", "-n", "20", "--format=%H%x1f%an%x1f%aI%x1f%s%x1e", "--end-of-options", "refs/heads/$default", "--"], $repo);
		echo "<table>\n<tr><th>Commit</th><th>Author</th><th>Date</th><th>Message</th></tr>\n";
		foreach (explode("\x1e", $log) as $record)
		{
			$fields = explode("\x1f", trim($record));
			if (count($fields) < 4) continue;
			echo "<tr><td>", link_tree($repo, $fields[0], "", substr($fields[0], 0, 10)), "</td><td>", h($fields[1]), "</td><td>", h($fields[2]), "</td><td>", h($fields[3]), "</td></tr>\n";
		}
		echo "</table>\n";

		echo "<h2>Files</h2>\n";
		$entries = git_ls_tree($repo, "refs/heads/$default", "");
		if ($entries !== false) tree_table($repo, $default, "", $entries);
	}

	if (git_session_admin())
	{
		echo "<h2>Administration</h2>\n";
		echo "<p>Visibility: ", h(GIT_VISIBILITIES[$visibility]), "</p>\n";
		foreach (GIT_VISIBILITIES as $value => $label)
		{
			if ($value === $visibility) continue;
			echo "<form method=\"post\" action=\"/git/\">", csrf_field(), "<input type=\"hidden\" name=\"action\" value=\"visibility\"><input type=\"hidden\" name=\"name\" value=\"", h($repo), "\">",
				"<input type=\"hidden\" name=\"visibility\" value=\"", h($value), "\"><button type=\"submit\">Make ", h(strtolower($label)), "</button></form>\n";
		}
		if (git_session_superadmin())
		echo "<form method=\"post\" action=\"/git/\">", csrf_field(), "<input type=\"hidden\" name=\"action\" value=\"delete\"><input type=\"hidden\" name=\"name\" value=\"", h($repo), "\">",
			"<p><label>Type <code>", h($repo), "</code> to confirm: <input type=\"text\" name=\"confirm\" required></label> <button type=\"submit\">Delete repository</button></p></form>\n";
	}

	page_end();
}

function page_tree_or_blob($repo, $kind, $ref, array $pathSegments)
{
	if (!git_can_view($repo)) page_not_found();
	$path = git_valid_path($pathSegments);
	$commit = $path === false ? false : git_resolve_commit($repo, $ref);
	if ($commit === false) page_not_found();

	$type = git_object_type($repo, $commit, $path);
	if ($kind === "tree" && $type !== "tree") page_not_found();
	if ($kind === "blob" && $type !== "blob") page_not_found();

	page_start(($path === "" ? $repo : "$path - $repo") . " - Git");
	echo "<h1><a href=\"/git/", h(rawurlencode($repo)), "\">", h($repo), "</a> / ", h($ref), $path === "" ? "" : " / " . h($path), "</h1>\n";

	if ($kind === "tree")
	{
		$entries = git_ls_tree($repo, $commit, $path);
		tree_table($repo, $ref, $path, $entries ?: []);
		page_end();
	}

	[, $size] = git_run(["cat-file", "-s", "--end-of-options", "$commit:$path"], $repo);
	$size = (int)trim($size);
	echo "<p>", number_format($size), " bytes";
	if (str_contains($path, "/")) echo " | ", link_tree($repo, $ref, substr($path, 0, strrpos($path, "/")), "parent directory");
	else echo " | ", link_tree($repo, $ref, "", "root directory");
	echo "</p>\n";

	if ($size > GIT_MAX_BLOB) { echo "<p>File too large to display.</p>\n"; page_end(); }
	[, $content] = git_run(["cat-file", "blob", "--end-of-options", "$commit:$path"], $repo, GIT_MAX_BLOB);
	if (str_contains(substr($content, 0, 8000), "\0")) echo "<p>Binary file, not shown.</p>\n";
	else echo "<pre>", h($content), "</pre>\n";
	page_end();
}

/* ---------- routing ---------- */

$uriPath = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH) ?? "";
if (!preg_match('#^/git(/.*)?$#', $uriPath, $m)) page_not_found();
$segments = array_map("rawurldecode", explode("/", trim($m[1] ?? "", "/")));
if ($segments === [""]) $segments = [];

// git smart HTTP: /git/<repo>.git/<info/refs|git-upload-pack|git-receive-pack>
if ($segments && str_ends_with($segments[0], ".git"))
{
	$name = substr($segments[0], 0, -4);
	if (!git_valid_name($name)) git_plain_error(404, "Repository not found.");
	git_smart_http($name, implode("/", array_slice($segments, 1)));
}

if ($_SERVER["REQUEST_METHOD"] === "POST")
{
	if ($segments) page_error(405, "Method not allowed", "Forms post to /git/.");
	handle_post();
}

if ($_SERVER["REQUEST_METHOD"] !== "GET" && $_SERVER["REQUEST_METHOD"] !== "HEAD") page_error(405, "Method not allowed", "Only GET and POST are supported.");

if (!$segments) page_index();
if (!git_valid_name($segments[0])) page_not_found();
if (count($segments) === 1) page_repo($segments[0]);
if (count($segments) >= 3 && ($segments[1] === "tree" || $segments[1] === "blob"))
	page_tree_or_blob($segments[0], $segments[1], $segments[2], array_slice($segments, 3));
page_not_found();