all repos — cgit @ 073a8bb3963d53630826ee43f6feefb5a9660dc0

a hyperfast web frontend for git written in c

cgit.c (view raw)

   1/* cgit.c: cgi for the git scm
   2 *
   3 * Copyright (C) 2006-2014 cgit Development Team <cgit@lists.zx2c4.com>
   4 *
   5 * Licensed under GNU General Public License v2
   6 *   (see COPYING for full license text)
   7 */
   8
   9#include "cgit.h"
  10#include "cache.h"
  11#include "cmd.h"
  12#include "configfile.h"
  13#include "html.h"
  14#include "ui-shared.h"
  15#include "ui-stats.h"
  16#include "ui-blob.h"
  17#include "ui-summary.h"
  18#include "scan-tree.h"
  19
  20const char *cgit_version = CGIT_VERSION;
  21
  22static void add_mimetype(const char *name, const char *value)
  23{
  24	struct string_list_item *item;
  25
  26	item = string_list_insert(&ctx.cfg.mimetypes, xstrdup(name));
  27	item->util = xstrdup(value);
  28}
  29
  30static void process_cached_repolist(const char *path);
  31
  32static void repo_config(struct cgit_repo *repo, const char *name, const char *value)
  33{
  34	struct string_list_item *item;
  35
  36	if (!strcmp(name, "name"))
  37		repo->name = xstrdup(value);
  38	else if (!strcmp(name, "clone-url"))
  39		repo->clone_url = xstrdup(value);
  40	else if (!strcmp(name, "desc"))
  41		repo->desc = xstrdup(value);
  42	else if (!strcmp(name, "owner"))
  43		repo->owner = xstrdup(value);
  44	else if (!strcmp(name, "homepage"))
  45		repo->homepage = xstrdup(value);
  46	else if (!strcmp(name, "defbranch"))
  47		repo->defbranch = xstrdup(value);
  48	else if (!strcmp(name, "snapshots"))
  49		repo->snapshots = ctx.cfg.snapshots & cgit_parse_snapshots_mask(value);
  50	else if (!strcmp(name, "enable-commit-graph"))
  51		repo->enable_commit_graph = atoi(value);
  52	else if (!strcmp(name, "enable-log-filecount"))
  53		repo->enable_log_filecount = atoi(value);
  54	else if (!strcmp(name, "enable-log-linecount"))
  55		repo->enable_log_linecount = atoi(value);
  56	else if (!strcmp(name, "enable-remote-branches"))
  57		repo->enable_remote_branches = atoi(value);
  58	else if (!strcmp(name, "enable-subject-links"))
  59		repo->enable_subject_links = atoi(value);
  60	else if (!strcmp(name, "enable-html-serving"))
  61		repo->enable_html_serving = atoi(value);
  62	else if (!strcmp(name, "branch-sort")) {
  63		if (!strcmp(value, "age"))
  64			repo->branch_sort = 1;
  65		if (!strcmp(value, "name"))
  66			repo->branch_sort = 0;
  67	} else if (!strcmp(name, "commit-sort")) {
  68		if (!strcmp(value, "date"))
  69			repo->commit_sort = 1;
  70		if (!strcmp(value, "topo"))
  71			repo->commit_sort = 2;
  72	} else if (!strcmp(name, "max-stats"))
  73		repo->max_stats = cgit_find_stats_period(value, NULL);
  74	else if (!strcmp(name, "module-link"))
  75		repo->module_link= xstrdup(value);
  76	else if (starts_with(name, "module-link.")) {
  77		item = string_list_append(&repo->submodules, xstrdup(name + 12));
  78		item->util = xstrdup(value);
  79	} else if (!strcmp(name, "section"))
  80		repo->section = xstrdup(value);
  81	else if (!strcmp(name, "readme") && value != NULL) {
  82		if (repo->readme.items == ctx.cfg.readme.items)
  83			memset(&repo->readme, 0, sizeof(repo->readme));
  84		string_list_append(&repo->readme, xstrdup(value));
  85	} else if (!strcmp(name, "logo") && value != NULL)
  86		repo->logo = xstrdup(value);
  87	else if (!strcmp(name, "logo-link") && value != NULL)
  88		repo->logo_link = xstrdup(value);
  89	else if (!strcmp(name, "hide"))
  90		repo->hide = atoi(value);
  91	else if (!strcmp(name, "ignore"))
  92		repo->ignore = atoi(value);
  93	else if (ctx.cfg.enable_filter_overrides) {
  94		if (!strcmp(name, "about-filter"))
  95			repo->about_filter = cgit_new_filter(value, ABOUT);
  96		else if (!strcmp(name, "commit-filter"))
  97			repo->commit_filter = cgit_new_filter(value, COMMIT);
  98		else if (!strcmp(name, "source-filter"))
  99			repo->source_filter = cgit_new_filter(value, SOURCE);
 100		else if (!strcmp(name, "email-filter"))
 101			repo->email_filter = cgit_new_filter(value, EMAIL);
 102		else if (!strcmp(name, "owner-filter"))
 103			repo->owner_filter = cgit_new_filter(value, OWNER);
 104	}
 105}
 106
 107static void config_cb(const char *name, const char *value)
 108{
 109	if (!strcmp(name, "section") || !strcmp(name, "repo.group"))
 110		ctx.cfg.section = xstrdup(value);
 111	else if (!strcmp(name, "repo.url"))
 112		ctx.repo = cgit_add_repo(value);
 113	else if (ctx.repo && !strcmp(name, "repo.path"))
 114		ctx.repo->path = trim_end(value, '/');
 115	else if (ctx.repo && starts_with(name, "repo."))
 116		repo_config(ctx.repo, name + 5, value);
 117	else if (!strcmp(name, "readme"))
 118		string_list_append(&ctx.cfg.readme, xstrdup(value));
 119	else if (!strcmp(name, "root-title"))
 120		ctx.cfg.root_title = xstrdup(value);
 121	else if (!strcmp(name, "root-desc"))
 122		ctx.cfg.root_desc = xstrdup(value);
 123	else if (!strcmp(name, "root-readme"))
 124		ctx.cfg.root_readme = xstrdup(value);
 125	else if (!strcmp(name, "css"))
 126		ctx.cfg.css = xstrdup(value);
 127	else if (!strcmp(name, "favicon"))
 128		ctx.cfg.favicon = xstrdup(value);
 129	else if (!strcmp(name, "footer"))
 130		ctx.cfg.footer = xstrdup(value);
 131	else if (!strcmp(name, "head-include"))
 132		ctx.cfg.head_include = xstrdup(value);
 133	else if (!strcmp(name, "header"))
 134		ctx.cfg.header = xstrdup(value);
 135	else if (!strcmp(name, "logo"))
 136		ctx.cfg.logo = xstrdup(value);
 137	else if (!strcmp(name, "index-header"))
 138		ctx.cfg.index_header = xstrdup(value);
 139	else if (!strcmp(name, "index-info"))
 140		ctx.cfg.index_info = xstrdup(value);
 141	else if (!strcmp(name, "logo-link"))
 142		ctx.cfg.logo_link = xstrdup(value);
 143	else if (!strcmp(name, "module-link"))
 144		ctx.cfg.module_link = xstrdup(value);
 145	else if (!strcmp(name, "strict-export"))
 146		ctx.cfg.strict_export = xstrdup(value);
 147	else if (!strcmp(name, "virtual-root")) {
 148		ctx.cfg.virtual_root = ensure_end(value, '/');
 149	} else if (!strcmp(name, "nocache"))
 150		ctx.cfg.nocache = atoi(value);
 151	else if (!strcmp(name, "noplainemail"))
 152		ctx.cfg.noplainemail = atoi(value);
 153	else if (!strcmp(name, "noheader"))
 154		ctx.cfg.noheader = atoi(value);
 155	else if (!strcmp(name, "snapshots"))
 156		ctx.cfg.snapshots = cgit_parse_snapshots_mask(value);
 157	else if (!strcmp(name, "enable-filter-overrides"))
 158		ctx.cfg.enable_filter_overrides = atoi(value);
 159	else if (!strcmp(name, "enable-follow-links"))
 160		ctx.cfg.enable_follow_links = atoi(value);
 161	else if (!strcmp(name, "enable-http-clone"))
 162		ctx.cfg.enable_http_clone = atoi(value);
 163	else if (!strcmp(name, "enable-index-links"))
 164		ctx.cfg.enable_index_links = atoi(value);
 165	else if (!strcmp(name, "enable-index-owner"))
 166		ctx.cfg.enable_index_owner = atoi(value);
 167	else if (!strcmp(name, "enable-commit-graph"))
 168		ctx.cfg.enable_commit_graph = atoi(value);
 169	else if (!strcmp(name, "enable-log-filecount"))
 170		ctx.cfg.enable_log_filecount = atoi(value);
 171	else if (!strcmp(name, "enable-log-linecount"))
 172		ctx.cfg.enable_log_linecount = atoi(value);
 173	else if (!strcmp(name, "enable-remote-branches"))
 174		ctx.cfg.enable_remote_branches = atoi(value);
 175	else if (!strcmp(name, "enable-subject-links"))
 176		ctx.cfg.enable_subject_links = atoi(value);
 177	else if (!strcmp(name, "enable-html-serving"))
 178		ctx.cfg.enable_html_serving = atoi(value);
 179	else if (!strcmp(name, "enable-tree-linenumbers"))
 180		ctx.cfg.enable_tree_linenumbers = atoi(value);
 181	else if (!strcmp(name, "enable-git-config"))
 182		ctx.cfg.enable_git_config = atoi(value);
 183	else if (!strcmp(name, "max-stats"))
 184		ctx.cfg.max_stats = cgit_find_stats_period(value, NULL);
 185	else if (!strcmp(name, "cache-size"))
 186		ctx.cfg.cache_size = atoi(value);
 187	else if (!strcmp(name, "cache-root"))
 188		ctx.cfg.cache_root = xstrdup(expand_macros(value));
 189	else if (!strcmp(name, "cache-root-ttl"))
 190		ctx.cfg.cache_root_ttl = atoi(value);
 191	else if (!strcmp(name, "cache-repo-ttl"))
 192		ctx.cfg.cache_repo_ttl = atoi(value);
 193	else if (!strcmp(name, "cache-scanrc-ttl"))
 194		ctx.cfg.cache_scanrc_ttl = atoi(value);
 195	else if (!strcmp(name, "cache-static-ttl"))
 196		ctx.cfg.cache_static_ttl = atoi(value);
 197	else if (!strcmp(name, "cache-dynamic-ttl"))
 198		ctx.cfg.cache_dynamic_ttl = atoi(value);
 199	else if (!strcmp(name, "cache-about-ttl"))
 200		ctx.cfg.cache_about_ttl = atoi(value);
 201	else if (!strcmp(name, "cache-snapshot-ttl"))
 202		ctx.cfg.cache_snapshot_ttl = atoi(value);
 203	else if (!strcmp(name, "case-sensitive-sort"))
 204		ctx.cfg.case_sensitive_sort = atoi(value);
 205	else if (!strcmp(name, "about-filter"))
 206		ctx.cfg.about_filter = cgit_new_filter(value, ABOUT);
 207	else if (!strcmp(name, "commit-filter"))
 208		ctx.cfg.commit_filter = cgit_new_filter(value, COMMIT);
 209	else if (!strcmp(name, "email-filter"))
 210		ctx.cfg.email_filter = cgit_new_filter(value, EMAIL);
 211	else if (!strcmp(name, "owner-filter"))
 212		ctx.cfg.owner_filter = cgit_new_filter(value, OWNER);
 213	else if (!strcmp(name, "auth-filter"))
 214		ctx.cfg.auth_filter = cgit_new_filter(value, AUTH);
 215	else if (!strcmp(name, "embedded"))
 216		ctx.cfg.embedded = atoi(value);
 217	else if (!strcmp(name, "max-atom-items"))
 218		ctx.cfg.max_atom_items = atoi(value);
 219	else if (!strcmp(name, "max-message-length"))
 220		ctx.cfg.max_msg_len = atoi(value);
 221	else if (!strcmp(name, "max-repodesc-length"))
 222		ctx.cfg.max_repodesc_len = atoi(value);
 223	else if (!strcmp(name, "max-blob-size"))
 224		ctx.cfg.max_blob_size = atoi(value);
 225	else if (!strcmp(name, "max-repo-count"))
 226		ctx.cfg.max_repo_count = atoi(value);
 227	else if (!strcmp(name, "max-commit-count"))
 228		ctx.cfg.max_commit_count = atoi(value);
 229	else if (!strcmp(name, "project-list"))
 230		ctx.cfg.project_list = xstrdup(expand_macros(value));
 231	else if (!strcmp(name, "scan-path"))
 232		if (!ctx.cfg.nocache && ctx.cfg.cache_size)
 233			process_cached_repolist(expand_macros(value));
 234		else if (ctx.cfg.project_list)
 235			scan_projects(expand_macros(value),
 236				      ctx.cfg.project_list, repo_config);
 237		else
 238			scan_tree(expand_macros(value), repo_config);
 239	else if (!strcmp(name, "scan-hidden-path"))
 240		ctx.cfg.scan_hidden_path = atoi(value);
 241	else if (!strcmp(name, "section-from-path"))
 242		ctx.cfg.section_from_path = atoi(value);
 243	else if (!strcmp(name, "repository-sort"))
 244		ctx.cfg.repository_sort = xstrdup(value);
 245	else if (!strcmp(name, "section-sort"))
 246		ctx.cfg.section_sort = atoi(value);
 247	else if (!strcmp(name, "source-filter"))
 248		ctx.cfg.source_filter = cgit_new_filter(value, SOURCE);
 249	else if (!strcmp(name, "summary-log"))
 250		ctx.cfg.summary_log = atoi(value);
 251	else if (!strcmp(name, "summary-branches"))
 252		ctx.cfg.summary_branches = atoi(value);
 253	else if (!strcmp(name, "summary-tags"))
 254		ctx.cfg.summary_tags = atoi(value);
 255	else if (!strcmp(name, "side-by-side-diffs"))
 256		ctx.cfg.difftype = atoi(value) ? DIFF_SSDIFF : DIFF_UNIFIED;
 257	else if (!strcmp(name, "agefile"))
 258		ctx.cfg.agefile = xstrdup(value);
 259	else if (!strcmp(name, "mimetype-file"))
 260		ctx.cfg.mimetype_file = xstrdup(value);
 261	else if (!strcmp(name, "renamelimit"))
 262		ctx.cfg.renamelimit = atoi(value);
 263	else if (!strcmp(name, "remove-suffix"))
 264		ctx.cfg.remove_suffix = atoi(value);
 265	else if (!strcmp(name, "robots"))
 266		ctx.cfg.robots = xstrdup(value);
 267	else if (!strcmp(name, "clone-prefix"))
 268		ctx.cfg.clone_prefix = xstrdup(value);
 269	else if (!strcmp(name, "clone-url"))
 270		ctx.cfg.clone_url = xstrdup(value);
 271	else if (!strcmp(name, "local-time"))
 272		ctx.cfg.local_time = atoi(value);
 273	else if (!strcmp(name, "commit-sort")) {
 274		if (!strcmp(value, "date"))
 275			ctx.cfg.commit_sort = 1;
 276		if (!strcmp(value, "topo"))
 277			ctx.cfg.commit_sort = 2;
 278	} else if (!strcmp(name, "branch-sort")) {
 279		if (!strcmp(value, "age"))
 280			ctx.cfg.branch_sort = 1;
 281		if (!strcmp(value, "name"))
 282			ctx.cfg.branch_sort = 0;
 283	} else if (starts_with(name, "mimetype."))
 284		add_mimetype(name + 9, value);
 285	else if (!strcmp(name, "include"))
 286		parse_configfile(expand_macros(value), config_cb);
 287}
 288
 289static void querystring_cb(const char *name, const char *value)
 290{
 291	if (!value)
 292		value = "";
 293
 294	if (!strcmp(name,"r")) {
 295		ctx.qry.repo = xstrdup(value);
 296		ctx.repo = cgit_get_repoinfo(value);
 297	} else if (!strcmp(name, "p")) {
 298		ctx.qry.page = xstrdup(value);
 299	} else if (!strcmp(name, "url")) {
 300		if (*value == '/')
 301			value++;
 302		ctx.qry.url = xstrdup(value);
 303		cgit_parse_url(value);
 304	} else if (!strcmp(name, "qt")) {
 305		ctx.qry.grep = xstrdup(value);
 306	} else if (!strcmp(name, "q")) {
 307		ctx.qry.search = xstrdup(value);
 308	} else if (!strcmp(name, "h")) {
 309		ctx.qry.head = xstrdup(value);
 310		ctx.qry.has_symref = 1;
 311	} else if (!strcmp(name, "id")) {
 312		ctx.qry.sha1 = xstrdup(value);
 313		ctx.qry.has_sha1 = 1;
 314	} else if (!strcmp(name, "id2")) {
 315		ctx.qry.sha2 = xstrdup(value);
 316		ctx.qry.has_sha1 = 1;
 317	} else if (!strcmp(name, "ofs")) {
 318		ctx.qry.ofs = atoi(value);
 319	} else if (!strcmp(name, "path")) {
 320		ctx.qry.path = trim_end(value, '/');
 321	} else if (!strcmp(name, "name")) {
 322		ctx.qry.name = xstrdup(value);
 323	} else if (!strcmp(name, "s")) {
 324		ctx.qry.sort = xstrdup(value);
 325	} else if (!strcmp(name, "showmsg")) {
 326		ctx.qry.showmsg = atoi(value);
 327	} else if (!strcmp(name, "period")) {
 328		ctx.qry.period = xstrdup(value);
 329	} else if (!strcmp(name, "dt")) {
 330		ctx.qry.difftype = atoi(value);
 331		ctx.qry.has_difftype = 1;
 332	} else if (!strcmp(name, "ss")) {
 333		/* No longer generated, but there may be links out there. */
 334		ctx.qry.difftype = atoi(value) ? DIFF_SSDIFF : DIFF_UNIFIED;
 335		ctx.qry.has_difftype = 1;
 336	} else if (!strcmp(name, "all")) {
 337		ctx.qry.show_all = atoi(value);
 338	} else if (!strcmp(name, "context")) {
 339		ctx.qry.context = atoi(value);
 340	} else if (!strcmp(name, "ignorews")) {
 341		ctx.qry.ignorews = atoi(value);
 342	} else if (!strcmp(name, "follow")) {
 343		ctx.qry.follow = atoi(value);
 344	}
 345}
 346
 347static void prepare_context(void)
 348{
 349	memset(&ctx, 0, sizeof(ctx));
 350	ctx.cfg.agefile = "info/web/last-modified";
 351	ctx.cfg.nocache = 0;
 352	ctx.cfg.cache_size = 0;
 353	ctx.cfg.cache_max_create_time = 5;
 354	ctx.cfg.cache_root = CGIT_CACHE_ROOT;
 355	ctx.cfg.cache_about_ttl = 15;
 356	ctx.cfg.cache_snapshot_ttl = 5;
 357	ctx.cfg.cache_repo_ttl = 5;
 358	ctx.cfg.cache_root_ttl = 5;
 359	ctx.cfg.cache_scanrc_ttl = 15;
 360	ctx.cfg.cache_dynamic_ttl = 5;
 361	ctx.cfg.cache_static_ttl = -1;
 362	ctx.cfg.case_sensitive_sort = 1;
 363	ctx.cfg.branch_sort = 0;
 364	ctx.cfg.commit_sort = 0;
 365	ctx.cfg.css = "/cgit.css";
 366	ctx.cfg.logo = "/cgit.png";
 367	ctx.cfg.favicon = "/favicon.ico";
 368	ctx.cfg.local_time = 0;
 369	ctx.cfg.enable_http_clone = 1;
 370	ctx.cfg.enable_index_owner = 1;
 371	ctx.cfg.enable_tree_linenumbers = 1;
 372	ctx.cfg.enable_git_config = 0;
 373	ctx.cfg.max_repo_count = 50;
 374	ctx.cfg.max_commit_count = 50;
 375	ctx.cfg.max_lock_attempts = 5;
 376	ctx.cfg.max_msg_len = 80;
 377	ctx.cfg.max_repodesc_len = 80;
 378	ctx.cfg.max_blob_size = 0;
 379	ctx.cfg.max_stats = 0;
 380	ctx.cfg.project_list = NULL;
 381	ctx.cfg.renamelimit = -1;
 382	ctx.cfg.remove_suffix = 0;
 383	ctx.cfg.robots = "index, nofollow";
 384	ctx.cfg.root_title = "Git repository browser";
 385	ctx.cfg.root_desc = "a fast webinterface for the git dscm";
 386	ctx.cfg.scan_hidden_path = 0;
 387	ctx.cfg.script_name = CGIT_SCRIPT_NAME;
 388	ctx.cfg.section = "";
 389	ctx.cfg.repository_sort = "name";
 390	ctx.cfg.section_sort = 1;
 391	ctx.cfg.summary_branches = 10;
 392	ctx.cfg.summary_log = 10;
 393	ctx.cfg.summary_tags = 10;
 394	ctx.cfg.max_atom_items = 10;
 395	ctx.cfg.difftype = DIFF_UNIFIED;
 396	ctx.env.cgit_config = getenv("CGIT_CONFIG");
 397	ctx.env.http_host = getenv("HTTP_HOST");
 398	ctx.env.https = getenv("HTTPS");
 399	ctx.env.no_http = getenv("NO_HTTP");
 400	ctx.env.path_info = getenv("PATH_INFO");
 401	ctx.env.query_string = getenv("QUERY_STRING");
 402	ctx.env.request_method = getenv("REQUEST_METHOD");
 403	ctx.env.script_name = getenv("SCRIPT_NAME");
 404	ctx.env.server_name = getenv("SERVER_NAME");
 405	ctx.env.server_port = getenv("SERVER_PORT");
 406	ctx.env.http_cookie = getenv("HTTP_COOKIE");
 407	ctx.env.http_referer = getenv("HTTP_REFERER");
 408	ctx.env.content_length = getenv("CONTENT_LENGTH") ? strtoul(getenv("CONTENT_LENGTH"), NULL, 10) : 0;
 409	ctx.env.authenticated = 0;
 410	ctx.page.mimetype = "text/html";
 411	ctx.page.charset = PAGE_ENCODING;
 412	ctx.page.filename = NULL;
 413	ctx.page.size = 0;
 414	ctx.page.modified = time(NULL);
 415	ctx.page.expires = ctx.page.modified;
 416	ctx.page.etag = NULL;
 417	memset(&ctx.cfg.mimetypes, 0, sizeof(struct string_list));
 418	if (ctx.env.script_name)
 419		ctx.cfg.script_name = xstrdup(ctx.env.script_name);
 420	if (ctx.env.query_string)
 421		ctx.qry.raw = xstrdup(ctx.env.query_string);
 422	if (!ctx.env.cgit_config)
 423		ctx.env.cgit_config = CGIT_CONFIG;
 424}
 425
 426struct refmatch {
 427	char *req_ref;
 428	char *first_ref;
 429	int match;
 430};
 431
 432static int find_current_ref(const char *refname, const struct object_id *oid,
 433			    int flags, void *cb_data)
 434{
 435	struct refmatch *info;
 436
 437	info = (struct refmatch *)cb_data;
 438	if (!strcmp(refname, info->req_ref))
 439		info->match = 1;
 440	if (!info->first_ref)
 441		info->first_ref = xstrdup(refname);
 442	return info->match;
 443}
 444
 445static void free_refmatch_inner(struct refmatch *info)
 446{
 447	if (info->first_ref)
 448		free(info->first_ref);
 449}
 450
 451static char *find_default_branch(struct cgit_repo *repo)
 452{
 453	struct refmatch info;
 454	char *ref;
 455
 456	info.req_ref = repo->defbranch;
 457	info.first_ref = NULL;
 458	info.match = 0;
 459	for_each_branch_ref(find_current_ref, &info);
 460	if (info.match)
 461		ref = info.req_ref;
 462	else
 463		ref = info.first_ref;
 464	if (ref)
 465		ref = xstrdup(ref);
 466	free_refmatch_inner(&info);
 467
 468	return ref;
 469}
 470
 471static char *guess_defbranch(void)
 472{
 473	const char *ref;
 474	struct object_id oid;
 475
 476	ref = resolve_ref_unsafe("HEAD", 0, oid.hash, NULL);
 477	if (!ref || !starts_with(ref, "refs/heads/"))
 478		return "master";
 479	return xstrdup(ref + 11);
 480}
 481
 482/* The caller must free filename and ref after calling this. */
 483static inline void parse_readme(const char *readme, char **filename, char **ref, struct cgit_repo *repo)
 484{
 485	const char *colon;
 486
 487	*filename = NULL;
 488	*ref = NULL;
 489
 490	if (!readme || !readme[0])
 491		return;
 492
 493	/* Check if the readme is tracked in the git repo. */
 494	colon = strchr(readme, ':');
 495	if (colon && strlen(colon) > 1) {
 496		/* If it starts with a colon, we want to use
 497		 * the default branch */
 498		if (colon == readme && repo->defbranch)
 499			*ref = xstrdup(repo->defbranch);
 500		else
 501			*ref = xstrndup(readme, colon - readme);
 502		readme = colon + 1;
 503	}
 504
 505	/* Prepend repo path to relative readme path unless tracked. */
 506	if (!(*ref) && readme[0] != '/')
 507		*filename = fmtalloc("%s/%s", repo->path, readme);
 508	else
 509		*filename = xstrdup(readme);
 510}
 511static void choose_readme(struct cgit_repo *repo)
 512{
 513	int found;
 514	char *filename, *ref;
 515	struct string_list_item *entry;
 516
 517	if (!repo->readme.nr)
 518		return;
 519
 520	found = 0;
 521	for_each_string_list_item(entry, &repo->readme) {
 522		parse_readme(entry->string, &filename, &ref, repo);
 523		if (!filename) {
 524			free(filename);
 525			free(ref);
 526			continue;
 527		}
 528		if (ref) {
 529			if (cgit_ref_path_exists(filename, ref, 1)) {
 530				found = 1;
 531				break;
 532			}
 533		}
 534		else if (!access(filename, R_OK)) {
 535			found = 1;
 536			break;
 537		}
 538		free(filename);
 539		free(ref);
 540	}
 541	repo->readme.strdup_strings = 1;
 542	string_list_clear(&repo->readme, 0);
 543	repo->readme.strdup_strings = 0;
 544	if (found)
 545		string_list_append(&repo->readme, filename)->util = ref;
 546}
 547
 548static void print_no_repo_clone_urls(const char *url)
 549{
 550        html("<tr><td><a rel='vcs-git' href='");
 551        html_url_path(url);
 552        html("' title='");
 553        html_attr(ctx.repo->name);
 554        html(" Git repository'>");
 555        html_txt(url);
 556        html("</a></td></tr>\n");
 557}
 558
 559static int prepare_repo_cmd(void)
 560{
 561	struct object_id oid;
 562	int nongit = 0;
 563	int rc;
 564
 565	/* The path to the git repository. */
 566	setenv("GIT_DIR", ctx.repo->path, 1);
 567
 568	/* Do not look in /etc/ for gitconfig and gitattributes. */
 569	setenv("GIT_CONFIG_NOSYSTEM", "1", 1);
 570	setenv("GIT_ATTR_NOSYSTEM", "1", 1);
 571	unsetenv("HOME");
 572	unsetenv("XDG_CONFIG_HOME");
 573
 574	/* Setup the git directory and initialize the notes system. Both of these
 575	 * load local configuration from the git repository, so we do them both while
 576	 * the HOME variables are unset. */
 577	setup_git_directory_gently(&nongit);
 578	init_display_notes(NULL);
 579
 580	if (nongit) {
 581		const char *name = ctx.repo->name;
 582		rc = errno;
 583		ctx.page.title = fmtalloc("%s - %s", ctx.cfg.root_title,
 584						"config error");
 585		ctx.repo = NULL;
 586		cgit_print_http_headers();
 587		cgit_print_docstart();
 588		cgit_print_pageheader();
 589		cgit_print_error("Failed to open %s: %s", name,
 590				 rc ? strerror(rc) : "Not a valid git repository");
 591		cgit_print_docend();
 592		return 1;
 593	}
 594	ctx.page.title = fmtalloc("%s - %s", ctx.repo->name, ctx.repo->desc);
 595
 596	if (!ctx.repo->defbranch)
 597		ctx.repo->defbranch = guess_defbranch();
 598
 599	if (!ctx.qry.head) {
 600		ctx.qry.nohead = 1;
 601		ctx.qry.head = find_default_branch(ctx.repo);
 602	}
 603
 604	if (!ctx.qry.head) {
 605		cgit_print_http_headers();
 606		cgit_print_docstart();
 607		cgit_print_pageheader();
 608		cgit_print_error("Repository seems to be empty");
 609		if (!strcmp(ctx.qry.page, "summary")) {
 610			html("<table class='list'><tr class='nohover'><td>&nbsp;</td></tr><tr class='nohover'><th class='left'>Clone</th></tr>\n");
 611			cgit_prepare_repo_env(ctx.repo);
 612			cgit_add_clone_urls(print_no_repo_clone_urls);
 613			html("</table>\n");
 614		}
 615		cgit_print_docend();
 616		return 1;
 617	}
 618
 619	if (get_oid(ctx.qry.head, &oid)) {
 620		char *old_head = ctx.qry.head;
 621		ctx.qry.head = xstrdup(ctx.repo->defbranch);
 622		cgit_print_error_page(404, "Not found",
 623				"Invalid branch: %s", old_head);
 624		free(old_head);
 625		return 1;
 626	}
 627	string_list_sort(&ctx.repo->submodules);
 628	cgit_prepare_repo_env(ctx.repo);
 629	choose_readme(ctx.repo);
 630	return 0;
 631}
 632
 633static inline void open_auth_filter(const char *function)
 634{
 635	cgit_open_filter(ctx.cfg.auth_filter, function,
 636		ctx.env.http_cookie ? ctx.env.http_cookie : "",
 637		ctx.env.request_method ? ctx.env.request_method : "",
 638		ctx.env.query_string ? ctx.env.query_string : "",
 639		ctx.env.http_referer ? ctx.env.http_referer : "",
 640		ctx.env.path_info ? ctx.env.path_info : "",
 641		ctx.env.http_host ? ctx.env.http_host : "",
 642		ctx.env.https ? ctx.env.https : "",
 643		ctx.qry.repo ? ctx.qry.repo : "",
 644		ctx.qry.page ? ctx.qry.page : "",
 645		ctx.qry.url ? ctx.qry.url : "",
 646		cgit_loginurl());
 647}
 648
 649/* We intentionally keep this rather small, instead of looping and
 650 * feeding it to the filter a couple bytes at a time. This way, the
 651 * filter itself does not need to handle any denial of service or
 652 * buffer bloat issues. If this winds up being too small, people
 653 * will complain on the mailing list, and we'll increase it as needed. */
 654#define MAX_AUTHENTICATION_POST_BYTES 4096
 655/* The filter is expected to spit out "Status: " and all headers. */
 656static inline void authenticate_post(void)
 657{
 658	char buffer[MAX_AUTHENTICATION_POST_BYTES];
 659	unsigned int len;
 660
 661	open_auth_filter("authenticate-post");
 662	len = ctx.env.content_length;
 663	if (len > MAX_AUTHENTICATION_POST_BYTES)
 664		len = MAX_AUTHENTICATION_POST_BYTES;
 665	if (read(STDIN_FILENO, buffer, len) < 0)
 666		die_errno("Could not read POST from stdin");
 667	if (write(STDOUT_FILENO, buffer, len) < 0)
 668		die_errno("Could not write POST to stdout");
 669	cgit_close_filter(ctx.cfg.auth_filter);
 670	exit(0);
 671}
 672
 673static inline void authenticate_cookie(void)
 674{
 675	/* If we don't have an auth_filter, consider all cookies valid, and thus return early. */
 676	if (!ctx.cfg.auth_filter) {
 677		ctx.env.authenticated = 1;
 678		return;
 679	}
 680
 681	/* If we're having something POST'd to /login, we're authenticating POST,
 682	 * instead of the cookie, so call authenticate_post and bail out early.
 683	 * This pattern here should match /?p=login with POST. */
 684	if (ctx.env.request_method && ctx.qry.page && !ctx.repo && \
 685	    !strcmp(ctx.env.request_method, "POST") && !strcmp(ctx.qry.page, "login")) {
 686		authenticate_post();
 687		return;
 688	}
 689
 690	/* If we've made it this far, we're authenticating the cookie for real, so do that. */
 691	open_auth_filter("authenticate-cookie");
 692	ctx.env.authenticated = cgit_close_filter(ctx.cfg.auth_filter);
 693}
 694
 695static void process_request(void)
 696{
 697	struct cgit_cmd *cmd;
 698
 699	/* If we're not yet authenticated, no matter what page we're on,
 700	 * display the authentication body from the auth_filter. This should
 701	 * never be cached. */
 702	if (!ctx.env.authenticated) {
 703		ctx.page.title = "Authentication Required";
 704		cgit_print_http_headers();
 705		cgit_print_docstart();
 706		cgit_print_pageheader();
 707		open_auth_filter("body");
 708		cgit_close_filter(ctx.cfg.auth_filter);
 709		cgit_print_docend();
 710		return;
 711	}
 712
 713	cmd = cgit_get_cmd();
 714	if (!cmd) {
 715		ctx.page.title = "cgit error";
 716		cgit_print_error_page(404, "Not found", "Invalid request");
 717		return;
 718	}
 719
 720	if (!ctx.cfg.enable_http_clone && cmd->is_clone) {
 721		ctx.page.title = "cgit error";
 722		cgit_print_error_page(404, "Not found", "Invalid request");
 723		return;
 724	}
 725
 726	/* If cmd->want_vpath is set, assume ctx.qry.path contains a "virtual"
 727	 * in-project path limit to be made available at ctx.qry.vpath.
 728	 * Otherwise, no path limit is in effect (ctx.qry.vpath = NULL).
 729	 */
 730	ctx.qry.vpath = cmd->want_vpath ? ctx.qry.path : NULL;
 731
 732	if (cmd->want_repo && !ctx.repo) {
 733		cgit_print_error_page(400, "Bad request",
 734				"No repository selected");
 735		return;
 736	}
 737
 738	if (ctx.repo && prepare_repo_cmd())
 739		return;
 740
 741	cmd->fn();
 742}
 743
 744static int cmp_repos(const void *a, const void *b)
 745{
 746	const struct cgit_repo *ra = a, *rb = b;
 747	return strcmp(ra->url, rb->url);
 748}
 749
 750static char *build_snapshot_setting(int bitmap)
 751{
 752	const struct cgit_snapshot_format *f;
 753	struct strbuf result = STRBUF_INIT;
 754
 755	for (f = cgit_snapshot_formats; f->suffix; f++) {
 756		if (f->bit & bitmap) {
 757			if (result.len)
 758				strbuf_addch(&result, ' ');
 759			strbuf_addstr(&result, f->suffix);
 760		}
 761	}
 762	return strbuf_detach(&result, NULL);
 763}
 764
 765static char *get_first_line(char *txt)
 766{
 767	char *t = xstrdup(txt);
 768	char *p = strchr(t, '\n');
 769	if (p)
 770		*p = '\0';
 771	return t;
 772}
 773
 774static void print_repo(FILE *f, struct cgit_repo *repo)
 775{
 776	struct string_list_item *item;
 777	fprintf(f, "repo.url=%s\n", repo->url);
 778	fprintf(f, "repo.name=%s\n", repo->name);
 779	fprintf(f, "repo.path=%s\n", repo->path);
 780	if (repo->owner)
 781		fprintf(f, "repo.owner=%s\n", repo->owner);
 782	if (repo->desc) {
 783		char *tmp = get_first_line(repo->desc);
 784		fprintf(f, "repo.desc=%s\n", tmp);
 785		free(tmp);
 786	}
 787	for_each_string_list_item(item, &repo->readme) {
 788		if (item->util)
 789			fprintf(f, "repo.readme=%s:%s\n", (char *)item->util, item->string);
 790		else
 791			fprintf(f, "repo.readme=%s\n", item->string);
 792	}
 793	if (repo->defbranch)
 794		fprintf(f, "repo.defbranch=%s\n", repo->defbranch);
 795	if (repo->module_link)
 796		fprintf(f, "repo.module-link=%s\n", repo->module_link);
 797	if (repo->section)
 798		fprintf(f, "repo.section=%s\n", repo->section);
 799	if (repo->homepage)
 800		fprintf(f, "repo.homepage=%s\n", repo->homepage);
 801	if (repo->clone_url)
 802		fprintf(f, "repo.clone-url=%s\n", repo->clone_url);
 803	fprintf(f, "repo.enable-commit-graph=%d\n",
 804	        repo->enable_commit_graph);
 805	fprintf(f, "repo.enable-log-filecount=%d\n",
 806	        repo->enable_log_filecount);
 807	fprintf(f, "repo.enable-log-linecount=%d\n",
 808	        repo->enable_log_linecount);
 809	if (repo->about_filter && repo->about_filter != ctx.cfg.about_filter)
 810		cgit_fprintf_filter(repo->about_filter, f, "repo.about-filter=");
 811	if (repo->commit_filter && repo->commit_filter != ctx.cfg.commit_filter)
 812		cgit_fprintf_filter(repo->commit_filter, f, "repo.commit-filter=");
 813	if (repo->source_filter && repo->source_filter != ctx.cfg.source_filter)
 814		cgit_fprintf_filter(repo->source_filter, f, "repo.source-filter=");
 815	if (repo->email_filter && repo->email_filter != ctx.cfg.email_filter)
 816		cgit_fprintf_filter(repo->email_filter, f, "repo.email-filter=");
 817	if (repo->owner_filter && repo->owner_filter != ctx.cfg.owner_filter)
 818		cgit_fprintf_filter(repo->owner_filter, f, "repo.owner-filter=");
 819	if (repo->snapshots != ctx.cfg.snapshots) {
 820		char *tmp = build_snapshot_setting(repo->snapshots);
 821		fprintf(f, "repo.snapshots=%s\n", tmp ? tmp : "");
 822		free(tmp);
 823	}
 824	if (repo->max_stats != ctx.cfg.max_stats)
 825		fprintf(f, "repo.max-stats=%s\n",
 826		        cgit_find_stats_periodname(repo->max_stats));
 827	if (repo->logo)
 828		fprintf(f, "repo.logo=%s\n", repo->logo);
 829	if (repo->logo_link)
 830		fprintf(f, "repo.logo-link=%s\n", repo->logo_link);
 831	fprintf(f, "repo.enable-remote-branches=%d\n", repo->enable_remote_branches);
 832	fprintf(f, "repo.enable-subject-links=%d\n", repo->enable_subject_links);
 833	fprintf(f, "repo.enable-html-serving=%d\n", repo->enable_html_serving);
 834	if (repo->branch_sort == 1)
 835		fprintf(f, "repo.branch-sort=age\n");
 836	if (repo->commit_sort) {
 837		if (repo->commit_sort == 1)
 838			fprintf(f, "repo.commit-sort=date\n");
 839		else if (repo->commit_sort == 2)
 840			fprintf(f, "repo.commit-sort=topo\n");
 841	}
 842	fprintf(f, "repo.hide=%d\n", repo->hide);
 843	fprintf(f, "repo.ignore=%d\n", repo->ignore);
 844	fprintf(f, "\n");
 845}
 846
 847static void print_repolist(FILE *f, struct cgit_repolist *list, int start)
 848{
 849	int i;
 850
 851	for (i = start; i < list->count; i++)
 852		print_repo(f, &list->repos[i]);
 853}
 854
 855/* Scan 'path' for git repositories, save the resulting repolist in 'cached_rc'
 856 * and return 0 on success.
 857 */
 858static int generate_cached_repolist(const char *path, const char *cached_rc)
 859{
 860	struct strbuf locked_rc = STRBUF_INIT;
 861	int result = 0;
 862	int idx;
 863	FILE *f;
 864
 865	strbuf_addf(&locked_rc, "%s.lock", cached_rc);
 866	f = fopen(locked_rc.buf, "wx");
 867	if (!f) {
 868		/* Inform about the error unless the lockfile already existed,
 869		 * since that only means we've got concurrent requests.
 870		 */
 871		result = errno;
 872		if (result != EEXIST)
 873			fprintf(stderr, "[cgit] Error opening %s: %s (%d)\n",
 874				locked_rc.buf, strerror(result), result);
 875		goto out;
 876	}
 877	idx = cgit_repolist.count;
 878	if (ctx.cfg.project_list)
 879		scan_projects(path, ctx.cfg.project_list, repo_config);
 880	else
 881		scan_tree(path, repo_config);
 882	print_repolist(f, &cgit_repolist, idx);
 883	if (rename(locked_rc.buf, cached_rc))
 884		fprintf(stderr, "[cgit] Error renaming %s to %s: %s (%d)\n",
 885			locked_rc.buf, cached_rc, strerror(errno), errno);
 886	fclose(f);
 887out:
 888	strbuf_release(&locked_rc);
 889	return result;
 890}
 891
 892static void process_cached_repolist(const char *path)
 893{
 894	struct stat st;
 895	struct strbuf cached_rc = STRBUF_INIT;
 896	time_t age;
 897	unsigned long hash;
 898
 899	hash = hash_str(path);
 900	if (ctx.cfg.project_list)
 901		hash += hash_str(ctx.cfg.project_list);
 902	strbuf_addf(&cached_rc, "%s/rc-%8lx", ctx.cfg.cache_root, hash);
 903
 904	if (stat(cached_rc.buf, &st)) {
 905		/* Nothing is cached, we need to scan without forking. And
 906		 * if we fail to generate a cached repolist, we need to
 907		 * invoke scan_tree manually.
 908		 */
 909		if (generate_cached_repolist(path, cached_rc.buf)) {
 910			if (ctx.cfg.project_list)
 911				scan_projects(path, ctx.cfg.project_list,
 912					      repo_config);
 913			else
 914				scan_tree(path, repo_config);
 915		}
 916		goto out;
 917	}
 918
 919	parse_configfile(cached_rc.buf, config_cb);
 920
 921	/* If the cached configfile hasn't expired, lets exit now */
 922	age = time(NULL) - st.st_mtime;
 923	if (age <= (ctx.cfg.cache_scanrc_ttl * 60))
 924		goto out;
 925
 926	/* The cached repolist has been parsed, but it was old. So lets
 927	 * rescan the specified path and generate a new cached repolist
 928	 * in a child-process to avoid latency for the current request.
 929	 */
 930	if (fork())
 931		goto out;
 932
 933	exit(generate_cached_repolist(path, cached_rc.buf));
 934out:
 935	strbuf_release(&cached_rc);
 936}
 937
 938static void cgit_parse_args(int argc, const char **argv)
 939{
 940	int i;
 941	int scan = 0;
 942
 943	for (i = 1; i < argc; i++) {
 944		if (!strcmp(argv[i], "--version")) {
 945			printf("CGit %s | https://git.zx2c4.com/cgit/\n\nCompiled in features:\n", CGIT_VERSION);
 946#ifdef NO_LUA
 947			printf("[-] ");
 948#else
 949			printf("[+] ");
 950#endif
 951			printf("Lua scripting\n");
 952#ifndef HAVE_LINUX_SENDFILE
 953			printf("[-] ");
 954#else
 955			printf("[+] ");
 956#endif
 957			printf("Linux sendfile() usage\n");
 958
 959			exit(0);
 960		}
 961		if (starts_with(argv[i], "--cache=")) {
 962			ctx.cfg.cache_root = xstrdup(argv[i] + 8);
 963		} else if (!strcmp(argv[i], "--nocache")) {
 964			ctx.cfg.nocache = 1;
 965		} else if (!strcmp(argv[i], "--nohttp")) {
 966			ctx.env.no_http = "1";
 967		} else if (starts_with(argv[i], "--query=")) {
 968			ctx.qry.raw = xstrdup(argv[i] + 8);
 969		} else if (starts_with(argv[i], "--repo=")) {
 970			ctx.qry.repo = xstrdup(argv[i] + 7);
 971		} else if (starts_with(argv[i], "--page=")) {
 972			ctx.qry.page = xstrdup(argv[i] + 7);
 973		} else if (starts_with(argv[i], "--head=")) {
 974			ctx.qry.head = xstrdup(argv[i] + 7);
 975			ctx.qry.has_symref = 1;
 976		} else if (starts_with(argv[i], "--sha1=")) {
 977			ctx.qry.sha1 = xstrdup(argv[i] + 7);
 978			ctx.qry.has_sha1 = 1;
 979		} else if (starts_with(argv[i], "--ofs=")) {
 980			ctx.qry.ofs = atoi(argv[i] + 6);
 981		} else if (starts_with(argv[i], "--scan-tree=") ||
 982		           starts_with(argv[i], "--scan-path=")) {
 983			/*
 984			 * HACK: The global snapshot bit mask defines the set
 985			 * of allowed snapshot formats, but the config file
 986			 * hasn't been parsed yet so the mask is currently 0.
 987			 * By setting all bits high before scanning we make
 988			 * sure that any in-repo cgitrc snapshot setting is
 989			 * respected by scan_tree().
 990			 *
 991			 * NOTE: We assume that there aren't more than 8
 992			 * different snapshot formats supported by cgit...
 993			 */
 994			ctx.cfg.snapshots = 0xFF;
 995			scan++;
 996			scan_tree(argv[i] + 12, repo_config);
 997		}
 998	}
 999	if (scan) {
1000		qsort(cgit_repolist.repos, cgit_repolist.count,
1001			sizeof(struct cgit_repo), cmp_repos);
1002		print_repolist(stdout, &cgit_repolist, 0);
1003		exit(0);
1004	}
1005}
1006
1007static int calc_ttl(void)
1008{
1009	if (!ctx.repo)
1010		return ctx.cfg.cache_root_ttl;
1011
1012	if (!ctx.qry.page)
1013		return ctx.cfg.cache_repo_ttl;
1014
1015	if (!strcmp(ctx.qry.page, "about"))
1016		return ctx.cfg.cache_about_ttl;
1017
1018	if (!strcmp(ctx.qry.page, "snapshot"))
1019		return ctx.cfg.cache_snapshot_ttl;
1020
1021	if (ctx.qry.has_sha1)
1022		return ctx.cfg.cache_static_ttl;
1023
1024	if (ctx.qry.has_symref)
1025		return ctx.cfg.cache_dynamic_ttl;
1026
1027	return ctx.cfg.cache_repo_ttl;
1028}
1029
1030int cmd_main(int argc, const char **argv)
1031{
1032	const char *path;
1033	int err, ttl;
1034
1035	cgit_init_filters();
1036	atexit(cgit_cleanup_filters);
1037
1038	prepare_context();
1039	cgit_repolist.length = 0;
1040	cgit_repolist.count = 0;
1041	cgit_repolist.repos = NULL;
1042
1043	cgit_parse_args(argc, argv);
1044	parse_configfile(expand_macros(ctx.env.cgit_config), config_cb);
1045	ctx.repo = NULL;
1046	http_parse_querystring(ctx.qry.raw, querystring_cb);
1047
1048	/* If virtual-root isn't specified in cgitrc, lets pretend
1049	 * that virtual-root equals SCRIPT_NAME, minus any possibly
1050	 * trailing slashes.
1051	 */
1052	if (!ctx.cfg.virtual_root && ctx.cfg.script_name)
1053		ctx.cfg.virtual_root = ensure_end(ctx.cfg.script_name, '/');
1054
1055	/* If no url parameter is specified on the querystring, lets
1056	 * use PATH_INFO as url. This allows cgit to work with virtual
1057	 * urls without the need for rewriterules in the webserver (as
1058	 * long as PATH_INFO is included in the cache lookup key).
1059	 */
1060	path = ctx.env.path_info;
1061	if (!ctx.qry.url && path) {
1062		if (path[0] == '/')
1063			path++;
1064		ctx.qry.url = xstrdup(path);
1065		if (ctx.qry.raw) {
1066			char *newqry = fmtalloc("%s?%s", path, ctx.qry.raw);
1067			free(ctx.qry.raw);
1068			ctx.qry.raw = newqry;
1069		} else
1070			ctx.qry.raw = xstrdup(ctx.qry.url);
1071		cgit_parse_url(ctx.qry.url);
1072	}
1073
1074	/* Before we go any further, we set ctx.env.authenticated by checking to see
1075	 * if the supplied cookie is valid. All cookies are valid if there is no
1076	 * auth_filter. If there is an auth_filter, the filter decides. */
1077	authenticate_cookie();
1078
1079	ttl = calc_ttl();
1080	if (ttl < 0)
1081		ctx.page.expires += 10 * 365 * 24 * 60 * 60; /* 10 years */
1082	else
1083		ctx.page.expires += ttl * 60;
1084	if (!ctx.env.authenticated || (ctx.env.request_method && !strcmp(ctx.env.request_method, "HEAD")))
1085		ctx.cfg.nocache = 1;
1086	if (ctx.cfg.nocache)
1087		ctx.cfg.cache_size = 0;
1088	err = cache_process(ctx.cfg.cache_size, ctx.cfg.cache_root,
1089			    ctx.qry.raw, ttl, process_request);
1090	cgit_cleanup_filters();
1091	if (err)
1092		cgit_print_error("Error processing page: %s (%d)",
1093				 strerror(err), err);
1094	return err;
1095}