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