Raw
1 /*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
6 *
7 */
8
9 #include "git-compat-util.h"
10 #include "abspath.h"
11 #include "advice.h"
12 #include "date.h"
13 #include "branch.h"
14 #include "config.h"
15 #include "dir.h"
16 #include "parse.h"
17 #include "convert.h"
18 #include "environment.h"
19 #include "gettext.h"
20 #include "git-zlib.h"
21 #include "repository.h"
22 #include "lockfile.h"
23 #include "exec-cmd.h"
24 #include "strbuf.h"
25 #include "quote.h"
26 #include "hashmap.h"
27 #include "string-list.h"
28 #include "object-name.h"
29 #include "odb.h"
30 #include "path.h"
31 #include "utf8.h"
32 #include "color.h"
33 #include "refs.h"
34 #include "setup.h"
35 #include "strvec.h"
36 #include "trace2.h"
37 #include "wildmatch.h"
38 #include "write-or-die.h"
39
40 struct config_source {
41 struct config_source *prev;
42 union {
43 FILE *file;
44 struct config_buf {
45 const char *buf;
46 size_t len;
47 size_t pos;
48 } buf;
49 } u;
50 enum config_origin_type origin_type;
51 const char *name;
52 enum config_error_action default_error_action;
53 int linenr;
54 int eof;
55 size_t total_len;
56 struct strbuf value;
57 struct strbuf var;
58 unsigned subsection_case_sensitive : 1;
59
60 int (*do_fgetc)(struct config_source *c);
61 int (*do_ungetc)(int c, struct config_source *conf);
62 long (*do_ftell)(struct config_source *c);
63 };
64 #define CONFIG_SOURCE_INIT { 0 }
65
66 /*
67 * Config that comes from trusted scopes, namely:
68 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
69 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
70 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
71 *
72 * This is declared here for code cleanliness, but unlike the other
73 * static variables, this does not hold config parser state.
74 */
75 static struct config_set protected_config;
76
77 static int config_file_fgetc(struct config_source *conf)
78 {
79 return getc_unlocked(conf->u.file);
80 }
81
82 static int config_file_ungetc(int c, struct config_source *conf)
83 {
84 return ungetc(c, conf->u.file);
85 }
86
87 static long config_file_ftell(struct config_source *conf)
88 {
89 return ftell(conf->u.file);
90 }
91
92 static int config_buf_fgetc(struct config_source *conf)
93 {
94 if (conf->u.buf.pos < conf->u.buf.len)
95 return conf->u.buf.buf[conf->u.buf.pos++];
96
97 return EOF;
98 }
99
100 static int config_buf_ungetc(int c, struct config_source *conf)
101 {
102 if (conf->u.buf.pos > 0) {
103 conf->u.buf.pos--;
104 if (conf->u.buf.buf[conf->u.buf.pos] != c)
105 BUG("config_buf can only ungetc the same character");
106 return c;
107 }
108
109 return EOF;
110 }
111
112 static long config_buf_ftell(struct config_source *conf)
113 {
114 return conf->u.buf.pos;
115 }
116
117 struct config_include_data {
118 int depth;
119 config_fn_t fn;
120 void *data;
121 const struct config_options *opts;
122 const struct git_config_source *config_source;
123 struct repository *repo;
124
125 /*
126 * All remote URLs discovered when reading all config files.
127 */
128 struct string_list *remote_urls;
129 };
130 #define CONFIG_INCLUDE_INIT { 0 }
131
132 static int git_config_include(const char *var, const char *value,
133 const struct config_context *ctx, void *data);
134
135 #define MAX_INCLUDE_DEPTH 10
136 static const char include_depth_advice[] = N_(
137 "exceeded maximum include depth (%d) while including\n"
138 " %s\n"
139 "from\n"
140 " %s\n"
141 "This might be due to circular includes.");
142 static int handle_path_include(const struct key_value_info *kvi,
143 const char *path,
144 struct config_include_data *inc)
145 {
146 int ret = 0;
147 struct strbuf buf = STRBUF_INIT;
148 char *expanded;
149
150 if (!path)
151 return config_error_nonbool("include.path");
152
153 expanded = interpolate_path(path, 0);
154 if (!expanded)
155 return error(_("could not expand include path '%s'"), path);
156 path = expanded;
157
158 /*
159 * Use an absolute path as-is, but interpret relative paths
160 * based on the including config file.
161 */
162 if (!is_absolute_path(path)) {
163 const char *slash;
164
165 if (!kvi || kvi->origin_type != CONFIG_ORIGIN_FILE) {
166 ret = error(_("relative config includes must come from files"));
167 goto cleanup;
168 }
169
170 slash = find_last_dir_sep(kvi->filename);
171 if (slash)
172 strbuf_add(&buf, kvi->filename, slash - kvi->filename + 1);
173 strbuf_addstr(&buf, path);
174 path = buf.buf;
175 }
176
177 if (!access_or_die(path, R_OK, 0)) {
178 if (++inc->depth > MAX_INCLUDE_DEPTH)
179 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
180 !kvi ? "<unknown>" :
181 kvi->filename ? kvi->filename :
182 "the command line");
183 ret = git_config_from_file_with_options(git_config_include, path, inc,
184 kvi->scope, NULL);
185 inc->depth--;
186 }
187 cleanup:
188 strbuf_release(&buf);
189 free(expanded);
190 return ret;
191 }
192
193 static void add_trailing_starstar_for_dir(struct strbuf *pat)
194 {
195 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
196 strbuf_addstr(pat, "**");
197 }
198
199 static int prepare_include_condition_pattern(const struct key_value_info *kvi,
200 struct strbuf *pat,
201 size_t *out)
202 {
203 struct strbuf path = STRBUF_INIT;
204 char *expanded;
205 size_t prefix = 0;
206
207 expanded = interpolate_path(pat->buf, 1);
208 if (expanded) {
209 strbuf_reset(pat);
210 strbuf_addstr(pat, expanded);
211 free(expanded);
212 }
213
214 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
215 const char *slash;
216
217 if (!kvi || kvi->origin_type != CONFIG_ORIGIN_FILE)
218 return error(_("relative config include "
219 "conditionals must come from files"));
220
221 strbuf_realpath(&path, kvi->filename, 1);
222 slash = find_last_dir_sep(path.buf);
223 if (!slash)
224 BUG("how is this possible?");
225 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
226 prefix = slash - path.buf + 1 /* slash */;
227 } else if (!is_absolute_path(pat->buf))
228 strbuf_insertstr(pat, 0, "**/");
229
230 add_trailing_starstar_for_dir(pat);
231
232 *out = prefix;
233
234 strbuf_release(&path);
235 return 0;
236 }
237
238 static int include_by_path(const struct key_value_info *kvi,
239 const char *path,
240 const char *cond, size_t cond_len, int icase)
241 {
242 struct strbuf text = STRBUF_INIT;
243 struct strbuf pattern = STRBUF_INIT;
244 size_t prefix;
245 int ret = 0;
246 int already_tried_absolute = 0;
247
248 if (!path)
249 goto done;
250
251 strbuf_realpath(&text, path, 1);
252 strbuf_add(&pattern, cond, cond_len);
253 ret = prepare_include_condition_pattern(kvi, &pattern, &prefix);
254 if (ret < 0)
255 goto done;
256
257 again:
258 if (prefix > 0) {
259 /*
260 * perform literal matching on the prefix part so that
261 * any wildcard character in it can't create side effects.
262 */
263 if (text.len < prefix)
264 goto done;
265 if (!icase && strncmp(pattern.buf, text.buf, prefix))
266 goto done;
267 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
268 goto done;
269 }
270
271 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
272 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
273
274 if (!ret && !already_tried_absolute) {
275 /*
276 * We've tried e.g. matching gitdir:~/work, but if
277 * ~/work is a symlink to /mnt/storage/work
278 * strbuf_realpath() will expand it, so the rule won't
279 * match. Let's match against a
280 * strbuf_add_absolute_path() version of the path,
281 * which'll do the right thing
282 */
283 strbuf_reset(&text);
284 strbuf_add_absolute_path(&text, path);
285 already_tried_absolute = 1;
286 goto again;
287 }
288 done:
289 strbuf_release(&pattern);
290 strbuf_release(&text);
291 return ret;
292 }
293
294 static int include_by_branch(struct config_include_data *data,
295 const char *cond, size_t cond_len)
296 {
297 int flags;
298 int ret;
299 struct strbuf pattern = STRBUF_INIT;
300 const char *refname, *shortname;
301
302 if (!data->repo || data->repo->ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
303 return 0;
304
305 refname = refs_resolve_ref_unsafe(get_main_ref_store(data->repo),
306 "HEAD", 0, NULL, &flags);
307 if (!refname ||
308 !(flags & REF_ISSYMREF) ||
309 !skip_prefix(refname, "refs/heads/", &shortname))
310 return 0;
311
312 strbuf_add(&pattern, cond, cond_len);
313 add_trailing_starstar_for_dir(&pattern);
314 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
315 strbuf_release(&pattern);
316 return ret;
317 }
318
319 static int add_remote_url(const char *var, const char *value,
320 const struct config_context *ctx UNUSED, void *data)
321 {
322 struct string_list *remote_urls = data;
323 const char *remote_name;
324 size_t remote_name_len;
325 const char *key;
326
327 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
328 &key) &&
329 remote_name &&
330 !strcmp(key, "url"))
331 string_list_append(remote_urls, value);
332 return 0;
333 }
334
335 static void populate_remote_urls(struct config_include_data *inc)
336 {
337 struct config_options opts;
338
339 opts = *inc->opts;
340 opts.unconditional_remote_url = 1;
341
342 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
343 string_list_init_dup(inc->remote_urls);
344 config_with_options(add_remote_url, inc->remote_urls,
345 inc->config_source, inc->repo, &opts);
346 }
347
348 static int forbid_remote_url(const char *var, const char *value UNUSED,
349 const struct config_context *ctx UNUSED,
350 void *data UNUSED)
351 {
352 const char *remote_name;
353 size_t remote_name_len;
354 const char *key;
355
356 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
357 &key) &&
358 remote_name &&
359 !strcmp(key, "url"))
360 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
361 return 0;
362 }
363
364 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
365 struct string_list *remote_urls)
366 {
367 struct strbuf pattern = STRBUF_INIT;
368 struct string_list_item *url_item;
369 int found = 0;
370
371 strbuf_add(&pattern, glob, glob_len);
372 for_each_string_list_item(url_item, remote_urls) {
373 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
374 found = 1;
375 break;
376 }
377 }
378 strbuf_release(&pattern);
379 return found;
380 }
381
382 static int include_by_remote_url(struct config_include_data *inc,
383 const char *cond, size_t cond_len)
384 {
385 if (inc->opts->unconditional_remote_url)
386 return 1;
387 if (!inc->remote_urls)
388 populate_remote_urls(inc);
389 return at_least_one_url_matches_glob(cond, cond_len,
390 inc->remote_urls);
391 }
392
393 static int include_condition_is_true(const struct key_value_info *kvi,
394 struct config_include_data *inc,
395 const char *cond, size_t cond_len)
396 {
397 const struct config_options *opts = inc->opts;
398
399 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
400 return include_by_path(kvi, opts->git_dir, cond, cond_len, 0);
401 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
402 return include_by_path(kvi, opts->git_dir, cond, cond_len, 1);
403 else if (skip_prefix_mem(cond, cond_len, "worktree:", &cond, &cond_len))
404 return include_by_path(kvi, inc->repo ? repo_get_work_tree(inc->repo) : NULL,
405 cond, cond_len, 0);
406 else if (skip_prefix_mem(cond, cond_len, "worktree/i:", &cond, &cond_len))
407 return include_by_path(kvi, inc->repo ? repo_get_work_tree(inc->repo) : NULL,
408 cond, cond_len, 1);
409 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
410 return include_by_branch(inc, cond, cond_len);
411 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
412 &cond_len))
413 return include_by_remote_url(inc, cond, cond_len);
414
415 /* unknown conditionals are always false */
416 return 0;
417 }
418
419 static int git_config_include(const char *var, const char *value,
420 const struct config_context *ctx,
421 void *data)
422 {
423 struct config_include_data *inc = data;
424 const char *cond, *key;
425 size_t cond_len;
426 int ret;
427
428 /*
429 * Pass along all values, including "include" directives; this makes it
430 * possible to query information on the includes themselves.
431 */
432 ret = inc->fn(var, value, ctx, inc->data);
433 if (ret < 0)
434 return ret;
435
436 if (!strcmp(var, "include.path"))
437 ret = handle_path_include(ctx->kvi, value, inc);
438
439 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
440 cond && include_condition_is_true(ctx->kvi, inc, cond, cond_len) &&
441 !strcmp(key, "path")) {
442 config_fn_t old_fn = inc->fn;
443
444 if (inc->opts->unconditional_remote_url)
445 inc->fn = forbid_remote_url;
446 ret = handle_path_include(ctx->kvi, value, inc);
447 inc->fn = old_fn;
448 }
449
450 return ret;
451 }
452
453 static void git_config_push_split_parameter(const char *key, const char *value)
454 {
455 struct strbuf env = STRBUF_INIT;
456 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
457 if (old && *old) {
458 strbuf_addstr(&env, old);
459 strbuf_addch(&env, ' ');
460 }
461 sq_quote_buf(&env, key);
462 strbuf_addch(&env, '=');
463 if (value)
464 sq_quote_buf(&env, value);
465 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
466 strbuf_release(&env);
467 }
468
469 void git_config_push_parameter(const char *text)
470 {
471 const char *value;
472
473 /*
474 * When we see:
475 *
476 * section.subsection=with=equals.key=value
477 *
478 * we cannot tell if it means:
479 *
480 * [section "subsection=with=equals"]
481 * key = value
482 *
483 * or:
484 *
485 * [section]
486 * subsection = with=equals.key=value
487 *
488 * We parse left-to-right for the first "=", meaning we'll prefer to
489 * keep the value intact over the subsection. This is historical, but
490 * also sensible since values are more likely to contain odd or
491 * untrusted input than a section name.
492 *
493 * A missing equals is explicitly allowed (as a bool-only entry).
494 */
495 value = strchr(text, '=');
496 if (value) {
497 char *key = xmemdupz(text, value - text);
498 git_config_push_split_parameter(key, value + 1);
499 free(key);
500 } else {
501 git_config_push_split_parameter(text, NULL);
502 }
503 }
504
505 void git_config_push_env(const char *spec)
506 {
507 char *key;
508 const char *env_name;
509 const char *env_value;
510
511 env_name = strrchr(spec, '=');
512 if (!env_name)
513 die(_("invalid config format: %s"), spec);
514 key = xmemdupz(spec, env_name - spec);
515 env_name++;
516 if (!*env_name)
517 die(_("missing environment variable name for configuration '%.*s'"),
518 (int)(env_name - spec - 1), spec);
519
520 env_value = getenv(env_name);
521 if (!env_value)
522 die(_("missing environment variable '%s' for configuration '%.*s'"),
523 env_name, (int)(env_name - spec - 1), spec);
524
525 git_config_push_split_parameter(key, env_value);
526 free(key);
527 }
528
529 static inline int iskeychar(int c)
530 {
531 return isalnum(c) || c == '-';
532 }
533
534 /*
535 * Auxiliary function to sanity-check and split the key into the section
536 * identifier and variable name.
537 *
538 * Returns 0 on success, -1 when there is an invalid character in the key and
539 * -2 if there is no section name in the key.
540 *
541 * store_key - pointer to char* which will hold a copy of the key with
542 * lowercase section and variable name, can be NULL to skip
543 * allocation when only validation is needed
544 * baselen - pointer to size_t which will hold the length of the
545 * section + subsection part, can be NULL
546 * quiet - when non-zero, suppress error() reports on rejection
547 */
548 static int do_parse_config_key(const char *key, char **store_key,
549 size_t *baselen_, int quiet)
550 {
551 size_t i, baselen;
552 int dot;
553 const char *last_dot = strrchr(key, '.');
554
555 /*
556 * Since "key" actually contains the section name and the real
557 * key name separated by a dot, we have to know where the dot is.
558 */
559
560 if (last_dot == NULL || last_dot == key) {
561 if (!quiet)
562 error(_("key does not contain a section: %s"), key);
563 return -CONFIG_NO_SECTION_OR_NAME;
564 }
565
566 if (!last_dot[1]) {
567 if (!quiet)
568 error(_("key does not contain variable name: %s"), key);
569 return -CONFIG_NO_SECTION_OR_NAME;
570 }
571
572 baselen = last_dot - key;
573 if (baselen_)
574 *baselen_ = baselen;
575
576 /*
577 * Validate the key and while at it, lower case it for matching.
578 */
579 if (store_key)
580 *store_key = xmallocz(strlen(key));
581
582 dot = 0;
583 for (i = 0; key[i]; i++) {
584 unsigned char c = key[i];
585 if (c == '.')
586 dot = 1;
587 /* Leave the extended basename untouched.. */
588 if (!dot || i > baselen) {
589 if (!iskeychar(c) ||
590 (i == baselen + 1 && !isalpha(c))) {
591 if (!quiet)
592 error(_("invalid key: %s"), key);
593 goto out_free_ret_1;
594 }
595 c = tolower(c);
596 } else if (c == '\n') {
597 if (!quiet)
598 error(_("invalid key (newline): %s"), key);
599 goto out_free_ret_1;
600 }
601 if (store_key)
602 (*store_key)[i] = c;
603 }
604
605 return 0;
606
607 out_free_ret_1:
608 if (store_key)
609 FREE_AND_NULL(*store_key);
610 return -CONFIG_INVALID_KEY;
611 }
612
613 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
614 {
615 return do_parse_config_key(key, store_key, baselen_, 0);
616 }
617
618 int git_config_key_is_valid(const char *key)
619 {
620 return !do_parse_config_key(key, NULL, NULL, 1);
621 }
622
623 static int config_parse_pair(const char *key, const char *value,
624 struct key_value_info *kvi,
625 config_fn_t fn, void *data)
626 {
627 char *canonical_name;
628 int ret;
629 struct config_context ctx = {
630 .kvi = kvi,
631 };
632
633 if (!strlen(key))
634 return error(_("empty config key"));
635 if (git_config_parse_key(key, &canonical_name, NULL))
636 return -1;
637
638 ret = (fn(canonical_name, value, &ctx, data) < 0) ? -1 : 0;
639 free(canonical_name);
640 return ret;
641 }
642
643
644 /* for values read from `git_config_from_parameters()` */
645 void kvi_from_param(struct key_value_info *out)
646 {
647 out->filename = NULL;
648 out->linenr = -1;
649 out->origin_type = CONFIG_ORIGIN_CMDLINE;
650 out->scope = CONFIG_SCOPE_COMMAND;
651 }
652
653 int git_config_parse_parameter(const char *text,
654 config_fn_t fn, void *data)
655 {
656 const char *value;
657 struct string_list pair = STRING_LIST_INIT_DUP;
658 int ret;
659 struct key_value_info kvi = KVI_INIT;
660
661 kvi_from_param(&kvi);
662
663 string_list_split(&pair, text, "=", 1);
664 if (!pair.nr)
665 return error(_("bogus config parameter: %s"), text);
666
667 if (pair.nr == 1)
668 value = NULL;
669 else
670 value = pair.items[1].string;
671
672 if (!*pair.items[0].string) {
673 string_list_clear(&pair, 0);
674 return error(_("bogus config parameter: %s"), text);
675 }
676
677 ret = config_parse_pair(pair.items[0].string, value, &kvi, fn, data);
678 string_list_clear(&pair, 0);
679 return ret;
680 }
681
682 static int parse_config_env_list(char *env, struct key_value_info *kvi,
683 config_fn_t fn, void *data)
684 {
685 char *cur = env;
686 while (cur && *cur) {
687 const char *key = sq_dequote_step(cur, &cur);
688 if (!key)
689 return error(_("bogus format in %s"),
690 CONFIG_DATA_ENVIRONMENT);
691
692 if (!cur || isspace(*cur)) {
693 /* old-style 'key=value' */
694 if (git_config_parse_parameter(key, fn, data) < 0)
695 return -1;
696 }
697 else if (*cur == '=') {
698 /* new-style 'key'='value' */
699 const char *value;
700
701 cur++;
702 if (*cur == '\'') {
703 /* quoted value */
704 value = sq_dequote_step(cur, &cur);
705 if (!value || (cur && !isspace(*cur))) {
706 return error(_("bogus format in %s"),
707 CONFIG_DATA_ENVIRONMENT);
708 }
709 } else if (!*cur || isspace(*cur)) {
710 /* implicit bool: 'key'= */
711 value = NULL;
712 } else {
713 return error(_("bogus format in %s"),
714 CONFIG_DATA_ENVIRONMENT);
715 }
716
717 if (config_parse_pair(key, value, kvi, fn, data) < 0)
718 return -1;
719 }
720 else {
721 /* unknown format */
722 return error(_("bogus format in %s"),
723 CONFIG_DATA_ENVIRONMENT);
724 }
725
726 if (cur) {
727 while (isspace(*cur))
728 cur++;
729 }
730 }
731 return 0;
732 }
733
734 int git_config_from_parameters(config_fn_t fn, void *data)
735 {
736 const char *env;
737 struct strbuf envvar = STRBUF_INIT;
738 struct strvec to_free = STRVEC_INIT;
739 int ret = 0;
740 char *envw = NULL;
741 struct key_value_info kvi = KVI_INIT;
742
743 kvi_from_param(&kvi);
744 env = getenv(CONFIG_COUNT_ENVIRONMENT);
745 if (env) {
746 unsigned long count;
747 char *endp;
748
749 count = strtoul(env, &endp, 10);
750 if (*endp) {
751 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
752 goto out;
753 }
754 if (count > INT_MAX) {
755 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
756 goto out;
757 }
758
759 for (unsigned long i = 0; i < count; i++) {
760 const char *key, *value;
761
762 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%lu", i);
763 key = getenv_safe(&to_free, envvar.buf);
764 if (!key) {
765 ret = error(_("missing config key %s"), envvar.buf);
766 goto out;
767 }
768 strbuf_reset(&envvar);
769
770 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%lu", i);
771 value = getenv_safe(&to_free, envvar.buf);
772 if (!value) {
773 ret = error(_("missing config value %s"), envvar.buf);
774 goto out;
775 }
776 strbuf_reset(&envvar);
777
778 if (config_parse_pair(key, value, &kvi, fn, data) < 0) {
779 ret = -1;
780 goto out;
781 }
782 }
783 }
784
785 env = getenv(CONFIG_DATA_ENVIRONMENT);
786 if (env) {
787 /* sq_dequote will write over it */
788 envw = xstrdup(env);
789 if (parse_config_env_list(envw, &kvi, fn, data) < 0) {
790 ret = -1;
791 goto out;
792 }
793 }
794
795 out:
796 strbuf_release(&envvar);
797 strvec_clear(&to_free);
798 free(envw);
799 return ret;
800 }
801
802 static int get_next_char(struct config_source *cs)
803 {
804 int c = cs->do_fgetc(cs);
805
806 if (c == '\r') {
807 /* DOS like systems */
808 c = cs->do_fgetc(cs);
809 if (c != '\n') {
810 if (c != EOF)
811 cs->do_ungetc(c, cs);
812 c = '\r';
813 }
814 }
815
816 if (c != EOF && ++cs->total_len > INT_MAX) {
817 /*
818 * This is an absurdly long config file; refuse to parse
819 * further in order to protect downstream code from integer
820 * overflows. Note that we can't return an error specifically,
821 * but we can mark EOF and put trash in the return value,
822 * which will trigger a parse error.
823 */
824 cs->eof = 1;
825 return 0;
826 }
827
828 if (c == '\n')
829 cs->linenr++;
830 if (c == EOF) {
831 cs->eof = 1;
832 cs->linenr++;
833 c = '\n';
834 }
835 return c;
836 }
837
838 static char *parse_value(struct config_source *cs)
839 {
840 int quote = 0, comment = 0;
841 size_t trim_len = 0;
842
843 strbuf_reset(&cs->value);
844 for (;;) {
845 int c = get_next_char(cs);
846 if (c == '\n') {
847 if (quote) {
848 cs->linenr--;
849 return NULL;
850 }
851 if (trim_len)
852 strbuf_setlen(&cs->value, trim_len);
853 return cs->value.buf;
854 }
855 if (comment)
856 continue;
857 if (isspace(c) && !quote) {
858 if (!trim_len)
859 trim_len = cs->value.len;
860 if (cs->value.len)
861 strbuf_addch(&cs->value, c);
862 continue;
863 }
864 if (!quote) {
865 if (c == ';' || c == '#') {
866 comment = 1;
867 continue;
868 }
869 }
870 if (trim_len)
871 trim_len = 0;
872 if (c == '\\') {
873 c = get_next_char(cs);
874 switch (c) {
875 case '\n':
876 continue;
877 case 't':
878 c = '\t';
879 break;
880 case 'b':
881 c = '\b';
882 break;
883 case 'n':
884 c = '\n';
885 break;
886 /* Some characters escape as themselves */
887 case '\\': case '"':
888 break;
889 /* Reject unknown escape sequences */
890 default:
891 return NULL;
892 }
893 strbuf_addch(&cs->value, c);
894 continue;
895 }
896 if (c == '"') {
897 quote = 1 - quote;
898 continue;
899 }
900 strbuf_addch(&cs->value, c);
901 }
902 }
903
904 static int get_value(struct config_source *cs, struct key_value_info *kvi,
905 config_fn_t fn, void *data, struct strbuf *name)
906 {
907 int c;
908 char *value;
909 int ret;
910 struct config_context ctx = {
911 .kvi = kvi,
912 };
913
914 /* Get the full name */
915 for (;;) {
916 c = get_next_char(cs);
917 if (cs->eof)
918 break;
919 if (!iskeychar(c))
920 break;
921 strbuf_addch(name, tolower(c));
922 }
923
924 while (c == ' ' || c == '\t')
925 c = get_next_char(cs);
926
927 value = NULL;
928 if (c != '\n') {
929 if (c != '=')
930 return -1;
931 value = parse_value(cs);
932 if (!value)
933 return -1;
934 }
935 /*
936 * We already consumed the \n, but we need linenr to point to
937 * the line we just parsed during the call to fn to get
938 * accurate line number in error messages.
939 */
940 cs->linenr--;
941 kvi->linenr = cs->linenr;
942 ret = fn(name->buf, value, &ctx, data);
943 if (ret >= 0)
944 cs->linenr++;
945 return ret;
946 }
947
948 static int get_extended_base_var(struct config_source *cs, struct strbuf *name,
949 int c)
950 {
951 cs->subsection_case_sensitive = 0;
952 do {
953 if (c == '\n')
954 goto error_incomplete_line;
955 c = get_next_char(cs);
956 } while (isspace(c));
957
958 /* We require the format to be '[base "extension"]' */
959 if (c != '"')
960 return -1;
961 strbuf_addch(name, '.');
962
963 for (;;) {
964 int c = get_next_char(cs);
965 if (c == '\n')
966 goto error_incomplete_line;
967 if (c == '"')
968 break;
969 if (c == '\\') {
970 c = get_next_char(cs);
971 if (c == '\n')
972 goto error_incomplete_line;
973 }
974 strbuf_addch(name, c);
975 }
976
977 /* Final ']' */
978 if (get_next_char(cs) != ']')
979 return -1;
980 return 0;
981 error_incomplete_line:
982 cs->linenr--;
983 return -1;
984 }
985
986 static int get_base_var(struct config_source *cs, struct strbuf *name)
987 {
988 cs->subsection_case_sensitive = 1;
989 for (;;) {
990 int c = get_next_char(cs);
991 if (cs->eof)
992 return -1;
993 if (c == ']')
994 return 0;
995 if (isspace(c))
996 return get_extended_base_var(cs, name, c);
997 if (!iskeychar(c) && c != '.')
998 return -1;
999 strbuf_addch(name, tolower(c));
1000 }
1001 }
1002
1003 struct parse_event_data {
1004 enum config_event_t previous_type;
1005 size_t previous_offset;
1006 const struct config_options *opts;
1007 };
1008
1009 static int do_event(struct config_source *cs, enum config_event_t type,
1010 struct parse_event_data *data)
1011 {
1012 size_t offset;
1013
1014 if (!data->opts || !data->opts->event_fn)
1015 return 0;
1016
1017 if (type == CONFIG_EVENT_WHITESPACE &&
1018 data->previous_type == type)
1019 return 0;
1020
1021 offset = cs->do_ftell(cs);
1022 /*
1023 * At EOF, the parser always "inserts" an extra '\n', therefore
1024 * the end offset of the event is the current file position, otherwise
1025 * we will already have advanced to the next event.
1026 */
1027 if (type != CONFIG_EVENT_EOF)
1028 offset--;
1029
1030 if (data->previous_type != CONFIG_EVENT_EOF &&
1031 data->opts->event_fn(data->previous_type, data->previous_offset,
1032 offset, cs, data->opts->event_fn_data) < 0)
1033 return -1;
1034
1035 data->previous_type = type;
1036 data->previous_offset = offset;
1037
1038 return 0;
1039 }
1040
1041 static void kvi_from_source(struct config_source *cs,
1042 enum config_scope scope,
1043 struct key_value_info *out)
1044 {
1045 out->filename = strintern(cs->name);
1046 out->origin_type = cs->origin_type;
1047 out->linenr = cs->linenr;
1048 out->scope = scope;
1049 }
1050
1051 static int git_parse_source(struct config_source *cs, config_fn_t fn,
1052 struct key_value_info *kvi, void *data,
1053 const struct config_options *opts)
1054 {
1055 int comment = 0;
1056 size_t baselen = 0;
1057 struct strbuf *var = &cs->var;
1058 int error_return = 0;
1059 char *error_msg = NULL;
1060
1061 /* U+FEFF Byte Order Mark in UTF8 */
1062 const char *bomptr = utf8_bom;
1063
1064 /* For the parser event callback */
1065 struct parse_event_data event_data = {
1066 CONFIG_EVENT_EOF, 0, opts
1067 };
1068
1069 for (;;) {
1070 int c;
1071
1072 c = get_next_char(cs);
1073 if (bomptr && *bomptr) {
1074 /* We are at the file beginning; skip UTF8-encoded BOM
1075 * if present. Sane editors won't put this in on their
1076 * own, but e.g. Windows Notepad will do it happily. */
1077 if (c == (*bomptr & 0377)) {
1078 bomptr++;
1079 continue;
1080 } else {
1081 /* Do not tolerate partial BOM. */
1082 if (bomptr != utf8_bom)
1083 break;
1084 /* No BOM at file beginning. Cool. */
1085 bomptr = NULL;
1086 }
1087 }
1088 if (c == '\n') {
1089 if (cs->eof) {
1090 if (do_event(cs, CONFIG_EVENT_EOF, &event_data) < 0)
1091 return -1;
1092 return 0;
1093 }
1094 if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1095 return -1;
1096 comment = 0;
1097 continue;
1098 }
1099 if (comment)
1100 continue;
1101 if (isspace(c)) {
1102 if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1103 return -1;
1104 continue;
1105 }
1106 if (c == '#' || c == ';') {
1107 if (do_event(cs, CONFIG_EVENT_COMMENT, &event_data) < 0)
1108 return -1;
1109 comment = 1;
1110 continue;
1111 }
1112 if (c == '[') {
1113 if (do_event(cs, CONFIG_EVENT_SECTION, &event_data) < 0)
1114 return -1;
1115
1116 /* Reset prior to determining a new stem */
1117 strbuf_reset(var);
1118 if (get_base_var(cs, var) < 0 || var->len < 1)
1119 break;
1120 strbuf_addch(var, '.');
1121 baselen = var->len;
1122 continue;
1123 }
1124 if (!isalpha(c))
1125 break;
1126
1127 if (do_event(cs, CONFIG_EVENT_ENTRY, &event_data) < 0)
1128 return -1;
1129
1130 /*
1131 * Truncate the var name back to the section header
1132 * stem prior to grabbing the suffix part of the name
1133 * and the value.
1134 */
1135 strbuf_setlen(var, baselen);
1136 strbuf_addch(var, tolower(c));
1137 if (get_value(cs, kvi, fn, data, var) < 0)
1138 break;
1139 }
1140
1141 if (do_event(cs, CONFIG_EVENT_ERROR, &event_data) < 0)
1142 return -1;
1143
1144 switch (cs->origin_type) {
1145 case CONFIG_ORIGIN_BLOB:
1146 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1147 cs->linenr, cs->name);
1148 break;
1149 case CONFIG_ORIGIN_FILE:
1150 error_msg = xstrfmt(_("bad config line %d in file %s"),
1151 cs->linenr, cs->name);
1152 break;
1153 case CONFIG_ORIGIN_STDIN:
1154 error_msg = xstrfmt(_("bad config line %d in standard input"),
1155 cs->linenr);
1156 break;
1157 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1158 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1159 cs->linenr, cs->name);
1160 break;
1161 case CONFIG_ORIGIN_CMDLINE:
1162 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1163 cs->linenr, cs->name);
1164 break;
1165 default:
1166 error_msg = xstrfmt(_("bad config line %d in %s"),
1167 cs->linenr, cs->name);
1168 }
1169
1170 switch (opts && opts->error_action ?
1171 opts->error_action :
1172 cs->default_error_action) {
1173 case CONFIG_ERROR_DIE:
1174 die("%s", error_msg);
1175 break;
1176 case CONFIG_ERROR_ERROR:
1177 error_return = error("%s", error_msg);
1178 break;
1179 case CONFIG_ERROR_SILENT:
1180 error_return = -1;
1181 break;
1182 case CONFIG_ERROR_UNSET:
1183 BUG("config error action unset");
1184 }
1185
1186 free(error_msg);
1187 return error_return;
1188 }
1189
1190 NORETURN
1191 static void die_bad_number(const char *name, const char *value,
1192 const struct key_value_info *kvi)
1193 {
1194 const char *error_type = (errno == ERANGE) ?
1195 N_("out of range") : N_("invalid unit");
1196 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1197
1198 if (!kvi)
1199 BUG("kvi should not be NULL");
1200
1201 if (!value)
1202 value = "";
1203
1204 if (!kvi->filename)
1205 die(_(bad_numeric), value, name, _(error_type));
1206
1207 switch (kvi->origin_type) {
1208 case CONFIG_ORIGIN_BLOB:
1209 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1210 value, name, kvi->filename, _(error_type));
1211 case CONFIG_ORIGIN_FILE:
1212 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1213 value, name, kvi->filename, _(error_type));
1214 case CONFIG_ORIGIN_STDIN:
1215 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1216 value, name, _(error_type));
1217 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1218 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1219 value, name, kvi->filename, _(error_type));
1220 case CONFIG_ORIGIN_CMDLINE:
1221 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1222 value, name, kvi->filename, _(error_type));
1223 default:
1224 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1225 value, name, kvi->filename, _(error_type));
1226 }
1227 }
1228
1229 int git_config_int(const char *name, const char *value,
1230 const struct key_value_info *kvi)
1231 {
1232 int ret;
1233 if (!git_parse_int(value, &ret))
1234 die_bad_number(name, value, kvi);
1235 return ret;
1236 }
1237
1238 unsigned int git_config_uint(const char *name, const char *value,
1239 const struct key_value_info *kvi)
1240 {
1241 unsigned int ret;
1242 if (!git_parse_uint(value, &ret))
1243 die_bad_number(name, value, kvi);
1244 return ret;
1245 }
1246
1247 int64_t git_config_int64(const char *name, const char *value,
1248 const struct key_value_info *kvi)
1249 {
1250 int64_t ret;
1251 if (!git_parse_int64(value, &ret))
1252 die_bad_number(name, value, kvi);
1253 return ret;
1254 }
1255
1256 unsigned long git_config_ulong(const char *name, const char *value,
1257 const struct key_value_info *kvi)
1258 {
1259 unsigned long ret;
1260 if (!git_parse_ulong(value, &ret))
1261 die_bad_number(name, value, kvi);
1262 return ret;
1263 }
1264
1265 ssize_t git_config_ssize_t(const char *name, const char *value,
1266 const struct key_value_info *kvi)
1267 {
1268 ssize_t ret;
1269 if (!git_parse_ssize_t(value, &ret))
1270 die_bad_number(name, value, kvi);
1271 return ret;
1272 }
1273
1274 double git_config_double(const char *name, const char *value,
1275 const struct key_value_info *kvi)
1276 {
1277 double ret;
1278 if (!git_parse_double(value, &ret))
1279 die_bad_number(name, value, kvi);
1280 return ret;
1281 }
1282
1283 int git_config_bool_or_int(const char *name, const char *value,
1284 const struct key_value_info *kvi, int *is_bool)
1285 {
1286 int v = git_parse_maybe_bool_text(value);
1287 if (0 <= v) {
1288 *is_bool = 1;
1289 return v;
1290 }
1291 *is_bool = 0;
1292 return git_config_int(name, value, kvi);
1293 }
1294
1295 int git_config_bool(const char *name, const char *value)
1296 {
1297 int v = git_parse_maybe_bool(value);
1298 if (v < 0)
1299 die(_("bad boolean config value '%s' for '%s'"), value, name);
1300 return v;
1301 }
1302
1303 int git_config_string(char **dest, const char *var, const char *value)
1304 {
1305 if (!value)
1306 return config_error_nonbool(var);
1307 *dest = xstrdup(value);
1308 return 0;
1309 }
1310
1311 int git_config_pathname(char **dest, const char *var, const char *value)
1312 {
1313 bool is_optional;
1314 char *path;
1315
1316 if (!value)
1317 return config_error_nonbool(var);
1318
1319 is_optional = skip_prefix(value, ":(optional)", &value);
1320 path = interpolate_path(value, 0);
1321 if (!path)
1322 die(_("failed to expand user dir in: '%s'"), value);
1323
1324 if (is_optional && is_missing_file(path)) {
1325 free(path);
1326 *dest = NULL;
1327 return 0;
1328 }
1329
1330 *dest = path;
1331 return 0;
1332 }
1333
1334 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1335 {
1336 if (!value)
1337 return config_error_nonbool(var);
1338 if (parse_expiry_date(value, timestamp))
1339 return error(_("'%s' for '%s' is not a valid timestamp"),
1340 value, var);
1341 return 0;
1342 }
1343
1344 int git_config_color(char *dest, const char *var, const char *value)
1345 {
1346 if (!value)
1347 return config_error_nonbool(var);
1348 if (color_parse(value, dest) < 0)
1349 return -1;
1350 return 0;
1351 }
1352
1353 /*
1354 * All source specific fields in the union, die_on_error, name and the callbacks
1355 * fgetc, ungetc, ftell of top need to be initialized before calling
1356 * this function.
1357 */
1358 static int do_config_from(struct config_source *top, config_fn_t fn,
1359 void *data, enum config_scope scope,
1360 const struct config_options *opts)
1361 {
1362 struct key_value_info kvi = KVI_INIT;
1363 int ret;
1364
1365 /* push config-file parsing state stack */
1366 top->linenr = 1;
1367 top->eof = 0;
1368 top->total_len = 0;
1369 strbuf_init(&top->value, 1024);
1370 strbuf_init(&top->var, 1024);
1371 kvi_from_source(top, scope, &kvi);
1372
1373 ret = git_parse_source(top, fn, &kvi, data, opts);
1374
1375 strbuf_release(&top->value);
1376 strbuf_release(&top->var);
1377
1378 return ret;
1379 }
1380
1381 static int do_config_from_file(config_fn_t fn,
1382 const enum config_origin_type origin_type,
1383 const char *name, FILE *f, void *data,
1384 enum config_scope scope,
1385 const struct config_options *opts)
1386 {
1387 struct config_source top = CONFIG_SOURCE_INIT;
1388 int ret;
1389
1390 if (origin_type == CONFIG_ORIGIN_FILE && (!name || !*name))
1391 BUG("missing filename for CONFIG_ORIGIN_FILE");
1392
1393 top.u.file = f;
1394 top.origin_type = origin_type;
1395 top.name = name;
1396 top.default_error_action = CONFIG_ERROR_DIE;
1397 top.do_fgetc = config_file_fgetc;
1398 top.do_ungetc = config_file_ungetc;
1399 top.do_ftell = config_file_ftell;
1400
1401 flockfile(f);
1402 ret = do_config_from(&top, fn, data, scope, opts);
1403 funlockfile(f);
1404 return ret;
1405 }
1406
1407 static int git_config_from_stdin(config_fn_t fn, void *data,
1408 enum config_scope scope)
1409 {
1410 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", stdin, data,
1411 scope, NULL);
1412 }
1413
1414 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1415 void *data, enum config_scope scope,
1416 const struct config_options *opts)
1417 {
1418 int ret = -1;
1419 FILE *f;
1420
1421 if (!filename)
1422 BUG("filename cannot be NULL");
1423 f = fopen_or_warn(filename, "r");
1424 if (f) {
1425 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
1426 f, data, scope, opts);
1427 fclose(f);
1428 }
1429 return ret;
1430 }
1431
1432 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1433 {
1434 return git_config_from_file_with_options(fn, filename, data,
1435 CONFIG_SCOPE_UNKNOWN, NULL);
1436 }
1437
1438 int git_config_from_mem(config_fn_t fn,
1439 const enum config_origin_type origin_type,
1440 const char *name, const char *buf, size_t len,
1441 void *data, enum config_scope scope,
1442 const struct config_options *opts)
1443 {
1444 struct config_source top = CONFIG_SOURCE_INIT;
1445
1446 top.u.buf.buf = buf;
1447 top.u.buf.len = len;
1448 top.u.buf.pos = 0;
1449 top.origin_type = origin_type;
1450 top.name = name;
1451 top.default_error_action = CONFIG_ERROR_ERROR;
1452 top.do_fgetc = config_buf_fgetc;
1453 top.do_ungetc = config_buf_ungetc;
1454 top.do_ftell = config_buf_ftell;
1455
1456 return do_config_from(&top, fn, data, scope, opts);
1457 }
1458
1459 int git_config_from_blob_oid(config_fn_t fn,
1460 const char *name,
1461 struct repository *repo,
1462 const struct object_id *oid,
1463 void *data,
1464 enum config_scope scope)
1465 {
1466 enum object_type type;
1467 char *buf;
1468 size_t size;
1469 int ret;
1470
1471 buf = odb_read_object(repo->objects, oid, &type, &size);
1472 if (!buf)
1473 return error(_("unable to load config blob object '%s'"), name);
1474 if (type != OBJ_BLOB) {
1475 free(buf);
1476 return error(_("reference '%s' does not point to a blob"), name);
1477 }
1478
1479 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
1480 data, scope, NULL);
1481 free(buf);
1482
1483 return ret;
1484 }
1485
1486 static int git_config_from_blob_ref(config_fn_t fn,
1487 struct repository *repo,
1488 const char *name,
1489 void *data,
1490 enum config_scope scope)
1491 {
1492 struct object_id oid;
1493
1494 if (repo_get_oid(repo, name, &oid) < 0)
1495 return error(_("unable to resolve config blob '%s'"), name);
1496 return git_config_from_blob_oid(fn, name, repo, &oid, data, scope);
1497 }
1498
1499 char *git_system_config(void)
1500 {
1501 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
1502 if (!system_config)
1503 system_config = system_path(ETC_GITCONFIG);
1504 normalize_path_copy(system_config, system_config);
1505 return system_config;
1506 }
1507
1508 char *git_global_config(void)
1509 {
1510 char *user_config, *xdg_config;
1511
1512 git_global_config_paths(&user_config, &xdg_config);
1513 if (!user_config) {
1514 free(xdg_config);
1515 return NULL;
1516 }
1517
1518 if (access_or_warn(user_config, R_OK, 0) && xdg_config &&
1519 !access_or_warn(xdg_config, R_OK, 0)) {
1520 free(user_config);
1521 return xdg_config;
1522 } else {
1523 free(xdg_config);
1524 return user_config;
1525 }
1526 }
1527
1528 void git_global_config_paths(char **user_out, char **xdg_out)
1529 {
1530 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
1531 char *xdg_config = NULL;
1532
1533 if (!user_config) {
1534 user_config = interpolate_path("~/.gitconfig", 0);
1535 xdg_config = xdg_config_home("config");
1536 }
1537
1538 *user_out = user_config;
1539 *xdg_out = xdg_config;
1540 }
1541
1542 int git_config_system(void)
1543 {
1544 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
1545 }
1546
1547 static int do_git_config_sequence(const struct config_options *opts,
1548 const struct repository *repo,
1549 config_fn_t fn, void *data)
1550 {
1551 int ret = 0;
1552 char *system_config = git_system_config();
1553 char *xdg_config = NULL;
1554 char *user_config = NULL;
1555 char *repo_config;
1556 char *worktree_config;
1557
1558 /*
1559 * Ensure that either:
1560 * - the git_dir and commondir are both set, or
1561 * - the git_dir and commondir are both NULL
1562 */
1563 if (!opts->git_dir != !opts->commondir)
1564 BUG("only one of commondir and git_dir is non-NULL");
1565
1566 if (opts->commondir) {
1567 repo_config = mkpathdup("%s/config", opts->commondir);
1568 worktree_config = mkpathdup("%s/config.worktree", opts->git_dir);
1569 } else {
1570 repo_config = NULL;
1571 worktree_config = NULL;
1572 }
1573
1574 if (git_config_system() && system_config &&
1575 !access_or_die(system_config, R_OK,
1576 opts->system_gently ? ACCESS_EACCES_OK : 0))
1577 ret += git_config_from_file_with_options(fn, system_config,
1578 data, CONFIG_SCOPE_SYSTEM,
1579 NULL);
1580
1581 git_global_config_paths(&user_config, &xdg_config);
1582
1583 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
1584 ret += git_config_from_file_with_options(fn, xdg_config, data,
1585 CONFIG_SCOPE_GLOBAL, NULL);
1586
1587 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
1588 ret += git_config_from_file_with_options(fn, user_config, data,
1589 CONFIG_SCOPE_GLOBAL, NULL);
1590
1591 if (!opts->ignore_repo && repo_config &&
1592 !access_or_die(repo_config, R_OK, 0))
1593 ret += git_config_from_file_with_options(fn, repo_config, data,
1594 CONFIG_SCOPE_LOCAL, NULL);
1595
1596 if (!opts->ignore_worktree && worktree_config &&
1597 repo && repo->repository_format_worktree_config &&
1598 !access_or_die(worktree_config, R_OK, 0)) {
1599 ret += git_config_from_file_with_options(fn, worktree_config, data,
1600 CONFIG_SCOPE_WORKTREE,
1601 NULL);
1602 }
1603
1604 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
1605 die(_("unable to parse command-line config"));
1606
1607 free(system_config);
1608 free(xdg_config);
1609 free(user_config);
1610 free(repo_config);
1611 free(worktree_config);
1612 return ret;
1613 }
1614
1615 int config_with_options(config_fn_t fn, void *data,
1616 const struct git_config_source *config_source,
1617 struct repository *repo,
1618 const struct config_options *opts)
1619 {
1620 struct config_include_data inc = CONFIG_INCLUDE_INIT;
1621 int ret;
1622
1623 if (opts->respect_includes) {
1624 inc.fn = fn;
1625 inc.data = data;
1626 inc.opts = opts;
1627 inc.repo = repo;
1628 inc.config_source = config_source;
1629 fn = git_config_include;
1630 data = &inc;
1631 }
1632
1633 /*
1634 * If we have a specific filename, use it. Otherwise, follow the
1635 * regular lookup sequence.
1636 */
1637 if (config_source && config_source->use_stdin) {
1638 ret = git_config_from_stdin(fn, data, config_source->scope);
1639 } else if (config_source && config_source->file) {
1640 ret = git_config_from_file_with_options(fn, config_source->file,
1641 data, config_source->scope,
1642 NULL);
1643 } else if (config_source && config_source->blob) {
1644 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
1645 data, config_source->scope);
1646 } else {
1647 ret = do_git_config_sequence(opts, repo, fn, data);
1648 }
1649
1650 if (inc.remote_urls) {
1651 string_list_clear(inc.remote_urls, 0);
1652 FREE_AND_NULL(inc.remote_urls);
1653 }
1654 return ret;
1655 }
1656
1657 static void configset_iter(struct config_set *set, config_fn_t fn, void *data)
1658 {
1659 int value_index;
1660 struct string_list *values;
1661 struct config_set_element *entry;
1662 struct configset_list *list = &set->list;
1663 struct config_context ctx = CONFIG_CONTEXT_INIT;
1664
1665 for (size_t i = 0; i < list->nr; i++) {
1666 entry = list->items[i].e;
1667 value_index = list->items[i].value_index;
1668 values = &entry->value_list;
1669
1670 ctx.kvi = values->items[value_index].util;
1671 if (fn(entry->key, values->items[value_index].string, &ctx, data) < 0)
1672 git_die_config_linenr(entry->key,
1673 ctx.kvi->filename,
1674 ctx.kvi->linenr);
1675 }
1676 }
1677
1678 void read_early_config(struct repository *repo, config_fn_t cb, void *data)
1679 {
1680 struct config_options opts = {0};
1681 struct strbuf commondir = STRBUF_INIT;
1682 struct strbuf gitdir = STRBUF_INIT;
1683
1684 opts.respect_includes = 1;
1685
1686 if (repo && repo->gitdir) {
1687 opts.commondir = repo_get_common_dir(repo);
1688 opts.git_dir = repo_get_git_dir(repo);
1689 /*
1690 * When setup_git_directory() was not yet asked to discover the
1691 * GIT_DIR, we ask discover_git_directory() to figure out whether there
1692 * is any repository config we should use (but unlike
1693 * setup_git_directory_gently(), no global state is changed, most
1694 * notably, the current working directory is still the same after the
1695 * call).
1696 */
1697 } else if (!discover_git_directory(&commondir, &gitdir)) {
1698 opts.commondir = commondir.buf;
1699 opts.git_dir = gitdir.buf;
1700 }
1701
1702 config_with_options(cb, data, NULL, NULL, &opts);
1703
1704 strbuf_release(&commondir);
1705 strbuf_release(&gitdir);
1706 }
1707
1708 void read_very_early_config(config_fn_t cb, void *data)
1709 {
1710 struct config_options opts = { 0 };
1711
1712 opts.respect_includes = 1;
1713 opts.ignore_repo = 1;
1714 opts.ignore_worktree = 1;
1715 opts.ignore_cmdline = 1;
1716 opts.system_gently = 1;
1717
1718 config_with_options(cb, data, NULL, NULL, &opts);
1719 }
1720
1721 RESULT_MUST_BE_USED
1722 static int configset_find_element(struct config_set *set, const char *key,
1723 struct config_set_element **dest)
1724 {
1725 struct config_set_element k;
1726 struct config_set_element *found_entry;
1727 char *normalized_key;
1728 int ret;
1729
1730 /*
1731 * `key` may come from the user, so normalize it before using it
1732 * for querying entries from the hashmap.
1733 */
1734 ret = git_config_parse_key(key, &normalized_key, NULL);
1735 if (ret)
1736 return ret;
1737
1738 hashmap_entry_init(&k.ent, strhash(normalized_key));
1739 k.key = normalized_key;
1740 found_entry = hashmap_get_entry(&set->config_hash, &k, ent, NULL);
1741 free(normalized_key);
1742 *dest = found_entry;
1743 return 0;
1744 }
1745
1746 static int configset_add_value(const struct key_value_info *kvi_p,
1747 struct config_set *set, const char *key,
1748 const char *value)
1749 {
1750 struct config_set_element *e;
1751 struct string_list_item *si;
1752 struct configset_list_item *l_item;
1753 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
1754 int ret;
1755
1756 ret = configset_find_element(set, key, &e);
1757 if (ret)
1758 return ret;
1759 /*
1760 * Since the keys are being fed by git_config*() callback mechanism, they
1761 * are already normalized. So simply add them without any further munging.
1762 */
1763 if (!e) {
1764 e = xmalloc(sizeof(*e));
1765 hashmap_entry_init(&e->ent, strhash(key));
1766 e->key = xstrdup(key);
1767 string_list_init_dup(&e->value_list);
1768 hashmap_add(&set->config_hash, &e->ent);
1769 }
1770 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
1771
1772 ALLOC_GROW(set->list.items, set->list.nr + 1, set->list.alloc);
1773 l_item = &set->list.items[set->list.nr++];
1774 l_item->e = e;
1775 l_item->value_index = e->value_list.nr - 1;
1776
1777 *kv_info = *kvi_p;
1778 si->util = kv_info;
1779
1780 return 0;
1781 }
1782
1783 static int config_set_element_cmp(const void *cmp_data UNUSED,
1784 const struct hashmap_entry *eptr,
1785 const struct hashmap_entry *entry_or_key,
1786 const void *keydata UNUSED)
1787 {
1788 const struct config_set_element *e1, *e2;
1789
1790 e1 = container_of(eptr, const struct config_set_element, ent);
1791 e2 = container_of(entry_or_key, const struct config_set_element, ent);
1792
1793 return strcmp(e1->key, e2->key);
1794 }
1795
1796 void git_configset_init(struct config_set *set)
1797 {
1798 hashmap_init(&set->config_hash, config_set_element_cmp, NULL, 0);
1799 set->hash_initialized = 1;
1800 set->list.nr = 0;
1801 set->list.alloc = 0;
1802 set->list.items = NULL;
1803 }
1804
1805 void git_configset_clear(struct config_set *set)
1806 {
1807 struct config_set_element *entry;
1808 struct hashmap_iter iter;
1809 if (!set->hash_initialized)
1810 return;
1811
1812 hashmap_for_each_entry(&set->config_hash, &iter, entry,
1813 ent /* member name */) {
1814 free(entry->key);
1815 string_list_clear(&entry->value_list, 1);
1816 }
1817 hashmap_clear_and_free(&set->config_hash, struct config_set_element, ent);
1818 set->hash_initialized = 0;
1819 free(set->list.items);
1820 set->list.nr = 0;
1821 set->list.alloc = 0;
1822 set->list.items = NULL;
1823 }
1824
1825 static int config_set_callback(const char *key, const char *value,
1826 const struct config_context *ctx,
1827 void *cb)
1828 {
1829 struct config_set *set = cb;
1830 configset_add_value(ctx->kvi, set, key, value);
1831 return 0;
1832 }
1833
1834 int git_configset_add_file(struct config_set *set, const char *filename)
1835 {
1836 return git_config_from_file(config_set_callback, filename, set);
1837 }
1838
1839 int git_configset_get_value(struct config_set *set, const char *key,
1840 const char **value, struct key_value_info *kvi)
1841 {
1842 const struct string_list *values = NULL;
1843 int ret;
1844 struct string_list_item item;
1845 /*
1846 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
1847 * queried key in the files of the configset, the value returned will be the last
1848 * value in the value list for that key.
1849 */
1850 if ((ret = git_configset_get_value_multi(set, key, &values)))
1851 return ret;
1852
1853 assert(values->nr > 0);
1854 item = values->items[values->nr - 1];
1855 *value = item.string;
1856 if (kvi)
1857 *kvi = *((struct key_value_info *)item.util);
1858 return 0;
1859 }
1860
1861 int git_configset_get_value_multi(struct config_set *set, const char *key,
1862 const struct string_list **dest)
1863 {
1864 struct config_set_element *e;
1865 int ret;
1866
1867 if ((ret = configset_find_element(set, key, &e)))
1868 return ret;
1869 else if (!e)
1870 return 1;
1871 *dest = &e->value_list;
1872
1873 return 0;
1874 }
1875
1876 static int check_multi_string(struct string_list_item *item, void *util)
1877 {
1878 return item->string ? 0 : config_error_nonbool(util);
1879 }
1880
1881 int git_configset_get_string_multi(struct config_set *cs, const char *key,
1882 const struct string_list **dest)
1883 {
1884 int ret;
1885
1886 if ((ret = git_configset_get_value_multi(cs, key, dest)))
1887 return ret;
1888 if ((ret = for_each_string_list((struct string_list *)*dest,
1889 check_multi_string, (void *)key)))
1890 return ret;
1891
1892 return 0;
1893 }
1894
1895 int git_configset_get(struct config_set *set, const char *key)
1896 {
1897 struct config_set_element *e;
1898 int ret;
1899
1900 if ((ret = configset_find_element(set, key, &e)))
1901 return ret;
1902 else if (!e)
1903 return 1;
1904 return 0;
1905 }
1906
1907 int git_configset_get_string(struct config_set *set, const char *key, char **dest)
1908 {
1909 const char *value;
1910 if (!git_configset_get_value(set, key, &value, NULL))
1911 return git_config_string(dest, key, value);
1912 else
1913 return 1;
1914 }
1915
1916 static int git_configset_get_string_tmp(struct config_set *set, const char *key,
1917 const char **dest)
1918 {
1919 const char *value;
1920 if (!git_configset_get_value(set, key, &value, NULL)) {
1921 if (!value)
1922 return config_error_nonbool(key);
1923 *dest = value;
1924 return 0;
1925 } else {
1926 return 1;
1927 }
1928 }
1929
1930 int git_configset_get_int(struct config_set *set, const char *key, int *dest)
1931 {
1932 const char *value;
1933 struct key_value_info kvi;
1934
1935 if (!git_configset_get_value(set, key, &value, &kvi)) {
1936 *dest = git_config_int(key, value, &kvi);
1937 return 0;
1938 } else
1939 return 1;
1940 }
1941
1942 int git_configset_get_uint(struct config_set *set, const char *key, unsigned int *dest)
1943 {
1944 const char *value;
1945 struct key_value_info kvi;
1946
1947 if (!git_configset_get_value(set, key, &value, &kvi)) {
1948 *dest = git_config_uint(key, value, &kvi);
1949 return 0;
1950 } else
1951 return 1;
1952 }
1953
1954 int git_configset_get_ulong(struct config_set *set, const char *key, unsigned long *dest)
1955 {
1956 const char *value;
1957 struct key_value_info kvi;
1958
1959 if (!git_configset_get_value(set, key, &value, &kvi)) {
1960 *dest = git_config_ulong(key, value, &kvi);
1961 return 0;
1962 } else
1963 return 1;
1964 }
1965
1966 int git_configset_get_bool(struct config_set *set, const char *key, int *dest)
1967 {
1968 const char *value;
1969 if (!git_configset_get_value(set, key, &value, NULL)) {
1970 *dest = git_config_bool(key, value);
1971 return 0;
1972 } else
1973 return 1;
1974 }
1975
1976 int git_configset_get_bool_or_int(struct config_set *set, const char *key,
1977 int *is_bool, int *dest)
1978 {
1979 const char *value;
1980 struct key_value_info kvi;
1981
1982 if (!git_configset_get_value(set, key, &value, &kvi)) {
1983 *dest = git_config_bool_or_int(key, value, &kvi, is_bool);
1984 return 0;
1985 } else
1986 return 1;
1987 }
1988
1989 int git_configset_get_maybe_bool(struct config_set *set, const char *key, int *dest)
1990 {
1991 const char *value;
1992 if (!git_configset_get_value(set, key, &value, NULL)) {
1993 *dest = git_parse_maybe_bool(value);
1994 if (*dest == -1)
1995 return -1;
1996 return 0;
1997 } else
1998 return 1;
1999 }
2000
2001 static int git_configset_get_pathname(struct config_set *set, const char *key, char **dest)
2002 {
2003 const char *value;
2004 if (!git_configset_get_value(set, key, &value, NULL))
2005 return git_config_pathname(dest, key, value);
2006 else
2007 return 1;
2008 }
2009
2010 struct comment_char_config {
2011 unsigned last_key_id;
2012 bool auto_set;
2013 bool auto_set_in_file;
2014 struct strintmap key_flags;
2015 size_t alloc, nr;
2016 struct comment_char_config_item {
2017 unsigned key_id;
2018 char *path;
2019 enum config_scope scope;
2020 } *item;
2021 };
2022
2023 #define COMMENT_CHAR_CFG_INIT { \
2024 .key_flags = STRINTMAP_INIT, \
2025 }
2026
2027 static void comment_char_config_release(struct comment_char_config *config)
2028 {
2029 strintmap_clear(&config->key_flags);
2030 for (size_t i = 0; i < config->nr; i++)
2031 free(config->item[i].path);
2032 free(config->item);
2033 }
2034
2035 /* Used to track whether the key occurs more than once in a given file */
2036 #define KEY_SEEN_ONCE 1u
2037 #define KEY_SEEN_TWICE 2u
2038 #define COMMENT_KEY_SHIFT(id) (2 * (id))
2039 #define COMMENT_KEY_MASK(id) (3u << COMMENT_KEY_SHIFT(id))
2040
2041 static void set_comment_key_flags(struct comment_char_config *config,
2042 const char *path, unsigned id, unsigned value)
2043 {
2044 unsigned old = strintmap_get(&config->key_flags, path);
2045 unsigned new = (old & ~COMMENT_KEY_MASK(id)) |
2046 value << COMMENT_KEY_SHIFT(id);
2047
2048 strintmap_set(&config->key_flags, path, new);
2049 }
2050
2051 static unsigned get_comment_key_flags(struct comment_char_config *config,
2052 const char *path, unsigned id)
2053 {
2054 unsigned value = strintmap_get(&config->key_flags, path);
2055
2056 return (value & COMMENT_KEY_MASK(id)) >> COMMENT_KEY_SHIFT(id);
2057 }
2058
2059 static const char *comment_key_name(unsigned id)
2060 {
2061 static const char *name[] = {
2062 "core.commentChar",
2063 "core.commentString",
2064 };
2065
2066 if (id >= ARRAY_SIZE(name))
2067 BUG("invalid comment key id");
2068
2069 return name[id];
2070 }
2071
2072 static void comment_char_callback(const char *key, const char *value,
2073 const struct config_context *ctx, void *data)
2074 {
2075 struct comment_char_config *config = data;
2076 const struct key_value_info *kvi = ctx->kvi;
2077 unsigned key_id;
2078
2079 if (!strcmp(key, "core.commentchar"))
2080 key_id = 0;
2081 else if (!strcmp(key, "core.commentstring"))
2082 key_id = 1;
2083 else
2084 return;
2085
2086 config->last_key_id = key_id;
2087 config->auto_set = value && !strcmp(value, "auto");
2088 if (kvi->origin_type != CONFIG_ORIGIN_FILE) {
2089 return;
2090 } else if (get_comment_key_flags(config, kvi->filename, key_id)) {
2091 set_comment_key_flags(config, kvi->filename, key_id,
2092 KEY_SEEN_TWICE);
2093 } else {
2094 struct comment_char_config_item *item;
2095
2096 ALLOC_GROW_BY(config->item, config->nr, 1, config->alloc);
2097 item = &config->item[config->nr - 1];
2098 item->key_id = key_id;
2099 item->scope = kvi->scope;
2100 item->path = xstrdup(kvi->filename);
2101 set_comment_key_flags(config, kvi->filename, key_id,
2102 KEY_SEEN_ONCE);
2103 }
2104 config->auto_set_in_file = config->auto_set;
2105 }
2106
2107 static void add_config_scope_arg(struct repository *repo, struct strbuf *buf,
2108 struct comment_char_config_item *item)
2109 {
2110 char *global_config = git_global_config();
2111 char *system_config = git_system_config();
2112
2113 if (item->scope == CONFIG_SCOPE_SYSTEM && access(item->path, W_OK)) {
2114 /*
2115 * If the user cannot write to the system config recommend
2116 * setting the global config instead.
2117 */
2118 strbuf_addstr(buf, "--global ");
2119 } else if (fspatheq(item->path, system_config)) {
2120 strbuf_addstr(buf, "--system ");
2121 } else if (fspatheq(item->path, global_config)) {
2122 strbuf_addstr(buf, "--global ");
2123 } else if (fspatheq(item->path,
2124 mkpath("%s/config",
2125 repo_get_git_dir(repo)))) {
2126 ; /* --local is the default */
2127 } else if (fspatheq(item->path,
2128 mkpath("%s/config.worktree",
2129 repo_get_common_dir(repo)))) {
2130 strbuf_addstr(buf, "--worktree ");
2131 } else {
2132 const char *path = item->path;
2133 const char *home = getenv("HOME");
2134
2135 strbuf_addstr(buf, "--file ");
2136 if (home && !fspathncmp(path, home, strlen(home))) {
2137 path += strlen(home);
2138 if (!fspathncmp(path, "/", 1))
2139 path++;
2140 strbuf_addstr(buf, "~/");
2141 }
2142 sq_quote_buf_pretty(buf, path);
2143 strbuf_addch(buf, ' ');
2144 }
2145
2146 free(global_config);
2147 free(system_config);
2148 }
2149
2150 static bool can_unset_comment_char_config(struct comment_char_config *config)
2151 {
2152 for (size_t i = 0; i < config->nr; i++) {
2153 struct comment_char_config_item *item = &config->item[i];
2154
2155 if (item->scope == CONFIG_SCOPE_SYSTEM &&
2156 access(item->path, W_OK))
2157 return false;
2158 }
2159
2160 return true;
2161 }
2162
2163 static void add_unset_auto_comment_char_advice(struct repository *repo,
2164 struct comment_char_config *config)
2165 {
2166 struct strbuf buf = STRBUF_INIT;
2167
2168 if (!can_unset_comment_char_config(config))
2169 return;
2170
2171 for (size_t i = 0; i < config->nr; i++) {
2172 struct comment_char_config_item *item = &config->item[i];
2173
2174 strbuf_addstr(&buf, " git config unset ");
2175 add_config_scope_arg(repo, &buf, item);
2176 if (get_comment_key_flags(config, item->path, item->key_id) == KEY_SEEN_TWICE)
2177 strbuf_addstr(&buf, "--all ");
2178 strbuf_addf(&buf, "%s\n", comment_key_name(item->key_id));
2179 }
2180 advise(_("\nTo use the default comment string (#) please run\n\n%s"),
2181 buf.buf);
2182 strbuf_release(&buf);
2183 }
2184
2185 static void add_comment_char_advice(struct repository *repo,
2186 struct comment_char_config *config)
2187 {
2188 struct strbuf buf = STRBUF_INIT;
2189 struct comment_char_config_item *item;
2190 /* TRANSLATORS this is a place holder for the value of core.commentString */
2191 const char *placeholder = _("<comment string>");
2192
2193 /*
2194 * If auto is set in the last file that we saw advise the user how to
2195 * update their config.
2196 */
2197 if (!config->auto_set_in_file)
2198 return;
2199
2200 add_unset_auto_comment_char_advice(repo, config);
2201 item = &config->item[config->nr - 1];
2202 strbuf_reset(&buf);
2203 strbuf_addstr(&buf, " git config set ");
2204 add_config_scope_arg(repo, &buf, item);
2205 strbuf_addf(&buf, "%s %s\n", comment_key_name(item->key_id),
2206 placeholder);
2207 advise(_("\nTo set a custom comment string please run\n\n"
2208 "%s\nwhere '%s' is the string you wish to use.\n"),
2209 buf.buf, placeholder);
2210 strbuf_release(&buf);
2211 }
2212
2213 #undef KEY_SEEN_ONCE
2214 #undef KEY_SEEN_TWICE
2215 #undef COMMENT_KEY_SHIFT
2216 #undef COMMENT_KEY_MASK
2217
2218 struct repo_config {
2219 struct repository *repo;
2220 struct comment_char_config comment_char_config;
2221 };
2222
2223 #define REPO_CONFIG_INIT(repo_) { \
2224 .comment_char_config = COMMENT_CHAR_CFG_INIT, \
2225 .repo = repo_, \
2226 };
2227
2228 static void repo_config_release(struct repo_config *config)
2229 {
2230 comment_char_config_release(&config->comment_char_config);
2231 }
2232
2233 #ifdef WITH_BREAKING_CHANGES
2234 static void check_auto_comment_char_config(struct repository *repo,
2235 struct comment_char_config *config)
2236 {
2237 if (!config->auto_set)
2238 return;
2239
2240 die_message(_("Support for '%s=auto' has been removed in Git 3.0"),
2241 comment_key_name(config->last_key_id));
2242 add_comment_char_advice(repo, config);
2243 die(NULL);
2244 }
2245 #else
2246 static void check_auto_comment_char_config(struct repository *repo,
2247 struct comment_char_config *config)
2248 {
2249 extern bool warn_on_auto_comment_char;
2250 const char *DEPRECATED_CONFIG_ENV =
2251 "GIT_AUTO_COMMENT_CHAR_CONFIG_WARNING_GIVEN";
2252
2253 if (!config->auto_set || !warn_on_auto_comment_char)
2254 return;
2255
2256 /*
2257 * Use an environment variable to ensure that subprocesses do not repeat
2258 * the warning.
2259 */
2260 if (git_env_bool(DEPRECATED_CONFIG_ENV, false))
2261 return;
2262
2263 setenv(DEPRECATED_CONFIG_ENV, "true", true);
2264
2265 warning(_("Support for '%s=auto' is deprecated and will be removed in "
2266 "Git 3.0"), comment_key_name(config->last_key_id));
2267 add_comment_char_advice(repo, config);
2268 }
2269 #endif /* WITH_BREAKING_CHANGES */
2270
2271 static void check_deprecated_config(struct repo_config *config)
2272 {
2273 if (!config->repo->check_deprecated_config)
2274 return;
2275
2276 check_auto_comment_char_config(config->repo,
2277 &config->comment_char_config);
2278 }
2279
2280 static int repo_config_callback(const char *key, const char *value,
2281 const struct config_context *ctx, void *data)
2282 {
2283 struct repo_config *config = data;
2284
2285 comment_char_callback(key, value, ctx, &config->comment_char_config);
2286 return config_set_callback(key, value, ctx, config->repo->config);
2287 }
2288
2289 /* Functions use to read configuration from a repository */
2290 static void repo_read_config(struct repository *repo)
2291 {
2292 struct config_options opts = { 0 };
2293 struct repo_config config = REPO_CONFIG_INIT(repo);
2294
2295 opts.respect_includes = 1;
2296 opts.commondir = repo->commondir;
2297 opts.git_dir = repo->gitdir;
2298
2299 if (!repo->config)
2300 CALLOC_ARRAY(repo->config, 1);
2301 else
2302 git_configset_clear(repo->config);
2303
2304 git_configset_init(repo->config);
2305 if (config_with_options(repo_config_callback, &config, NULL, repo,
2306 &opts) < 0)
2307 /*
2308 * config_with_options() normally returns only
2309 * zero, as most errors are fatal, and
2310 * non-fatal potential errors are guarded by "if"
2311 * statements that are entered only when no error is
2312 * possible.
2313 *
2314 * If we ever encounter a non-fatal error, it means
2315 * something went really wrong and we should stop
2316 * immediately.
2317 */
2318 die(_("unknown error occurred while reading the configuration files"));
2319 check_deprecated_config(&config);
2320 repo_config_release(&config);
2321 }
2322
2323 static void git_config_check_init(struct repository *repo)
2324 {
2325 if (repo->config && repo->config->hash_initialized)
2326 return;
2327 repo_read_config(repo);
2328 }
2329
2330 void repo_config_clear(struct repository *repo)
2331 {
2332 if (!repo->config || !repo->config->hash_initialized)
2333 return;
2334 git_configset_clear(repo->config);
2335 }
2336
2337 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2338 {
2339 if (!repo) {
2340 read_very_early_config(fn, data);
2341 return;
2342 }
2343 git_config_check_init(repo);
2344 configset_iter(repo->config, fn, data);
2345 }
2346
2347 int repo_config_get(struct repository *repo, const char *key)
2348 {
2349 git_config_check_init(repo);
2350 return git_configset_get(repo->config, key);
2351 }
2352
2353 int repo_config_get_value(struct repository *repo,
2354 const char *key, const char **value)
2355 {
2356 git_config_check_init(repo);
2357 return git_configset_get_value(repo->config, key, value, NULL);
2358 }
2359
2360 int repo_config_get_value_multi(struct repository *repo, const char *key,
2361 const struct string_list **dest)
2362 {
2363 git_config_check_init(repo);
2364 return git_configset_get_value_multi(repo->config, key, dest);
2365 }
2366
2367 int repo_config_get_string_multi(struct repository *repo, const char *key,
2368 const struct string_list **dest)
2369 {
2370 git_config_check_init(repo);
2371 return git_configset_get_string_multi(repo->config, key, dest);
2372 }
2373
2374 int repo_config_get_string(struct repository *repo,
2375 const char *key, char **dest)
2376 {
2377 int ret;
2378 git_config_check_init(repo);
2379 ret = git_configset_get_string(repo->config, key, dest);
2380 if (ret < 0)
2381 git_die_config(repo, key, NULL);
2382 return ret;
2383 }
2384
2385 int repo_config_get_string_tmp(struct repository *repo,
2386 const char *key, const char **dest)
2387 {
2388 int ret;
2389 git_config_check_init(repo);
2390 ret = git_configset_get_string_tmp(repo->config, key, dest);
2391 if (ret < 0)
2392 git_die_config(repo, key, NULL);
2393 return ret;
2394 }
2395
2396 int repo_config_get_int(struct repository *repo,
2397 const char *key, int *dest)
2398 {
2399 git_config_check_init(repo);
2400 return git_configset_get_int(repo->config, key, dest);
2401 }
2402
2403 int repo_config_get_uint(struct repository *repo,
2404 const char *key, unsigned int *dest)
2405 {
2406 git_config_check_init(repo);
2407 return git_configset_get_uint(repo->config, key, dest);
2408 }
2409
2410 int repo_config_get_ulong(struct repository *repo,
2411 const char *key, unsigned long *dest)
2412 {
2413 git_config_check_init(repo);
2414 return git_configset_get_ulong(repo->config, key, dest);
2415 }
2416
2417 int repo_config_get_bool(struct repository *repo,
2418 const char *key, int *dest)
2419 {
2420 git_config_check_init(repo);
2421 return git_configset_get_bool(repo->config, key, dest);
2422 }
2423
2424 int repo_config_get_bool_or_int(struct repository *repo,
2425 const char *key, int *is_bool, int *dest)
2426 {
2427 git_config_check_init(repo);
2428 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2429 }
2430
2431 int repo_config_get_maybe_bool(struct repository *repo,
2432 const char *key, int *dest)
2433 {
2434 git_config_check_init(repo);
2435 return git_configset_get_maybe_bool(repo->config, key, dest);
2436 }
2437
2438 int repo_config_get_pathname(struct repository *repo,
2439 const char *key, char **dest)
2440 {
2441 int ret;
2442 git_config_check_init(repo);
2443 ret = git_configset_get_pathname(repo->config, key, dest);
2444 if (ret < 0)
2445 git_die_config(repo, key, NULL);
2446 return ret;
2447 }
2448
2449 /* Read values into protected_config. */
2450 static void read_protected_config(void)
2451 {
2452 struct config_options opts = {
2453 .respect_includes = 1,
2454 .ignore_repo = 1,
2455 .ignore_worktree = 1,
2456 .system_gently = 1,
2457 };
2458
2459 git_configset_init(&protected_config);
2460 config_with_options(config_set_callback, &protected_config, NULL,
2461 NULL, &opts);
2462 }
2463
2464 void git_protected_config(config_fn_t fn, void *data)
2465 {
2466 if (!protected_config.hash_initialized)
2467 read_protected_config();
2468 configset_iter(&protected_config, fn, data);
2469 }
2470
2471 int repo_config_get_expiry(struct repository *r, const char *key, char **output)
2472 {
2473 int ret = repo_config_get_string(r, key, output);
2474
2475 if (ret)
2476 return ret;
2477 if (strcmp(*output, "now")) {
2478 timestamp_t now = approxidate("now");
2479 if (approxidate(*output) >= now)
2480 git_die_config(r, key, _("Invalid %s: '%s'"), key, *output);
2481 }
2482 return ret;
2483 }
2484
2485 int repo_config_get_expiry_in_days(struct repository *r, const char *key,
2486 timestamp_t *expiry, timestamp_t now)
2487 {
2488 const char *expiry_string;
2489 int days;
2490 timestamp_t when;
2491
2492 if (repo_config_get_string_tmp(r, key, &expiry_string))
2493 return 1; /* no such thing */
2494
2495 if (git_parse_int(expiry_string, &days)) {
2496 const intmax_t scale = 86400;
2497 *expiry = now - days * scale;
2498 return 0;
2499 }
2500
2501 if (!parse_expiry_date(expiry_string, &when)) {
2502 *expiry = when;
2503 return 0;
2504 }
2505 return -1; /* thing exists but cannot be parsed */
2506 }
2507
2508 int repo_config_get_split_index(struct repository *r)
2509 {
2510 int val;
2511
2512 if (!repo_config_get_maybe_bool(r, "core.splitindex", &val))
2513 return val;
2514
2515 return -1; /* default value */
2516 }
2517
2518 int repo_config_get_max_percent_split_change(struct repository *r)
2519 {
2520 int val = -1;
2521
2522 if (!repo_config_get_int(r, "splitindex.maxpercentchange", &val)) {
2523 if (0 <= val && val <= 100)
2524 return val;
2525
2526 return error(_("splitIndex.maxPercentChange value '%d' "
2527 "should be between 0 and 100"), val);
2528 }
2529
2530 return -1; /* default value */
2531 }
2532
2533 int repo_config_get_index_threads(struct repository *r, int *dest)
2534 {
2535 int is_bool, val;
2536
2537 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2538 if (val) {
2539 *dest = val;
2540 return 0;
2541 }
2542
2543 if (!repo_config_get_bool_or_int(r, "index.threads", &is_bool, &val)) {
2544 if (is_bool)
2545 *dest = val ? 0 : 1;
2546 else
2547 *dest = val;
2548 return 0;
2549 }
2550
2551 return 1;
2552 }
2553
2554 NORETURN
2555 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2556 {
2557 if (!filename)
2558 die(_("unable to parse '%s' from command-line config"), key);
2559 else
2560 die(_("bad config variable '%s' in file '%s' at line %d"),
2561 key, filename, linenr);
2562 }
2563
2564 void git_die_config(struct repository *r, const char *key, const char *err, ...)
2565 {
2566 const struct string_list *values;
2567 struct key_value_info *kv_info;
2568 report_fn error_fn = get_error_routine();
2569
2570 if (err) {
2571 va_list params;
2572 va_start(params, err);
2573 error_fn(err, params);
2574 va_end(params);
2575 }
2576 if (repo_config_get_value_multi(r, key, &values))
2577 BUG("for key '%s' we must have a value to report on", key);
2578 kv_info = values->items[values->nr - 1].util;
2579 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2580 }
2581
2582 /*
2583 * Find all the stuff for repo_config_set() below.
2584 */
2585
2586 struct config_store_data {
2587 size_t baselen;
2588 char *key;
2589 int do_not_match;
2590 const char *fixed_value;
2591 regex_t *value_pattern;
2592 int multi_replace;
2593 struct {
2594 size_t begin, end;
2595 enum config_event_t type;
2596 int is_keys_section;
2597 } *parsed;
2598 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2599 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2600 };
2601 #define CONFIG_STORE_INIT { 0 }
2602
2603 static void config_store_data_clear(struct config_store_data *store)
2604 {
2605 free(store->key);
2606 if (store->value_pattern != NULL &&
2607 store->value_pattern != CONFIG_REGEX_NONE) {
2608 regfree(store->value_pattern);
2609 free(store->value_pattern);
2610 }
2611 free(store->parsed);
2612 free(store->seen);
2613 memset(store, 0, sizeof(*store));
2614 }
2615
2616 static int matches(const char *key, const char *value,
2617 const struct config_store_data *store)
2618 {
2619 if (strcmp(key, store->key))
2620 return 0; /* not ours */
2621 if (store->fixed_value && value)
2622 return !strcmp(store->fixed_value, value);
2623 if (!store->value_pattern)
2624 return 1; /* always matches */
2625 if (store->value_pattern == CONFIG_REGEX_NONE)
2626 return 0; /* never matches */
2627
2628 return store->do_not_match ^
2629 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2630 }
2631
2632 static int store_aux_event(enum config_event_t type, size_t begin, size_t end,
2633 struct config_source *cs, void *data)
2634 {
2635 struct config_store_data *store = data;
2636
2637 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2638 store->parsed[store->parsed_nr].begin = begin;
2639 store->parsed[store->parsed_nr].end = end;
2640 store->parsed[store->parsed_nr].type = type;
2641
2642 if (type == CONFIG_EVENT_SECTION) {
2643 int (*cmpfn)(const char *, const char *, size_t);
2644
2645 if (cs->var.len < 2 || cs->var.buf[cs->var.len - 1] != '.')
2646 return error(_("invalid section name '%s'"), cs->var.buf);
2647
2648 if (cs->subsection_case_sensitive)
2649 cmpfn = strncasecmp;
2650 else
2651 cmpfn = strncmp;
2652
2653 /* Is this the section we were looking for? */
2654 store->is_keys_section =
2655 store->parsed[store->parsed_nr].is_keys_section =
2656 cs->var.len - 1 == store->baselen &&
2657 !cmpfn(cs->var.buf, store->key, store->baselen);
2658 if (store->is_keys_section) {
2659 store->section_seen = 1;
2660 ALLOC_GROW(store->seen, store->seen_nr + 1,
2661 store->seen_alloc);
2662 store->seen[store->seen_nr] = store->parsed_nr;
2663 }
2664 }
2665
2666 store->parsed_nr++;
2667
2668 return 0;
2669 }
2670
2671 static int store_aux(const char *key, const char *value,
2672 const struct config_context *ctx UNUSED, void *cb)
2673 {
2674 struct config_store_data *store = cb;
2675
2676 if (store->key_seen) {
2677 if (matches(key, value, store)) {
2678 if (store->seen_nr == 1 && store->multi_replace == 0) {
2679 warning(_("%s has multiple values"), key);
2680 }
2681
2682 ALLOC_GROW(store->seen, store->seen_nr + 1,
2683 store->seen_alloc);
2684
2685 store->seen[store->seen_nr] = store->parsed_nr;
2686 store->seen_nr++;
2687 }
2688 } else if (store->is_keys_section) {
2689 /*
2690 * Do not increment matches yet: this may not be a match, but we
2691 * are in the desired section.
2692 */
2693 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2694 store->seen[store->seen_nr] = store->parsed_nr;
2695 store->section_seen = 1;
2696
2697 if (matches(key, value, store)) {
2698 store->seen_nr++;
2699 store->key_seen = 1;
2700 }
2701 }
2702
2703 return 0;
2704 }
2705
2706 static int write_error(const char *filename)
2707 {
2708 error(_("failed to write new configuration file %s"), filename);
2709
2710 /* Same error code as "failed to rename". */
2711 return 4;
2712 }
2713
2714 static struct strbuf store_create_section(const char *key,
2715 const struct config_store_data *store)
2716 {
2717 const char *dot;
2718 size_t i;
2719 struct strbuf sb = STRBUF_INIT;
2720
2721 dot = memchr(key, '.', store->baselen);
2722 if (dot) {
2723 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2724 for (i = dot - key + 1; i < store->baselen; i++) {
2725 if (key[i] == '"' || key[i] == '\\')
2726 strbuf_addch(&sb, '\\');
2727 strbuf_addch(&sb, key[i]);
2728 }
2729 strbuf_addstr(&sb, "\"]\n");
2730 } else {
2731 strbuf_addch(&sb, '[');
2732 strbuf_add(&sb, key, store->baselen);
2733 strbuf_addstr(&sb, "]\n");
2734 }
2735
2736 return sb;
2737 }
2738
2739 static ssize_t write_section(int fd, const char *key,
2740 const struct config_store_data *store)
2741 {
2742 struct strbuf sb = store_create_section(key, store);
2743 ssize_t ret;
2744
2745 ret = write_in_full(fd, sb.buf, sb.len);
2746 strbuf_release(&sb);
2747
2748 return ret;
2749 }
2750
2751 static ssize_t write_pair(int fd, const char *key, const char *value,
2752 const char *comment,
2753 const struct config_store_data *store)
2754 {
2755 int i;
2756 ssize_t ret;
2757 const char *quote = "";
2758 struct strbuf sb = STRBUF_INIT;
2759
2760 /*
2761 * Check to see if the value needs to be surrounded with a dq pair.
2762 * Note that problematic characters are always backslash-quoted; this
2763 * check is about not losing leading or trailing SP and strings that
2764 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2765 * configuration parser.
2766 */
2767 if (value[0] == ' ')
2768 quote = "\"";
2769 for (i = 0; value[i]; i++)
2770 if (value[i] == ';' || value[i] == '#' || value[i] == '\r')
2771 quote = "\"";
2772 if (i && value[i - 1] == ' ')
2773 quote = "\"";
2774
2775 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
2776
2777 for (i = 0; value[i]; i++)
2778 switch (value[i]) {
2779 case '\n':
2780 strbuf_addstr(&sb, "\\n");
2781 break;
2782 case '\t':
2783 strbuf_addstr(&sb, "\\t");
2784 break;
2785 case '"':
2786 case '\\':
2787 strbuf_addch(&sb, '\\');
2788 /* fallthrough */
2789 default:
2790 strbuf_addch(&sb, value[i]);
2791 break;
2792 }
2793
2794 if (comment)
2795 strbuf_addf(&sb, "%s%s\n", quote, comment);
2796 else
2797 strbuf_addf(&sb, "%s\n", quote);
2798
2799 ret = write_in_full(fd, sb.buf, sb.len);
2800 strbuf_release(&sb);
2801
2802 return ret;
2803 }
2804
2805 /*
2806 * If we are about to unset the last key(s) in a section, and if there are
2807 * no comments surrounding (or included in) the section, we will want to
2808 * extend begin/end to remove the entire section.
2809 *
2810 * Note: the parameter `seen_ptr` points to the index into the store.seen
2811 * array. * This index may be incremented if a section has more than one
2812 * entry (which all are to be removed).
2813 */
2814 static void maybe_remove_section(struct config_store_data *store,
2815 size_t *begin_offset, size_t *end_offset,
2816 unsigned *seen_ptr)
2817 {
2818 size_t begin;
2819 int section_seen = 0;
2820 unsigned int i, seen;
2821
2822 /*
2823 * First, ensure that this is the first key, and that there are no
2824 * comments before the entry nor before the section header.
2825 */
2826 seen = *seen_ptr;
2827 for (i = store->seen[seen]; i > 0; i--) {
2828 enum config_event_t type = store->parsed[i - 1].type;
2829
2830 if (type == CONFIG_EVENT_COMMENT)
2831 /* There is a comment before this entry or section */
2832 return;
2833 if (type == CONFIG_EVENT_ENTRY) {
2834 if (!section_seen)
2835 /* This is not the section's first entry. */
2836 return;
2837 /* We encountered no comment before the section. */
2838 break;
2839 }
2840 if (type == CONFIG_EVENT_SECTION) {
2841 if (!store->parsed[i - 1].is_keys_section)
2842 break;
2843 section_seen = 1;
2844 }
2845 }
2846 begin = store->parsed[i].begin;
2847
2848 /*
2849 * Next, make sure that we are removing the last key(s) in the section,
2850 * and that there are no comments that are possibly about the current
2851 * section.
2852 */
2853 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
2854 enum config_event_t type = store->parsed[i].type;
2855
2856 if (type == CONFIG_EVENT_COMMENT)
2857 return;
2858 if (type == CONFIG_EVENT_SECTION) {
2859 if (store->parsed[i].is_keys_section)
2860 continue;
2861 break;
2862 }
2863 if (type == CONFIG_EVENT_ENTRY) {
2864 if (++seen < store->seen_nr &&
2865 i == store->seen[seen])
2866 /* We want to remove this entry, too */
2867 continue;
2868 /* There is another entry in this section. */
2869 return;
2870 }
2871 }
2872
2873 /*
2874 * We are really removing the last entry/entries from this section, and
2875 * there are no enclosed or surrounding comments. Remove the entire,
2876 * now-empty section.
2877 */
2878 *seen_ptr = seen;
2879 *begin_offset = begin;
2880 if (i < store->parsed_nr)
2881 *end_offset = store->parsed[i].begin;
2882 else
2883 *end_offset = store->parsed[store->parsed_nr - 1].end;
2884 }
2885
2886 int repo_config_set_in_file_gently(struct repository *r, const char *config_filename,
2887 const char *key, const char *comment, const char *value)
2888 {
2889 return repo_config_set_multivar_in_file_gently(r, config_filename, key, value, NULL, comment, 0);
2890 }
2891
2892 void repo_config_set_in_file(struct repository *r, const char *config_filename,
2893 const char *key, const char *value)
2894 {
2895 repo_config_set_multivar_in_file(r, config_filename, key, value, NULL, 0);
2896 }
2897
2898 int repo_config_set_gently(struct repository *r, const char *key, const char *value)
2899 {
2900 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
2901 }
2902
2903 int repo_config_set_worktree_gently(struct repository *r,
2904 const char *key, const char *value)
2905 {
2906 /* Only use worktree-specific config if it is already enabled. */
2907 if (r->repository_format_worktree_config) {
2908 char *file = repo_git_path(r, "config.worktree");
2909 int ret = repo_config_set_multivar_in_file_gently(
2910 r, file, key, value, NULL, NULL, 0);
2911 free(file);
2912 return ret;
2913 }
2914 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
2915 }
2916
2917 void repo_config_set(struct repository *r, const char *key, const char *value)
2918 {
2919 repo_config_set_multivar(r, key, value, NULL, 0);
2920
2921 trace2_cmd_set_config(key, value);
2922 }
2923
2924 char *git_config_prepare_comment_string(const char *comment)
2925 {
2926 size_t leading_blanks;
2927 char *prepared;
2928
2929 if (!comment)
2930 return NULL;
2931
2932 if (strchr(comment, '\n'))
2933 die(_("no multi-line comment allowed: '%s'"), comment);
2934
2935 /*
2936 * If it begins with one or more leading whitespace characters
2937 * followed by '#", the comment string is used as-is.
2938 *
2939 * If it begins with '#', a SP is inserted between the comment
2940 * and the value the comment is about.
2941 *
2942 * Otherwise, the value is followed by a SP followed by '#'
2943 * followed by SP and then the comment string comes.
2944 */
2945
2946 leading_blanks = strspn(comment, " \t");
2947 if (leading_blanks && comment[leading_blanks] == '#')
2948 prepared = xstrdup(comment); /* use it as-is */
2949 else if (comment[0] == '#')
2950 prepared = xstrfmt(" %s", comment);
2951 else
2952 prepared = xstrfmt(" # %s", comment);
2953
2954 return prepared;
2955 }
2956
2957 /*
2958 * How long to retry acquiring config.lock when another process holds
2959 * it. Default matches core.packedRefsTimeout; override via
2960 * core.configLockTimeout.
2961 */
2962 static long config_lock_timeout_ms(struct repository *r)
2963 {
2964 static int configured;
2965 static int timeout_ms = 1000;
2966
2967 if (!configured) {
2968 repo_config_get_int(r, "core.configlocktimeout", &timeout_ms);
2969 configured = 1;
2970 }
2971
2972 return timeout_ms;
2973 }
2974
2975 static void validate_comment_string(const char *comment)
2976 {
2977 size_t leading_blanks;
2978
2979 if (!comment)
2980 return;
2981 /*
2982 * The front-end must have massaged the comment string
2983 * properly before calling us.
2984 */
2985 if (strchr(comment, '\n'))
2986 BUG("multi-line comments are not permitted: '%s'", comment);
2987
2988 leading_blanks = strspn(comment, " \t");
2989 if (!leading_blanks || comment[leading_blanks] != '#')
2990 BUG("comment must begin with one or more SP followed by '#': '%s'",
2991 comment);
2992 }
2993
2994 /*
2995 * If value==NULL, unset in (remove from) config,
2996 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
2997 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
2998 * (only add a new one)
2999 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3000 * key/values are removed before a single new pair is written. If the
3001 * flag is not present, then replace only the first match.
3002 *
3003 * Returns 0 on success.
3004 *
3005 * This function does this:
3006 *
3007 * - it locks the config file by creating ".git/config.lock"
3008 *
3009 * - it then parses the config using store_aux() as validator to find
3010 * the position on the key/value pair to replace. If it is to be unset,
3011 * it must be found exactly once.
3012 *
3013 * - the config file is mmap()ed and the part before the match (if any) is
3014 * written to the lock file, then the changed part and the rest.
3015 *
3016 * - the config file is removed and the lock file rename()d to it.
3017 *
3018 */
3019 int repo_config_set_multivar_in_file_gently(struct repository *r,
3020 const char *config_filename,
3021 const char *key, const char *value,
3022 const char *value_pattern,
3023 const char *comment,
3024 unsigned flags)
3025 {
3026 int fd = -1, in_fd = -1;
3027 int ret;
3028 struct lock_file lock = LOCK_INIT;
3029 char *filename_buf = NULL;
3030 char *contents = NULL;
3031 size_t contents_sz;
3032 struct config_store_data store = CONFIG_STORE_INIT;
3033 bool saved_check_deprecated_config = r->check_deprecated_config;
3034
3035 /*
3036 * Do not warn or die if there are deprecated config settings as
3037 * we want the user to be able to change those settings by running
3038 * "git config".
3039 */
3040 r->check_deprecated_config = false;
3041
3042 validate_comment_string(comment);
3043
3044 /* parse-key returns negative; flip the sign to feed exit(3) */
3045 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3046 if (ret)
3047 goto out_free;
3048
3049 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3050
3051 if (!config_filename)
3052 config_filename = filename_buf = repo_git_path(r, "config");
3053
3054 /*
3055 * The lock serves a purpose in addition to locking: the new
3056 * contents of .git/config will be written into it.
3057 */
3058 fd = repo_hold_lock_file_for_update_timeout(r, &lock, config_filename, 0,
3059 config_lock_timeout_ms(r));
3060 if (fd < 0) {
3061 error_errno(_("could not lock config file %s"), config_filename);
3062 ret = CONFIG_NO_LOCK;
3063 goto out_free;
3064 }
3065
3066 /*
3067 * If .git/config does not exist yet, write a minimal version.
3068 */
3069 in_fd = open(config_filename, O_RDONLY);
3070 if ( in_fd < 0 ) {
3071 if ( ENOENT != errno ) {
3072 error_errno(_("opening %s"), config_filename);
3073 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3074 goto out_free;
3075 }
3076 /* if nothing to unset, error out */
3077 if (!value) {
3078 ret = CONFIG_NOTHING_SET;
3079 goto out_free;
3080 }
3081
3082 free(store.key);
3083 store.key = xstrdup(key);
3084 if (write_section(fd, key, &store) < 0 ||
3085 write_pair(fd, key, value, comment, &store) < 0)
3086 goto write_err_out;
3087 } else {
3088 struct stat st;
3089 size_t copy_begin, copy_end;
3090 unsigned i;
3091 int new_line = 0;
3092 struct config_options opts;
3093
3094 if (!value_pattern)
3095 store.value_pattern = NULL;
3096 else if (value_pattern == CONFIG_REGEX_NONE)
3097 store.value_pattern = CONFIG_REGEX_NONE;
3098 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3099 store.fixed_value = value_pattern;
3100 else {
3101 if (value_pattern[0] == '!') {
3102 store.do_not_match = 1;
3103 value_pattern++;
3104 } else
3105 store.do_not_match = 0;
3106
3107 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3108 if (regcomp(store.value_pattern, value_pattern,
3109 REG_EXTENDED)) {
3110 error(_("invalid pattern: %s"), value_pattern);
3111 FREE_AND_NULL(store.value_pattern);
3112 ret = CONFIG_INVALID_PATTERN;
3113 goto out_free;
3114 }
3115 }
3116
3117 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3118 store.parsed[0].end = 0;
3119
3120 memset(&opts, 0, sizeof(opts));
3121 opts.event_fn = store_aux_event;
3122 opts.event_fn_data = &store;
3123
3124 /*
3125 * After this, store.parsed will contain offsets of all the
3126 * parsed elements, and store.seen will contain a list of
3127 * matches, as indices into store.parsed.
3128 *
3129 * As a side effect, we make sure to transform only a valid
3130 * existing config file.
3131 */
3132 if (git_config_from_file_with_options(store_aux,
3133 config_filename,
3134 &store, CONFIG_SCOPE_UNKNOWN,
3135 &opts)) {
3136 error(_("invalid config file %s"), config_filename);
3137 ret = CONFIG_INVALID_FILE;
3138 goto out_free;
3139 }
3140
3141 /* if nothing to unset, or too many matches, error out */
3142 if ((store.seen_nr == 0 && value == NULL) ||
3143 (store.seen_nr > 1 && !store.multi_replace)) {
3144 ret = CONFIG_NOTHING_SET;
3145 goto out_free;
3146 }
3147
3148 if (fstat(in_fd, &st) == -1) {
3149 error_errno(_("fstat on %s failed"), config_filename);
3150 ret = CONFIG_INVALID_FILE;
3151 goto out_free;
3152 }
3153
3154 contents_sz = xsize_t(st.st_size);
3155 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3156 MAP_PRIVATE, in_fd, 0);
3157 if (contents == MAP_FAILED) {
3158 if (errno == ENODEV && S_ISDIR(st.st_mode))
3159 errno = EISDIR;
3160 error_errno(_("unable to mmap '%s'%s"),
3161 config_filename, mmap_os_err());
3162 ret = CONFIG_INVALID_FILE;
3163 contents = NULL;
3164 goto out_free;
3165 }
3166 close(in_fd);
3167 in_fd = -1;
3168
3169 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3170 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3171 ret = CONFIG_NO_WRITE;
3172 goto out_free;
3173 }
3174
3175 if (store.seen_nr == 0) {
3176 if (!store.seen_alloc) {
3177 /* Did not see key nor section */
3178 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3179 store.seen[0] = store.parsed_nr
3180 - !!store.parsed_nr;
3181 }
3182 store.seen_nr = 1;
3183 }
3184
3185 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3186 size_t replace_end;
3187 int j = store.seen[i];
3188
3189 new_line = 0;
3190 if (!store.key_seen) {
3191 copy_end = store.parsed[j].end;
3192 /* include '\n' when copying section header */
3193 if (copy_end > 0 && copy_end < contents_sz &&
3194 contents[copy_end - 1] != '\n' &&
3195 contents[copy_end] == '\n')
3196 copy_end++;
3197 replace_end = copy_end;
3198 } else {
3199 replace_end = store.parsed[j].end;
3200 copy_end = store.parsed[j].begin;
3201 if (!value)
3202 maybe_remove_section(&store,
3203 &copy_end,
3204 &replace_end, &i);
3205 /*
3206 * Swallow preceding white-space on the same
3207 * line.
3208 */
3209 while (copy_end > 0 ) {
3210 char c = contents[copy_end - 1];
3211
3212 if (isspace(c) && c != '\n')
3213 copy_end--;
3214 else
3215 break;
3216 }
3217 }
3218
3219 if (copy_end > 0 && contents[copy_end-1] != '\n')
3220 new_line = 1;
3221
3222 /* write the first part of the config */
3223 if (copy_end > copy_begin) {
3224 if (write_in_full(fd, contents + copy_begin,
3225 copy_end - copy_begin) < 0)
3226 goto write_err_out;
3227 if (new_line &&
3228 write_str_in_full(fd, "\n") < 0)
3229 goto write_err_out;
3230 }
3231 copy_begin = replace_end;
3232 }
3233
3234 /* write the pair (value == NULL means unset) */
3235 if (value) {
3236 if (!store.section_seen) {
3237 if (write_section(fd, key, &store) < 0)
3238 goto write_err_out;
3239 }
3240 if (write_pair(fd, key, value, comment, &store) < 0)
3241 goto write_err_out;
3242 }
3243
3244 /* write the rest of the config */
3245 if (copy_begin < contents_sz)
3246 if (write_in_full(fd, contents + copy_begin,
3247 contents_sz - copy_begin) < 0)
3248 goto write_err_out;
3249
3250 munmap(contents, contents_sz);
3251 contents = NULL;
3252 }
3253
3254 if (commit_lock_file(&lock) < 0) {
3255 error_errno(_("could not write config file %s"), config_filename);
3256 ret = CONFIG_NO_WRITE;
3257 goto out_free;
3258 }
3259
3260 ret = 0;
3261
3262 /* Invalidate the config cache */
3263 repo_config_clear(r);
3264
3265 out_free:
3266 rollback_lock_file(&lock);
3267 free(filename_buf);
3268 if (contents)
3269 munmap(contents, contents_sz);
3270 if (in_fd >= 0)
3271 close(in_fd);
3272 config_store_data_clear(&store);
3273 r->check_deprecated_config = saved_check_deprecated_config;
3274 return ret;
3275
3276 write_err_out:
3277 ret = write_error(get_lock_file_path(&lock));
3278 goto out_free;
3279 }
3280
3281 void repo_config_set_multivar_in_file(struct repository *r,
3282 const char *config_filename,
3283 const char *key, const char *value,
3284 const char *value_pattern, unsigned flags)
3285 {
3286 if (!repo_config_set_multivar_in_file_gently(r, config_filename, key, value,
3287 value_pattern, NULL, flags))
3288 return;
3289 if (value)
3290 die(_("could not set '%s' to '%s'"), key, value);
3291 else
3292 die(_("could not unset '%s'"), key);
3293 }
3294
3295 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3296 const char *value,
3297 const char *value_pattern, unsigned flags)
3298 {
3299 char *file = repo_git_path(r, "config");
3300 int res = repo_config_set_multivar_in_file_gently(r, file,
3301 key, value,
3302 value_pattern,
3303 NULL, flags);
3304 free(file);
3305 return res;
3306 }
3307
3308 void repo_config_set_multivar(struct repository *r,
3309 const char *key, const char *value,
3310 const char *value_pattern, unsigned flags)
3311 {
3312 char *file = repo_git_path(r, "config");
3313 repo_config_set_multivar_in_file(r, file, key, value,
3314 value_pattern, flags);
3315 free(file);
3316 }
3317
3318 static size_t section_name_match (const char *buf, const char *name)
3319 {
3320 size_t i = 0, j = 0;
3321 int dot = 0;
3322 if (buf[i] != '[')
3323 return 0;
3324 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3325 if (!dot && isspace(buf[i])) {
3326 dot = 1;
3327 if (name[j++] != '.')
3328 break;
3329 for (i++; isspace(buf[i]); i++)
3330 ; /* do nothing */
3331 if (buf[i] != '"')
3332 break;
3333 continue;
3334 }
3335 if (buf[i] == '\\' && dot)
3336 i++;
3337 else if (buf[i] == '"' && dot) {
3338 for (i++; isspace(buf[i]); i++)
3339 ; /* do_nothing */
3340 break;
3341 }
3342 if (buf[i] != name[j++])
3343 break;
3344 }
3345 if (buf[i] == ']' && name[j] == 0) {
3346 /*
3347 * We match, now just find the right length offset by
3348 * gobbling up any whitespace after it, as well
3349 */
3350 i++;
3351 for (; buf[i] && isspace(buf[i]); i++)
3352 ; /* do nothing */
3353 return i;
3354 }
3355 return 0;
3356 }
3357
3358 static int section_name_is_ok(const char *name)
3359 {
3360 /* Empty section names are bogus. */
3361 if (!*name)
3362 return 0;
3363
3364 /*
3365 * Before a dot, we must be alphanumeric or dash. After the first dot,
3366 * anything goes, so we can stop checking.
3367 */
3368 for (; *name && *name != '.'; name++)
3369 if (*name != '-' && !isalnum(*name))
3370 return 0;
3371 return 1;
3372 }
3373
3374 #define GIT_CONFIG_MAX_LINE_LEN (512 * 1024)
3375
3376 /* if new_name == NULL, the section is removed instead */
3377 static int repo_config_copy_or_rename_section_in_file(
3378 struct repository *r,
3379 const char *config_filename,
3380 const char *old_name,
3381 const char *new_name, int copy)
3382 {
3383 int ret = 0, remove = 0;
3384 char *filename_buf = NULL;
3385 struct lock_file lock = LOCK_INIT;
3386 int out_fd;
3387 struct strbuf buf = STRBUF_INIT;
3388 FILE *config_file = NULL;
3389 struct stat st;
3390 struct strbuf copystr = STRBUF_INIT;
3391 struct config_store_data store;
3392 uint32_t line_nr = 0;
3393
3394 memset(&store, 0, sizeof(store));
3395
3396 if (new_name && !section_name_is_ok(new_name)) {
3397 ret = error(_("invalid section name: %s"), new_name);
3398 goto out_no_rollback;
3399 }
3400
3401 if (!config_filename)
3402 config_filename = filename_buf = repo_git_path(r, "config");
3403
3404 out_fd = repo_hold_lock_file_for_update_timeout(r, &lock,
3405 config_filename, 0,
3406 config_lock_timeout_ms(r));
3407 if (out_fd < 0) {
3408 ret = error(_("could not lock config file %s"), config_filename);
3409 goto out;
3410 }
3411
3412 if (!(config_file = fopen(config_filename, "rb"))) {
3413 ret = warn_on_fopen_errors(config_filename);
3414 if (ret)
3415 goto out;
3416 /* no config file means nothing to rename, no error */
3417 goto commit_and_out;
3418 }
3419
3420 if (fstat(fileno(config_file), &st) == -1) {
3421 ret = error_errno(_("fstat on %s failed"), config_filename);
3422 goto out;
3423 }
3424
3425 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3426 ret = error_errno(_("chmod on %s failed"),
3427 get_lock_file_path(&lock));
3428 goto out;
3429 }
3430
3431 while (!strbuf_getwholeline(&buf, config_file, '\n')) {
3432 size_t i, length;
3433 int is_section = 0;
3434 char *output = buf.buf;
3435
3436 line_nr++;
3437
3438 if (buf.len >= GIT_CONFIG_MAX_LINE_LEN) {
3439 ret = error(_("refusing to work with overly long line "
3440 "in '%s' on line %"PRIuMAX),
3441 config_filename, (uintmax_t)line_nr);
3442 goto out;
3443 }
3444
3445 for (i = 0; buf.buf[i] && isspace(buf.buf[i]); i++)
3446 ; /* do nothing */
3447 if (buf.buf[i] == '[') {
3448 /* it's a section */
3449 size_t offset;
3450 is_section = 1;
3451
3452 /*
3453 * When encountering a new section under -c we
3454 * need to flush out any section we're already
3455 * coping and begin anew. There might be
3456 * multiple [branch "$name"] sections.
3457 */
3458 if (copystr.len > 0) {
3459 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3460 ret = write_error(get_lock_file_path(&lock));
3461 goto out;
3462 }
3463 strbuf_reset(&copystr);
3464 }
3465
3466 offset = section_name_match(&buf.buf[i], old_name);
3467 if (offset > 0) {
3468 ret++;
3469 if (!new_name) {
3470 remove = 1;
3471 continue;
3472 }
3473 store.baselen = strlen(new_name);
3474 if (!copy) {
3475 if (write_section(out_fd, new_name, &store) < 0) {
3476 ret = write_error(get_lock_file_path(&lock));
3477 goto out;
3478 }
3479 /*
3480 * We wrote out the new section, with
3481 * a newline, now skip the old
3482 * section's length
3483 */
3484 output += offset + i;
3485 if (strlen(output) > 0) {
3486 /*
3487 * More content means there's
3488 * a declaration to put on the
3489 * next line; indent with a
3490 * tab
3491 */
3492 output -= 1;
3493 output[0] = '\t';
3494 }
3495 } else {
3496 strbuf_release(&copystr);
3497 copystr = store_create_section(new_name, &store);
3498 }
3499 }
3500 remove = 0;
3501 }
3502 if (remove)
3503 continue;
3504 length = strlen(output);
3505
3506 if (!is_section && copystr.len > 0) {
3507 strbuf_add(&copystr, output, length);
3508 }
3509
3510 if (write_in_full(out_fd, output, length) < 0) {
3511 ret = write_error(get_lock_file_path(&lock));
3512 goto out;
3513 }
3514 }
3515
3516 /*
3517 * Copy a trailing section at the end of the config, won't be
3518 * flushed by the usual "flush because we have a new section
3519 * logic in the loop above.
3520 */
3521 if (copystr.len > 0) {
3522 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3523 ret = write_error(get_lock_file_path(&lock));
3524 goto out;
3525 }
3526 strbuf_reset(&copystr);
3527 }
3528
3529 fclose(config_file);
3530 config_file = NULL;
3531 commit_and_out:
3532 if (commit_lock_file(&lock) < 0)
3533 ret = error_errno(_("could not write config file %s"),
3534 config_filename);
3535 out:
3536 if (config_file)
3537 fclose(config_file);
3538 rollback_lock_file(&lock);
3539 out_no_rollback:
3540 free(filename_buf);
3541 config_store_data_clear(&store);
3542 strbuf_release(&buf);
3543 strbuf_release(&copystr);
3544 return ret;
3545 }
3546
3547 int repo_config_rename_section_in_file(struct repository *r, const char *config_filename,
3548 const char *old_name, const char *new_name)
3549 {
3550 return repo_config_copy_or_rename_section_in_file(r, config_filename,
3551 old_name, new_name, 0);
3552 }
3553
3554 int repo_config_rename_section(struct repository *r, const char *old_name, const char *new_name)
3555 {
3556 return repo_config_rename_section_in_file(r, NULL, old_name, new_name);
3557 }
3558
3559 int repo_config_copy_section_in_file(struct repository *r, const char *config_filename,
3560 const char *old_name, const char *new_name)
3561 {
3562 return repo_config_copy_or_rename_section_in_file(r, config_filename,
3563 old_name, new_name, 1);
3564 }
3565
3566 int repo_config_copy_section(struct repository *r, const char *old_name, const char *new_name)
3567 {
3568 return repo_config_copy_section_in_file(r, NULL, old_name, new_name);
3569 }
3570
3571 /*
3572 * Call this to report error for your variable that should not
3573 * get a boolean value (i.e. "[my] var" means "true").
3574 */
3575 #undef config_error_nonbool
3576 int config_error_nonbool(const char *var)
3577 {
3578 return error(_("missing value for '%s'"), var);
3579 }
3580
3581 int parse_config_key(const char *var,
3582 const char *section,
3583 const char **subsection, size_t *subsection_len,
3584 const char **key)
3585 {
3586 const char *dot;
3587
3588 /* Does it start with "section." ? */
3589 if (!skip_prefix(var, section, &var) || *var != '.')
3590 return -1;
3591
3592 /*
3593 * Find the key; we don't know yet if we have a subsection, but we must
3594 * parse backwards from the end, since the subsection may have dots in
3595 * it, too.
3596 */
3597 dot = strrchr(var, '.');
3598 *key = dot + 1;
3599
3600 /* Did we have a subsection at all? */
3601 if (dot == var) {
3602 if (subsection) {
3603 *subsection = NULL;
3604 *subsection_len = 0;
3605 }
3606 }
3607 else {
3608 if (!subsection)
3609 return -1;
3610 *subsection = var + 1;
3611 *subsection_len = dot - *subsection;
3612 }
3613
3614 return 0;
3615 }
3616
3617 const char *config_origin_type_name(enum config_origin_type type)
3618 {
3619 switch (type) {
3620 case CONFIG_ORIGIN_BLOB:
3621 return "blob";
3622 case CONFIG_ORIGIN_FILE:
3623 return "file";
3624 case CONFIG_ORIGIN_STDIN:
3625 return "standard input";
3626 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3627 return "submodule-blob";
3628 case CONFIG_ORIGIN_CMDLINE:
3629 return "command line";
3630 default:
3631 BUG("unknown config origin type");
3632 }
3633 }
3634
3635 const char *config_scope_name(enum config_scope scope)
3636 {
3637 switch (scope) {
3638 case CONFIG_SCOPE_SYSTEM:
3639 return "system";
3640 case CONFIG_SCOPE_GLOBAL:
3641 return "global";
3642 case CONFIG_SCOPE_LOCAL:
3643 return "local";
3644 case CONFIG_SCOPE_WORKTREE:
3645 return "worktree";
3646 case CONFIG_SCOPE_COMMAND:
3647 return "command";
3648 case CONFIG_SCOPE_SUBMODULE:
3649 return "submodule";
3650 default:
3651 return "unknown";
3652 }
3653 }
3654
3655 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3656 {
3657 int i;
3658
3659 for (i = 0; i < nr_mapping; i++) {
3660 const char *name = mapping[i];
3661
3662 if (name && !strcasecmp(var, name))
3663 return i;
3664 }
3665 return -1;
3666 }