all repos — cgit @ c19d983ed7b86face56e41effea4fffcf9ad1e19

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