all repos — cgit @ 316ddeb74f1edcaf4c79f0249e4a8d78ea938821

a hyperfast web frontend for git written in c

shared.c (view raw)

  1/* shared.c: global vars + some callback functions
  2 *
  3 * Copyright (C) 2006-2014 cgit Development Team <cgit@lists.zx2c4.com>
  4 *
  5 * Licensed under GNU General Public License v2
  6 *   (see COPYING for full license text)
  7 */
  8
  9#include "cgit.h"
 10
 11struct cgit_repolist cgit_repolist;
 12struct cgit_context ctx;
 13
 14int chk_zero(int result, char *msg)
 15{
 16	if (result != 0)
 17		die_errno("%s", msg);
 18	return result;
 19}
 20
 21int chk_positive(int result, char *msg)
 22{
 23	if (result <= 0)
 24		die_errno("%s", msg);
 25	return result;
 26}
 27
 28int chk_non_negative(int result, char *msg)
 29{
 30	if (result < 0)
 31		die_errno("%s", msg);
 32	return result;
 33}
 34
 35char *cgit_default_repo_desc = "[no description]";
 36struct cgit_repo *cgit_add_repo(const char *url)
 37{
 38	struct cgit_repo *ret;
 39
 40	if (++cgit_repolist.count > cgit_repolist.length) {
 41		if (cgit_repolist.length == 0)
 42			cgit_repolist.length = 8;
 43		else
 44			cgit_repolist.length *= 2;
 45		cgit_repolist.repos = xrealloc(cgit_repolist.repos,
 46					       cgit_repolist.length *
 47					       sizeof(struct cgit_repo));
 48	}
 49
 50	ret = &cgit_repolist.repos[cgit_repolist.count-1];
 51	memset(ret, 0, sizeof(struct cgit_repo));
 52	ret->url = trim_end(url, '/');
 53	ret->name = ret->url;
 54	ret->path = NULL;
 55	ret->desc = cgit_default_repo_desc;
 56	ret->extra_head_content = NULL;
 57	ret->owner = NULL;
 58	ret->homepage = NULL;
 59	ret->section = ctx.cfg.section;
 60	ret->snapshots = ctx.cfg.snapshots;
 61	ret->enable_blame = ctx.cfg.enable_blame;
 62	ret->enable_commit_graph = ctx.cfg.enable_commit_graph;
 63	ret->enable_log_filecount = ctx.cfg.enable_log_filecount;
 64	ret->enable_log_linecount = ctx.cfg.enable_log_linecount;
 65	ret->enable_remote_branches = ctx.cfg.enable_remote_branches;
 66	ret->enable_subject_links = ctx.cfg.enable_subject_links;
 67	ret->enable_html_serving = ctx.cfg.enable_html_serving;
 68	ret->max_stats = ctx.cfg.max_stats;
 69	ret->branch_sort = ctx.cfg.branch_sort;
 70	ret->commit_sort = ctx.cfg.commit_sort;
 71	ret->module_link = ctx.cfg.module_link;
 72	ret->readme = ctx.cfg.readme;
 73	ret->mtime = -1;
 74	ret->about_filter = ctx.cfg.about_filter;
 75	ret->commit_filter = ctx.cfg.commit_filter;
 76	ret->source_filter = ctx.cfg.source_filter;
 77	ret->email_filter = ctx.cfg.email_filter;
 78	ret->owner_filter = ctx.cfg.owner_filter;
 79	ret->clone_url = ctx.cfg.clone_url;
 80	ret->submodules.strdup_strings = 1;
 81	ret->hide = ret->ignore = 0;
 82	return ret;
 83}
 84
 85struct cgit_repo *cgit_get_repoinfo(const char *url)
 86{
 87	int i;
 88	struct cgit_repo *repo;
 89
 90	for (i = 0; i < cgit_repolist.count; i++) {
 91		repo = &cgit_repolist.repos[i];
 92		if (repo->ignore)
 93			continue;
 94		if (!strcmp(repo->url, url))
 95			return repo;
 96	}
 97	return NULL;
 98}
 99
100void cgit_free_commitinfo(struct commitinfo *info)
101{
102	free(info->author);
103	free(info->author_email);
104	free(info->committer);
105	free(info->committer_email);
106	free(info->subject);
107	free(info->msg);
108	free(info->msg_encoding);
109	free(info);
110}
111
112char *trim_end(const char *str, char c)
113{
114	int len;
115
116	if (str == NULL)
117		return NULL;
118	len = strlen(str);
119	while (len > 0 && str[len - 1] == c)
120		len--;
121	if (len == 0)
122		return NULL;
123	return xstrndup(str, len);
124}
125
126char *ensure_end(const char *str, char c)
127{
128	size_t len = strlen(str);
129	char *result;
130
131	if (len && str[len - 1] == c)
132		return xstrndup(str, len);
133
134	result = xmalloc(len + 2);
135	memcpy(result, str, len);
136	result[len] = '/';
137	result[len + 1] = '\0';
138	return result;
139}
140
141void strbuf_ensure_end(struct strbuf *sb, char c)
142{
143	if (!sb->len || sb->buf[sb->len - 1] != c)
144		strbuf_addch(sb, c);
145}
146
147void cgit_add_ref(struct reflist *list, struct refinfo *ref)
148{
149	size_t size;
150
151	if (list->count >= list->alloc) {
152		list->alloc += (list->alloc ? list->alloc : 4);
153		size = list->alloc * sizeof(struct refinfo *);
154		list->refs = xrealloc(list->refs, size);
155	}
156	list->refs[list->count++] = ref;
157}
158
159static struct refinfo *cgit_mk_refinfo(const char *refname, const struct object_id *oid)
160{
161	struct refinfo *ref;
162
163	ref = xmalloc(sizeof (struct refinfo));
164	ref->refname = xstrdup(refname);
165	ref->object = parse_object(the_repository, oid);
166	switch (ref->object->type) {
167	case OBJ_TAG:
168		ref->tag = cgit_parse_tag((struct tag *)ref->object);
169		break;
170	case OBJ_COMMIT:
171		ref->commit = cgit_parse_commit((struct commit *)ref->object);
172		break;
173	}
174	return ref;
175}
176
177void cgit_free_taginfo(struct taginfo *tag)
178{
179	if (tag->tagger)
180		free(tag->tagger);
181	if (tag->tagger_email)
182		free(tag->tagger_email);
183	if (tag->msg)
184		free(tag->msg);
185	free(tag);
186}
187
188static void cgit_free_refinfo(struct refinfo *ref)
189{
190	if (ref->refname)
191		free((char *)ref->refname);
192	switch (ref->object->type) {
193	case OBJ_TAG:
194		cgit_free_taginfo(ref->tag);
195		break;
196	case OBJ_COMMIT:
197		cgit_free_commitinfo(ref->commit);
198		break;
199	}
200	free(ref);
201}
202
203void cgit_free_reflist_inner(struct reflist *list)
204{
205	int i;
206
207	for (i = 0; i < list->count; i++) {
208		cgit_free_refinfo(list->refs[i]);
209	}
210	free(list->refs);
211}
212
213int cgit_refs_cb(const char *refname, const struct object_id *oid, int flags,
214		  void *cb_data)
215{
216	struct reflist *list = (struct reflist *)cb_data;
217	struct refinfo *info = cgit_mk_refinfo(refname, oid);
218
219	if (info)
220		cgit_add_ref(list, info);
221	return 0;
222}
223
224void cgit_diff_tree_cb(struct diff_queue_struct *q,
225		       struct diff_options *options, void *data)
226{
227	int i;
228
229	for (i = 0; i < q->nr; i++) {
230		if (q->queue[i]->status == 'U')
231			continue;
232		((filepair_fn)data)(q->queue[i]);
233	}
234}
235
236static int load_mmfile(mmfile_t *file, const struct object_id *oid)
237{
238	enum object_type type;
239
240	if (is_null_oid(oid)) {
241		file->ptr = (char *)"";
242		file->size = 0;
243	} else {
244		file->ptr = read_object_file(oid, &type,
245		                           (unsigned long *)&file->size);
246	}
247	return 1;
248}
249
250/*
251 * Receive diff-buffers from xdiff and concatenate them as
252 * needed across multiple callbacks.
253 *
254 * This is basically a copy of xdiff-interface.c/xdiff_outf(),
255 * ripped from git and modified to use globals instead of
256 * a special callback-struct.
257 */
258static char *diffbuf = NULL;
259static int buflen = 0;
260
261static int filediff_cb(void *priv, mmbuffer_t *mb, int nbuf)
262{
263	int i;
264
265	for (i = 0; i < nbuf; i++) {
266		if (mb[i].ptr[mb[i].size-1] != '\n') {
267			/* Incomplete line */
268			diffbuf = xrealloc(diffbuf, buflen + mb[i].size);
269			memcpy(diffbuf + buflen, mb[i].ptr, mb[i].size);
270			buflen += mb[i].size;
271			continue;
272		}
273
274		/* we have a complete line */
275		if (!diffbuf) {
276			((linediff_fn)priv)(mb[i].ptr, mb[i].size);
277			continue;
278		}
279		diffbuf = xrealloc(diffbuf, buflen + mb[i].size);
280		memcpy(diffbuf + buflen, mb[i].ptr, mb[i].size);
281		((linediff_fn)priv)(diffbuf, buflen + mb[i].size);
282		free(diffbuf);
283		diffbuf = NULL;
284		buflen = 0;
285	}
286	if (diffbuf) {
287		((linediff_fn)priv)(diffbuf, buflen);
288		free(diffbuf);
289		diffbuf = NULL;
290		buflen = 0;
291	}
292	return 0;
293}
294
295int cgit_diff_files(const struct object_id *old_oid,
296		    const struct object_id *new_oid, unsigned long *old_size,
297		    unsigned long *new_size, int *binary, int context,
298		    int ignorews, linediff_fn fn)
299{
300	mmfile_t file1, file2;
301	xpparam_t diff_params;
302	xdemitconf_t emit_params;
303	xdemitcb_t emit_cb;
304
305	if (!load_mmfile(&file1, old_oid) || !load_mmfile(&file2, new_oid))
306		return 1;
307
308	*old_size = file1.size;
309	*new_size = file2.size;
310
311	if ((file1.ptr && buffer_is_binary(file1.ptr, file1.size)) ||
312	    (file2.ptr && buffer_is_binary(file2.ptr, file2.size))) {
313		*binary = 1;
314		if (file1.size)
315			free(file1.ptr);
316		if (file2.size)
317			free(file2.ptr);
318		return 0;
319	}
320
321	memset(&diff_params, 0, sizeof(diff_params));
322	memset(&emit_params, 0, sizeof(emit_params));
323	memset(&emit_cb, 0, sizeof(emit_cb));
324	diff_params.flags = XDF_NEED_MINIMAL;
325	if (ignorews)
326		diff_params.flags |= XDF_IGNORE_WHITESPACE;
327	emit_params.ctxlen = context > 0 ? context : 3;
328	emit_params.flags = XDL_EMIT_FUNCNAMES;
329	emit_cb.out_line = filediff_cb;
330	emit_cb.priv = fn;
331	xdl_diff(&file1, &file2, &diff_params, &emit_params, &emit_cb);
332	if (file1.size)
333		free(file1.ptr);
334	if (file2.size)
335		free(file2.ptr);
336	return 0;
337}
338
339void cgit_diff_tree(const struct object_id *old_oid,
340		    const struct object_id *new_oid,
341		    filepair_fn fn, const char *prefix, int ignorews)
342{
343	struct diff_options opt;
344	struct pathspec_item item;
345
346	memset(&item, 0, sizeof(item));
347	diff_setup(&opt);
348	opt.output_format = DIFF_FORMAT_CALLBACK;
349	opt.detect_rename = 1;
350	opt.rename_limit = ctx.cfg.renamelimit;
351	opt.flags.recursive = 1;
352	if (ignorews)
353		DIFF_XDL_SET(&opt, IGNORE_WHITESPACE);
354	opt.format_callback = cgit_diff_tree_cb;
355	opt.format_callback_data = fn;
356	if (prefix) {
357		item.match = xstrdup(prefix);
358		item.len = strlen(prefix);
359		opt.pathspec.nr = 1;
360		opt.pathspec.items = &item;
361	}
362	diff_setup_done(&opt);
363
364	if (old_oid && !is_null_oid(old_oid))
365		diff_tree_oid(old_oid, new_oid, "", &opt);
366	else
367		diff_root_tree_oid(new_oid, "", &opt);
368	diffcore_std(&opt);
369	diff_flush(&opt);
370
371	free(item.match);
372}
373
374void cgit_diff_commit(struct commit *commit, filepair_fn fn, const char *prefix)
375{
376	const struct object_id *old_oid = NULL;
377
378	if (commit->parents)
379		old_oid = &commit->parents->item->object.oid;
380	cgit_diff_tree(old_oid, &commit->object.oid, fn, prefix,
381		       ctx.qry.ignorews);
382}
383
384int cgit_parse_snapshots_mask(const char *str)
385{
386	struct string_list tokens = STRING_LIST_INIT_DUP;
387	struct string_list_item *item;
388	const struct cgit_snapshot_format *f;
389	int rv = 0;
390
391	/* favor legacy setting */
392	if (atoi(str))
393		return 1;
394
395	if (strcmp(str, "all") == 0)
396		return INT_MAX;
397
398	string_list_split(&tokens, str, ' ', -1);
399	string_list_remove_empty_items(&tokens, 0);
400
401	for_each_string_list_item(item, &tokens) {
402		for (f = cgit_snapshot_formats; f->suffix; f++) {
403			if (!strcmp(item->string, f->suffix) ||
404			    !strcmp(item->string, f->suffix + 1)) {
405				rv |= cgit_snapshot_format_bit(f);
406				break;
407			}
408		}
409	}
410
411	string_list_clear(&tokens, 0);
412	return rv;
413}
414
415typedef struct {
416	char * name;
417	char * value;
418} cgit_env_var;
419
420void cgit_prepare_repo_env(struct cgit_repo * repo)
421{
422	cgit_env_var env_vars[] = {
423		{ .name = "CGIT_REPO_URL", .value = repo->url },
424		{ .name = "CGIT_REPO_NAME", .value = repo->name },
425		{ .name = "CGIT_REPO_PATH", .value = repo->path },
426		{ .name = "CGIT_REPO_OWNER", .value = repo->owner },
427		{ .name = "CGIT_REPO_DEFBRANCH", .value = repo->defbranch },
428		{ .name = "CGIT_REPO_SECTION", .value = repo->section },
429		{ .name = "CGIT_REPO_CLONE_URL", .value = repo->clone_url }
430	};
431	int env_var_count = ARRAY_SIZE(env_vars);
432	cgit_env_var *p, *q;
433	static char *warn = "cgit warning: failed to set env: %s=%s\n";
434
435	p = env_vars;
436	q = p + env_var_count;
437	for (; p < q; p++)
438		if (p->value && setenv(p->name, p->value, 1))
439			fprintf(stderr, warn, p->name, p->value);
440}
441
442/* Read the content of the specified file into a newly allocated buffer,
443 * zeroterminate the buffer and return 0 on success, errno otherwise.
444 */
445int readfile(const char *path, char **buf, size_t *size)
446{
447	int fd, e;
448	struct stat st;
449
450	fd = open(path, O_RDONLY);
451	if (fd == -1)
452		return errno;
453	if (fstat(fd, &st)) {
454		e = errno;
455		close(fd);
456		return e;
457	}
458	if (!S_ISREG(st.st_mode)) {
459		close(fd);
460		return EISDIR;
461	}
462	*buf = xmalloc(st.st_size + 1);
463	*size = read_in_full(fd, *buf, st.st_size);
464	e = errno;
465	(*buf)[*size] = '\0';
466	close(fd);
467	return (*size == st.st_size ? 0 : e);
468}
469
470static int is_token_char(char c)
471{
472	return isalnum(c) || c == '_';
473}
474
475/* Replace name with getenv(name), return pointer to zero-terminating char
476 */
477static char *expand_macro(char *name, int maxlength)
478{
479	char *value;
480	size_t len;
481
482	len = 0;
483	value = getenv(name);
484	if (value) {
485		len = strlen(value) + 1;
486		if (len > maxlength)
487			len = maxlength;
488		strlcpy(name, value, len);
489		--len;
490	}
491	return name + len;
492}
493
494#define EXPBUFSIZE (1024 * 8)
495
496/* Replace all tokens prefixed by '$' in the specified text with the
497 * value of the named environment variable.
498 * NB: the return value is a static buffer, i.e. it must be strdup'd
499 * by the caller.
500 */
501char *expand_macros(const char *txt)
502{
503	static char result[EXPBUFSIZE];
504	char *p, *start;
505	int len;
506
507	p = result;
508	start = NULL;
509	while (p < result + EXPBUFSIZE - 1 && txt && *txt) {
510		*p = *txt;
511		if (start) {
512			if (!is_token_char(*txt)) {
513				if (p - start > 0) {
514					*p = '\0';
515					len = result + EXPBUFSIZE - start - 1;
516					p = expand_macro(start, len) - 1;
517				}
518				start = NULL;
519				txt--;
520			}
521			p++;
522			txt++;
523			continue;
524		}
525		if (*txt == '$') {
526			start = p;
527			txt++;
528			continue;
529		}
530		p++;
531		txt++;
532	}
533	*p = '\0';
534	if (start && p - start > 0) {
535		len = result + EXPBUFSIZE - start - 1;
536		p = expand_macro(start, len);
537		*p = '\0';
538	}
539	return result;
540}
541
542char *get_mimetype_for_filename(const char *filename)
543{
544	char *ext, *mimetype, *token, line[1024], *saveptr;
545	FILE *file;
546	struct string_list_item *mime;
547
548	if (!filename)
549		return NULL;
550
551	ext = strrchr(filename, '.');
552	if (!ext)
553		return NULL;
554	++ext;
555	if (!ext[0])
556		return NULL;
557	mime = string_list_lookup(&ctx.cfg.mimetypes, ext);
558	if (mime)
559		return xstrdup(mime->util);
560
561	if (!ctx.cfg.mimetype_file)
562		return NULL;
563	file = fopen(ctx.cfg.mimetype_file, "r");
564	if (!file)
565		return NULL;
566	while (fgets(line, sizeof(line), file)) {
567		if (!line[0] || line[0] == '#')
568			continue;
569		mimetype = strtok_r(line, " \t\r\n", &saveptr);
570		while ((token = strtok_r(NULL, " \t\r\n", &saveptr))) {
571			if (!strcasecmp(ext, token)) {
572				fclose(file);
573				return xstrdup(mimetype);
574			}
575		}
576	}
577	fclose(file);
578	return NULL;
579}