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