all repos — cgit @ bc2f5a6d53fa8ec1dee3335dd6de4650f834231b

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