all repos — cgit @ 3cb5d86dc68bab4883bf5a7cbc90f3e266237355

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