]> gitweb.ps.run Git - ps-cgit/blob - shared.c
shared.c: use execvp() to execute filter commands
[ps-cgit] / shared.c
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
13 struct cgit_repolist cgit_repolist;
14 struct cgit_context ctx;
15
16 int chk_zero(int result, char *msg)
17 {
18         if (result != 0)
19                 die("%s: %s", msg, strerror(errno));
20         return result;
21 }
22
23 int chk_positive(int result, char *msg)
24 {
25         if (result <= 0)
26                 die("%s: %s", msg, strerror(errno));
27         return result;
28 }
29
30 int chk_non_negative(int result, char *msg)
31 {
32         if (result < 0)
33                 die("%s: %s",msg, strerror(errno));
34         return result;
35 }
36
37 struct 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
76 struct 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
89 void *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
102 char *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
124 char *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
140 char *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
155 void 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
167 struct 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
185 int 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
196 void 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
208 static 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  */
230 char *diffbuf = NULL;
231 int buflen = 0;
232
233 int 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
267 int 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
311 void 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
344 void 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
354 int 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
381 typedef struct {
382         char * name;
383         char * value;
384 } cgit_env_var;
385
386 static void 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         cgit_env_var *p, *q;
398         static char *warn = "cgit warning: failed to set env: %s=%s\n";
399
400         p = env_vars;
401         q = p + env_var_count;
402         for (; p < q; p++)
403                 if (setenv(p->name, p->value, 1))
404                         fprintf(stderr, warn, p->name, p->value);
405 }
406
407 int cgit_open_filter(struct cgit_filter *filter, struct cgit_repo * repo)
408 {
409
410         filter->old_stdout = chk_positive(dup(STDOUT_FILENO),
411                 "Unable to duplicate STDOUT");
412         chk_zero(pipe(filter->pipe_fh), "Unable to create pipe to subprocess");
413         filter->pid = chk_non_negative(fork(), "Unable to create subprocess");
414         if (filter->pid == 0) {
415                 close(filter->pipe_fh[1]);
416                 chk_non_negative(dup2(filter->pipe_fh[0], STDIN_FILENO),
417                         "Unable to use pipe as STDIN");
418                 if (repo)
419                         prepare_env(repo);
420                 execvp(filter->cmd, filter->argv);
421                 die("Unable to exec subprocess %s: %s (%d)", filter->cmd,
422                         strerror(errno), errno);
423         }
424         close(filter->pipe_fh[0]);
425         chk_non_negative(dup2(filter->pipe_fh[1], STDOUT_FILENO),
426                 "Unable to use pipe as STDOUT");
427         close(filter->pipe_fh[1]);
428         return 0;
429 }
430
431 int cgit_close_filter(struct cgit_filter *filter)
432 {
433         chk_non_negative(dup2(filter->old_stdout, STDOUT_FILENO),
434                 "Unable to restore STDOUT");
435         close(filter->old_stdout);
436         if (filter->pid < 0)
437                 return 0;
438         waitpid(filter->pid, &filter->exitstatus, 0);
439         if (WIFEXITED(filter->exitstatus) && !WEXITSTATUS(filter->exitstatus))
440                 return 0;
441         die("Subprocess %s exited abnormally", filter->cmd);
442 }
443
444 /* Read the content of the specified file into a newly allocated buffer,
445  * zeroterminate the buffer and return 0 on success, errno otherwise.
446  */
447 int readfile(const char *path, char **buf, size_t *size)
448 {
449         int fd, e;
450         struct stat st;
451
452         fd = open(path, O_RDONLY);
453         if (fd == -1)
454                 return errno;
455         if (fstat(fd, &st)) {
456                 e = errno;
457                 close(fd);
458                 return e;
459         }
460         if (!S_ISREG(st.st_mode)) {
461                 close(fd);
462                 return EISDIR;
463         }
464         *buf = xmalloc(st.st_size + 1);
465         *size = read_in_full(fd, *buf, st.st_size);
466         e = errno;
467         (*buf)[*size] = '\0';
468         close(fd);
469         return (*size == st.st_size ? 0 : e);
470 }
471
472 int is_token_char(char c)
473 {
474         return isalnum(c) || c == '_';
475 }
476
477 /* Replace name with getenv(name), return pointer to zero-terminating char
478  */
479 char *expand_macro(char *name, int maxlength)
480 {
481         char *value;
482         int len;
483
484         len = 0;
485         value = getenv(name);
486         if (value) {
487                 len = strlen(value);
488                 if (len > maxlength)
489                         len = maxlength;
490                 strncpy(name, value, len);
491         }
492         return name + len;
493 }
494
495 #define EXPBUFSIZE (1024 * 8)
496
497 /* Replace all tokens prefixed by '$' in the specified text with the
498  * value of the named environment variable.
499  * NB: the return value is a static buffer, i.e. it must be strdup'd
500  * by the caller.
501  */
502 char *expand_macros(const char *txt)
503 {
504         static char result[EXPBUFSIZE];
505         char *p, *start;
506         int len;
507
508         p = result;
509         start = NULL;
510         while (p < result + EXPBUFSIZE - 1 && txt && *txt) {
511                 *p = *txt;
512                 if (start) {
513                         if (!is_token_char(*txt)) {
514                                 if (p - start > 0) {
515                                         *p = '\0';
516                                         len = result + EXPBUFSIZE - start - 1;
517                                         p = expand_macro(start, len) - 1;
518                                 }
519                                 start = NULL;
520                                 txt--;
521                         }
522                         p++;
523                         txt++;
524                         continue;
525                 }
526                 if (*txt == '$') {
527                         start = p;
528                         txt++;
529                         continue;
530                 }
531                 p++;
532                 txt++;
533         }
534         *p = '\0';
535         if (start && p - start > 0) {
536                 len = result + EXPBUFSIZE - start - 1;
537                 p = expand_macro(start, len);
538                 *p = '\0';
539         }
540         return result;
541 }