all repos — cgit @ 989d251384d5600abb33eb4c97b85d54dbfc6fcb

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