all repos — cgit @ 880223dc845e8b502e753425b889cbb70b73478e

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