all repos — cgit @ 00e3a3ecda77bf5ab149db0940c549f1bb618de4

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