all repos — cgit @ cd4c77d989983778432363061e99219f034c3717

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