at commit a0189536

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 size_t git_config_size_t(const char *name, const char *value,
1275 const struct key_value_info *kvi)
1276 {
1277 size_t ret;
1278 if (!git_parse_size_t(value, &ret))
1279 die_bad_number(name, value, kvi);
1280 return ret;
1281 }
1282
1283 double git_config_double(const char *name, const char *value,
1284 const struct key_value_info *kvi)
1285 {
1286 double ret;
1287 if (!git_parse_double(value, &ret))
1288 die_bad_number(name, value, kvi);
1289 return ret;
1290 }
1291
1292 int git_config_bool_or_int(const char *name, const char *value,
1293 const struct key_value_info *kvi, int *is_bool)
1294 {
1295 int v = git_parse_maybe_bool_text(value);
1296 if (0 <= v) {
1297 *is_bool = 1;
1298 return v;
1299 }
1300 *is_bool = 0;
1301 return git_config_int(name, value, kvi);
1302 }
1303
1304 int git_config_bool(const char *name, const char *value)
1305 {
1306 int v = git_parse_maybe_bool(value);
1307 if (v < 0)
1308 die(_("bad boolean config value '%s' for '%s'"), value, name);
1309 return v;
1310 }
1311
1312 int git_config_string(char **dest, const char *var, const char *value)
1313 {
1314 if (!value)
1315 return config_error_nonbool(var);
1316 *dest = xstrdup(value);
1317 return 0;
1318 }
1319
1320 int git_config_pathname(char **dest, const char *var, const char *value)
1321 {
1322 bool is_optional;
1323 char *path;
1324
1325 if (!value)
1326 return config_error_nonbool(var);
1327
1328 is_optional = skip_prefix(value, ":(optional)", &value);
1329 path = interpolate_path(value, 0);
1330 if (!path)
1331 die(_("failed to expand user dir in: '%s'"), value);
1332
1333 if (is_optional && is_missing_file(path)) {
1334 free(path);
1335 *dest = NULL;
1336 return 0;
1337 }
1338
1339 *dest = path;
1340 return 0;
1341 }
1342
1343 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1344 {
1345 if (!value)
1346 return config_error_nonbool(var);
1347 if (parse_expiry_date(value, timestamp))
1348 return error(_("'%s' for '%s' is not a valid timestamp"),
1349 value, var);
1350 return 0;
1351 }
1352
1353 int git_config_color(char *dest, const char *var, const char *value)
1354 {
1355 if (!value)
1356 return config_error_nonbool(var);
1357 if (color_parse(value, dest) < 0)
1358 return -1;
1359 return 0;
1360 }
1361
1362 /*
1363 * All source specific fields in the union, die_on_error, name and the callbacks
1364 * fgetc, ungetc, ftell of top need to be initialized before calling
1365 * this function.
1366 */
1367 static int do_config_from(struct config_source *top, config_fn_t fn,
1368 void *data, enum config_scope scope,
1369 const struct config_options *opts)
1370 {
1371 struct key_value_info kvi = KVI_INIT;
1372 int ret;
1373
1374 /* push config-file parsing state stack */
1375 top->linenr = 1;
1376 top->eof = 0;
1377 top->total_len = 0;
1378 strbuf_init(&top->value, 1024);
1379 strbuf_init(&top->var, 1024);
1380 kvi_from_source(top, scope, &kvi);
1381
1382 ret = git_parse_source(top, fn, &kvi, data, opts);
1383
1384 strbuf_release(&top->value);
1385 strbuf_release(&top->var);
1386
1387 return ret;
1388 }
1389
1390 static int do_config_from_file(config_fn_t fn,
1391 const enum config_origin_type origin_type,
1392 const char *name, FILE *f, void *data,
1393 enum config_scope scope,
1394 const struct config_options *opts)
1395 {
1396 struct config_source top = CONFIG_SOURCE_INIT;
1397 int ret;
1398
1399 if (origin_type == CONFIG_ORIGIN_FILE && (!name || !*name))
1400 BUG("missing filename for CONFIG_ORIGIN_FILE");
1401
1402 top.u.file = f;
1403 top.origin_type = origin_type;
1404 top.name = name;
1405 top.default_error_action = CONFIG_ERROR_DIE;
1406 top.do_fgetc = config_file_fgetc;
1407 top.do_ungetc = config_file_ungetc;
1408 top.do_ftell = config_file_ftell;
1409
1410 flockfile(f);
1411 ret = do_config_from(&top, fn, data, scope, opts);
1412 funlockfile(f);
1413 return ret;
1414 }
1415
1416 static int git_config_from_stdin(config_fn_t fn, void *data,
1417 enum config_scope scope)
1418 {
1419 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", stdin, data,
1420 scope, NULL);
1421 }
1422
1423 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1424 void *data, enum config_scope scope,
1425 const struct config_options *opts)
1426 {
1427 int ret = -1;
1428 FILE *f;
1429
1430 if (!filename)
1431 BUG("filename cannot be NULL");
1432 f = fopen_or_warn(filename, "r");
1433 if (f) {
1434 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
1435 f, data, scope, opts);
1436 fclose(f);
1437 }
1438 return ret;
1439 }
1440
1441 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1442 {
1443 return git_config_from_file_with_options(fn, filename, data,
1444 CONFIG_SCOPE_UNKNOWN, NULL);
1445 }
1446
1447 int git_config_from_mem(config_fn_t fn,
1448 const enum config_origin_type origin_type,
1449 const char *name, const char *buf, size_t len,
1450 void *data, enum config_scope scope,
1451 const struct config_options *opts)
1452 {
1453 struct config_source top = CONFIG_SOURCE_INIT;
1454
1455 top.u.buf.buf = buf;
1456 top.u.buf.len = len;
1457 top.u.buf.pos = 0;
1458 top.origin_type = origin_type;
1459 top.name = name;
1460 top.default_error_action = CONFIG_ERROR_ERROR;
1461 top.do_fgetc = config_buf_fgetc;
1462 top.do_ungetc = config_buf_ungetc;
1463 top.do_ftell = config_buf_ftell;
1464
1465 return do_config_from(&top, fn, data, scope, opts);
1466 }
1467
1468 int git_config_from_blob_oid(config_fn_t fn,
1469 const char *name,
1470 struct repository *repo,
1471 const struct object_id *oid,
1472 void *data,
1473 enum config_scope scope)
1474 {
1475 enum object_type type;
1476 char *buf;
1477 size_t size;
1478 int ret;
1479
1480 buf = odb_read_object(repo->objects, oid, &type, &size);
1481 if (!buf)
1482 return error(_("unable to load config blob object '%s'"), name);
1483 if (type != OBJ_BLOB) {
1484 free(buf);
1485 return error(_("reference '%s' does not point to a blob"), name);
1486 }
1487
1488 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
1489 data, scope, NULL);
1490 free(buf);
1491
1492 return ret;
1493 }
1494
1495 static int git_config_from_blob_ref(config_fn_t fn,
1496 struct repository *repo,
1497 const char *name,
1498 void *data,
1499 enum config_scope scope)
1500 {
1501 struct object_id oid;
1502
1503 if (repo_get_oid(repo, name, &oid) < 0)
1504 return error(_("unable to resolve config blob '%s'"), name);
1505 return git_config_from_blob_oid(fn, name, repo, &oid, data, scope);
1506 }
1507
1508 char *git_system_config(void)
1509 {
1510 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
1511 if (!system_config)
1512 system_config = system_path(ETC_GITCONFIG);
1513 normalize_path_copy(system_config, system_config);
1514 return system_config;
1515 }
1516
1517 char *git_global_config(void)
1518 {
1519 char *user_config, *xdg_config;
1520
1521 git_global_config_paths(&user_config, &xdg_config);
1522 if (!user_config) {
1523 free(xdg_config);
1524 return NULL;
1525 }
1526
1527 if (access_or_warn(user_config, R_OK, 0) && xdg_config &&
1528 !access_or_warn(xdg_config, R_OK, 0)) {
1529 free(user_config);
1530 return xdg_config;
1531 } else {
1532 free(xdg_config);
1533 return user_config;
1534 }
1535 }
1536
1537 void git_global_config_paths(char **user_out, char **xdg_out)
1538 {
1539 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
1540 char *xdg_config = NULL;
1541
1542 if (!user_config) {
1543 user_config = interpolate_path("~/.gitconfig", 0);
1544 xdg_config = xdg_config_home("config");
1545 }
1546
1547 *user_out = user_config;
1548 *xdg_out = xdg_config;
1549 }
1550
1551 int git_config_system(void)
1552 {
1553 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
1554 }
1555
1556 static int do_git_config_sequence(const struct config_options *opts,
1557 const struct repository *repo,
1558 config_fn_t fn, void *data)
1559 {
1560 int ret = 0;
1561 char *system_config = git_system_config();
1562 char *xdg_config = NULL;
1563 char *user_config = NULL;
1564 char *repo_config;
1565 char *worktree_config;
1566
1567 /*
1568 * Ensure that either:
1569 * - the git_dir and commondir are both set, or
1570 * - the git_dir and commondir are both NULL
1571 */
1572 if (!opts->git_dir != !opts->commondir)
1573 BUG("only one of commondir and git_dir is non-NULL");
1574
1575 if (opts->commondir) {
1576 repo_config = mkpathdup("%s/config", opts->commondir);
1577 worktree_config = mkpathdup("%s/config.worktree", opts->git_dir);
1578 } else {
1579 repo_config = NULL;
1580 worktree_config = NULL;
1581 }
1582
1583 if (git_config_system() && system_config &&
1584 !access_or_die(system_config, R_OK,
1585 opts->system_gently ? ACCESS_EACCES_OK : 0))
1586 ret += git_config_from_file_with_options(fn, system_config,
1587 data, CONFIG_SCOPE_SYSTEM,
1588 NULL);
1589
1590 git_global_config_paths(&user_config, &xdg_config);
1591
1592 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
1593 ret += git_config_from_file_with_options(fn, xdg_config, data,
1594 CONFIG_SCOPE_GLOBAL, NULL);
1595
1596 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
1597 ret += git_config_from_file_with_options(fn, user_config, data,
1598 CONFIG_SCOPE_GLOBAL, NULL);
1599
1600 if (!opts->ignore_repo && repo_config &&
1601 !access_or_die(repo_config, R_OK, 0))
1602 ret += git_config_from_file_with_options(fn, repo_config, data,
1603 CONFIG_SCOPE_LOCAL, NULL);
1604
1605 if (!opts->ignore_worktree && worktree_config &&
1606 repo && repo->repository_format_worktree_config &&
1607 !access_or_die(worktree_config, R_OK, 0)) {
1608 ret += git_config_from_file_with_options(fn, worktree_config, data,
1609 CONFIG_SCOPE_WORKTREE,
1610 NULL);
1611 }
1612
1613 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
1614 die(_("unable to parse command-line config"));
1615
1616 free(system_config);
1617 free(xdg_config);
1618 free(user_config);
1619 free(repo_config);
1620 free(worktree_config);
1621 return ret;
1622 }
1623
1624 int config_with_options(config_fn_t fn, void *data,
1625 const struct git_config_source *config_source,
1626 struct repository *repo,
1627 const struct config_options *opts)
1628 {
1629 struct config_include_data inc = CONFIG_INCLUDE_INIT;
1630 int ret;
1631
1632 if (opts->respect_includes) {
1633 inc.fn = fn;
1634 inc.data = data;
1635 inc.opts = opts;
1636 inc.repo = repo;
1637 inc.config_source = config_source;
1638 fn = git_config_include;
1639 data = &inc;
1640 }
1641
1642 /*
1643 * If we have a specific filename, use it. Otherwise, follow the
1644 * regular lookup sequence.
1645 */
1646 if (config_source && config_source->use_stdin) {
1647 ret = git_config_from_stdin(fn, data, config_source->scope);
1648 } else if (config_source && config_source->file) {
1649 ret = git_config_from_file_with_options(fn, config_source->file,
1650 data, config_source->scope,
1651 NULL);
1652 } else if (config_source && config_source->blob) {
1653 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
1654 data, config_source->scope);
1655 } else {
1656 ret = do_git_config_sequence(opts, repo, fn, data);
1657 }
1658
1659 if (inc.remote_urls) {
1660 string_list_clear(inc.remote_urls, 0);
1661 FREE_AND_NULL(inc.remote_urls);
1662 }
1663 return ret;
1664 }
1665
1666 static void configset_iter(struct config_set *set, config_fn_t fn, void *data)
1667 {
1668 int value_index;
1669 struct string_list *values;
1670 struct config_set_element *entry;
1671 struct configset_list *list = &set->list;
1672 struct config_context ctx = CONFIG_CONTEXT_INIT;
1673
1674 for (size_t i = 0; i < list->nr; i++) {
1675 entry = list->items[i].e;
1676 value_index = list->items[i].value_index;
1677 values = &entry->value_list;
1678
1679 ctx.kvi = values->items[value_index].util;
1680 if (fn(entry->key, values->items[value_index].string, &ctx, data) < 0)
1681 git_die_config_linenr(entry->key,
1682 ctx.kvi->filename,
1683 ctx.kvi->linenr);
1684 }
1685 }
1686
1687 void read_early_config(struct repository *repo, config_fn_t cb, void *data)
1688 {
1689 struct config_options opts = {0};
1690 struct strbuf commondir = STRBUF_INIT;
1691 struct strbuf gitdir = STRBUF_INIT;
1692
1693 opts.respect_includes = 1;
1694
1695 if (repo && repo->gitdir) {
1696 opts.commondir = repo_get_common_dir(repo);
1697 opts.git_dir = repo_get_git_dir(repo);
1698 /*
1699 * When setup_git_directory() was not yet asked to discover the
1700 * GIT_DIR, we ask discover_git_directory() to figure out whether there
1701 * is any repository config we should use (but unlike
1702 * setup_git_directory_gently(), no global state is changed, most
1703 * notably, the current working directory is still the same after the
1704 * call).
1705 */
1706 } else if (!discover_git_directory(&commondir, &gitdir)) {
1707 opts.commondir = commondir.buf;
1708 opts.git_dir = gitdir.buf;
1709 }
1710
1711 config_with_options(cb, data, NULL, NULL, &opts);
1712
1713 strbuf_release(&commondir);
1714 strbuf_release(&gitdir);
1715 }
1716
1717 void read_very_early_config(config_fn_t cb, void *data)
1718 {
1719 struct config_options opts = { 0 };
1720
1721 opts.respect_includes = 1;
1722 opts.ignore_repo = 1;
1723 opts.ignore_worktree = 1;
1724 opts.ignore_cmdline = 1;
1725 opts.system_gently = 1;
1726
1727 config_with_options(cb, data, NULL, NULL, &opts);
1728 }
1729
1730 RESULT_MUST_BE_USED
1731 static int configset_find_element(struct config_set *set, const char *key,
1732 struct config_set_element **dest)
1733 {
1734 struct config_set_element k;
1735 struct config_set_element *found_entry;
1736 char *normalized_key;
1737 int ret;
1738
1739 /*
1740 * `key` may come from the user, so normalize it before using it
1741 * for querying entries from the hashmap.
1742 */
1743 ret = git_config_parse_key(key, &normalized_key, NULL);
1744 if (ret)
1745 return ret;
1746
1747 hashmap_entry_init(&k.ent, strhash(normalized_key));
1748 k.key = normalized_key;
1749 found_entry = hashmap_get_entry(&set->config_hash, &k, ent, NULL);
1750 free(normalized_key);
1751 *dest = found_entry;
1752 return 0;
1753 }
1754
1755 static int configset_add_value(const struct key_value_info *kvi_p,
1756 struct config_set *set, const char *key,
1757 const char *value)
1758 {
1759 struct config_set_element *e;
1760 struct string_list_item *si;
1761 struct configset_list_item *l_item;
1762 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
1763 int ret;
1764
1765 ret = configset_find_element(set, key, &e);
1766 if (ret)
1767 return ret;
1768 /*
1769 * Since the keys are being fed by git_config*() callback mechanism, they
1770 * are already normalized. So simply add them without any further munging.
1771 */
1772 if (!e) {
1773 e = xmalloc(sizeof(*e));
1774 hashmap_entry_init(&e->ent, strhash(key));
1775 e->key = xstrdup(key);
1776 string_list_init_dup(&e->value_list);
1777 hashmap_add(&set->config_hash, &e->ent);
1778 }
1779 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
1780
1781 ALLOC_GROW(set->list.items, set->list.nr + 1, set->list.alloc);
1782 l_item = &set->list.items[set->list.nr++];
1783 l_item->e = e;
1784 l_item->value_index = e->value_list.nr - 1;
1785
1786 *kv_info = *kvi_p;
1787 si->util = kv_info;
1788
1789 return 0;
1790 }
1791
1792 static int config_set_element_cmp(const void *cmp_data UNUSED,
1793 const struct hashmap_entry *eptr,
1794 const struct hashmap_entry *entry_or_key,
1795 const void *keydata UNUSED)
1796 {
1797 const struct config_set_element *e1, *e2;
1798
1799 e1 = container_of(eptr, const struct config_set_element, ent);
1800 e2 = container_of(entry_or_key, const struct config_set_element, ent);
1801
1802 return strcmp(e1->key, e2->key);
1803 }
1804
1805 void git_configset_init(struct config_set *set)
1806 {
1807 hashmap_init(&set->config_hash, config_set_element_cmp, NULL, 0);
1808 set->hash_initialized = 1;
1809 set->list.nr = 0;
1810 set->list.alloc = 0;
1811 set->list.items = NULL;
1812 }
1813
1814 void git_configset_clear(struct config_set *set)
1815 {
1816 struct config_set_element *entry;
1817 struct hashmap_iter iter;
1818 if (!set->hash_initialized)
1819 return;
1820
1821 hashmap_for_each_entry(&set->config_hash, &iter, entry,
1822 ent /* member name */) {
1823 free(entry->key);
1824 string_list_clear(&entry->value_list, 1);
1825 }
1826 hashmap_clear_and_free(&set->config_hash, struct config_set_element, ent);
1827 set->hash_initialized = 0;
1828 free(set->list.items);
1829 set->list.nr = 0;
1830 set->list.alloc = 0;
1831 set->list.items = NULL;
1832 }
1833
1834 static int config_set_callback(const char *key, const char *value,
1835 const struct config_context *ctx,
1836 void *cb)
1837 {
1838 struct config_set *set = cb;
1839 configset_add_value(ctx->kvi, set, key, value);
1840 return 0;
1841 }
1842
1843 int git_configset_add_file(struct config_set *set, const char *filename)
1844 {
1845 return git_config_from_file(config_set_callback, filename, set);
1846 }
1847
1848 int git_configset_get_value(struct config_set *set, const char *key,
1849 const char **value, struct key_value_info *kvi)
1850 {
1851 const struct string_list *values = NULL;
1852 int ret;
1853 struct string_list_item item;
1854 /*
1855 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
1856 * queried key in the files of the configset, the value returned will be the last
1857 * value in the value list for that key.
1858 */
1859 if ((ret = git_configset_get_value_multi(set, key, &values)))
1860 return ret;
1861
1862 assert(values->nr > 0);
1863 item = values->items[values->nr - 1];
1864 *value = item.string;
1865 if (kvi)
1866 *kvi = *((struct key_value_info *)item.util);
1867 return 0;
1868 }
1869
1870 int git_configset_get_value_multi(struct config_set *set, const char *key,
1871 const struct string_list **dest)
1872 {
1873 struct config_set_element *e;
1874 int ret;
1875
1876 if ((ret = configset_find_element(set, key, &e)))
1877 return ret;
1878 else if (!e)
1879 return 1;
1880 *dest = &e->value_list;
1881
1882 return 0;
1883 }
1884
1885 static int check_multi_string(struct string_list_item *item, void *util)
1886 {
1887 return item->string ? 0 : config_error_nonbool(util);
1888 }
1889
1890 int git_configset_get_string_multi(struct config_set *cs, const char *key,
1891 const struct string_list **dest)
1892 {
1893 int ret;
1894
1895 if ((ret = git_configset_get_value_multi(cs, key, dest)))
1896 return ret;
1897 if ((ret = for_each_string_list((struct string_list *)*dest,
1898 check_multi_string, (void *)key)))
1899 return ret;
1900
1901 return 0;
1902 }
1903
1904 int git_configset_get(struct config_set *set, const char *key)
1905 {
1906 struct config_set_element *e;
1907 int ret;
1908
1909 if ((ret = configset_find_element(set, key, &e)))
1910 return ret;
1911 else if (!e)
1912 return 1;
1913 return 0;
1914 }
1915
1916 int git_configset_get_string(struct config_set *set, const char *key, char **dest)
1917 {
1918 const char *value;
1919 if (!git_configset_get_value(set, key, &value, NULL))
1920 return git_config_string(dest, key, value);
1921 else
1922 return 1;
1923 }
1924
1925 static int git_configset_get_string_tmp(struct config_set *set, const char *key,
1926 const char **dest)
1927 {
1928 const char *value;
1929 if (!git_configset_get_value(set, key, &value, NULL)) {
1930 if (!value)
1931 return config_error_nonbool(key);
1932 *dest = value;
1933 return 0;
1934 } else {
1935 return 1;
1936 }
1937 }
1938
1939 int git_configset_get_int(struct config_set *set, const char *key, int *dest)
1940 {
1941 const char *value;
1942 struct key_value_info kvi;
1943
1944 if (!git_configset_get_value(set, key, &value, &kvi)) {
1945 *dest = git_config_int(key, value, &kvi);
1946 return 0;
1947 } else
1948 return 1;
1949 }
1950
1951 int git_configset_get_uint(struct config_set *set, const char *key, unsigned int *dest)
1952 {
1953 const char *value;
1954 struct key_value_info kvi;
1955
1956 if (!git_configset_get_value(set, key, &value, &kvi)) {
1957 *dest = git_config_uint(key, value, &kvi);
1958 return 0;
1959 } else
1960 return 1;
1961 }
1962
1963 int git_configset_get_ulong(struct config_set *set, const char *key, unsigned long *dest)
1964 {
1965 const char *value;
1966 struct key_value_info kvi;
1967
1968 if (!git_configset_get_value(set, key, &value, &kvi)) {
1969 *dest = git_config_ulong(key, value, &kvi);
1970 return 0;
1971 } else
1972 return 1;
1973 }
1974
1975 int git_configset_get_bool(struct config_set *set, const char *key, int *dest)
1976 {
1977 const char *value;
1978 if (!git_configset_get_value(set, key, &value, NULL)) {
1979 *dest = git_config_bool(key, value);
1980 return 0;
1981 } else
1982 return 1;
1983 }
1984
1985 int git_configset_get_bool_or_int(struct config_set *set, const char *key,
1986 int *is_bool, int *dest)
1987 {
1988 const char *value;
1989 struct key_value_info kvi;
1990
1991 if (!git_configset_get_value(set, key, &value, &kvi)) {
1992 *dest = git_config_bool_or_int(key, value, &kvi, is_bool);
1993 return 0;
1994 } else
1995 return 1;
1996 }
1997
1998 int git_configset_get_maybe_bool(struct config_set *set, const char *key, int *dest)
1999 {
2000 const char *value;
2001 if (!git_configset_get_value(set, key, &value, NULL)) {
2002 *dest = git_parse_maybe_bool(value);
2003 if (*dest == -1)
2004 return -1;
2005 return 0;
2006 } else
2007 return 1;
2008 }
2009
2010 static int git_configset_get_pathname(struct config_set *set, const char *key, char **dest)
2011 {
2012 const char *value;
2013 if (!git_configset_get_value(set, key, &value, NULL))
2014 return git_config_pathname(dest, key, value);
2015 else
2016 return 1;
2017 }
2018
2019 struct comment_char_config {
2020 unsigned last_key_id;
2021 bool auto_set;
2022 bool auto_set_in_file;
2023 struct strintmap key_flags;
2024 size_t alloc, nr;
2025 struct comment_char_config_item {
2026 unsigned key_id;
2027 char *path;
2028 enum config_scope scope;
2029 } *item;
2030 };
2031
2032 #define COMMENT_CHAR_CFG_INIT { \
2033 .key_flags = STRINTMAP_INIT, \
2034 }
2035
2036 static void comment_char_config_release(struct comment_char_config *config)
2037 {
2038 strintmap_clear(&config->key_flags);
2039 for (size_t i = 0; i < config->nr; i++)
2040 free(config->item[i].path);
2041 free(config->item);
2042 }
2043
2044 /* Used to track whether the key occurs more than once in a given file */
2045 #define KEY_SEEN_ONCE 1u
2046 #define KEY_SEEN_TWICE 2u
2047 #define COMMENT_KEY_SHIFT(id) (2 * (id))
2048 #define COMMENT_KEY_MASK(id) (3u << COMMENT_KEY_SHIFT(id))
2049
2050 static void set_comment_key_flags(struct comment_char_config *config,
2051 const char *path, unsigned id, unsigned value)
2052 {
2053 unsigned old = strintmap_get(&config->key_flags, path);
2054 unsigned new = (old & ~COMMENT_KEY_MASK(id)) |
2055 value << COMMENT_KEY_SHIFT(id);
2056
2057 strintmap_set(&config->key_flags, path, new);
2058 }
2059
2060 static unsigned get_comment_key_flags(struct comment_char_config *config,
2061 const char *path, unsigned id)
2062 {
2063 unsigned value = strintmap_get(&config->key_flags, path);
2064
2065 return (value & COMMENT_KEY_MASK(id)) >> COMMENT_KEY_SHIFT(id);
2066 }
2067
2068 static const char *comment_key_name(unsigned id)
2069 {
2070 static const char *name[] = {
2071 "core.commentChar",
2072 "core.commentString",
2073 };
2074
2075 if (id >= ARRAY_SIZE(name))
2076 BUG("invalid comment key id");
2077
2078 return name[id];
2079 }
2080
2081 static void comment_char_callback(const char *key, const char *value,
2082 const struct config_context *ctx, void *data)
2083 {
2084 struct comment_char_config *config = data;
2085 const struct key_value_info *kvi = ctx->kvi;
2086 unsigned key_id;
2087
2088 if (!strcmp(key, "core.commentchar"))
2089 key_id = 0;
2090 else if (!strcmp(key, "core.commentstring"))
2091 key_id = 1;
2092 else
2093 return;
2094
2095 config->last_key_id = key_id;
2096 config->auto_set = value && !strcmp(value, "auto");
2097 if (kvi->origin_type != CONFIG_ORIGIN_FILE) {
2098 return;
2099 } else if (get_comment_key_flags(config, kvi->filename, key_id)) {
2100 set_comment_key_flags(config, kvi->filename, key_id,
2101 KEY_SEEN_TWICE);
2102 } else {
2103 struct comment_char_config_item *item;
2104
2105 ALLOC_GROW_BY(config->item, config->nr, 1, config->alloc);
2106 item = &config->item[config->nr - 1];
2107 item->key_id = key_id;
2108 item->scope = kvi->scope;
2109 item->path = xstrdup(kvi->filename);
2110 set_comment_key_flags(config, kvi->filename, key_id,
2111 KEY_SEEN_ONCE);
2112 }
2113 config->auto_set_in_file = config->auto_set;
2114 }
2115
2116 static void add_config_scope_arg(struct repository *repo, struct strbuf *buf,
2117 struct comment_char_config_item *item)
2118 {
2119 char *global_config = git_global_config();
2120 char *system_config = git_system_config();
2121
2122 if (item->scope == CONFIG_SCOPE_SYSTEM && access(item->path, W_OK)) {
2123 /*
2124 * If the user cannot write to the system config recommend
2125 * setting the global config instead.
2126 */
2127 strbuf_addstr(buf, "--global ");
2128 } else if (fspatheq(item->path, system_config)) {
2129 strbuf_addstr(buf, "--system ");
2130 } else if (fspatheq(item->path, global_config)) {
2131 strbuf_addstr(buf, "--global ");
2132 } else if (fspatheq(item->path,
2133 mkpath("%s/config",
2134 repo_get_git_dir(repo)))) {
2135 ; /* --local is the default */
2136 } else if (fspatheq(item->path,
2137 mkpath("%s/config.worktree",
2138 repo_get_common_dir(repo)))) {
2139 strbuf_addstr(buf, "--worktree ");
2140 } else {
2141 const char *path = item->path;
2142 const char *home = getenv("HOME");
2143
2144 strbuf_addstr(buf, "--file ");
2145 if (home && !fspathncmp(path, home, strlen(home))) {
2146 path += strlen(home);
2147 if (!fspathncmp(path, "/", 1))
2148 path++;
2149 strbuf_addstr(buf, "~/");
2150 }
2151 sq_quote_buf_pretty(buf, path);
2152 strbuf_addch(buf, ' ');
2153 }
2154
2155 free(global_config);
2156 free(system_config);
2157 }
2158
2159 static bool can_unset_comment_char_config(struct comment_char_config *config)
2160 {
2161 for (size_t i = 0; i < config->nr; i++) {
2162 struct comment_char_config_item *item = &config->item[i];
2163
2164 if (item->scope == CONFIG_SCOPE_SYSTEM &&
2165 access(item->path, W_OK))
2166 return false;
2167 }
2168
2169 return true;
2170 }
2171
2172 static void add_unset_auto_comment_char_advice(struct repository *repo,
2173 struct comment_char_config *config)
2174 {
2175 struct strbuf buf = STRBUF_INIT;
2176
2177 if (!can_unset_comment_char_config(config))
2178 return;
2179
2180 for (size_t i = 0; i < config->nr; i++) {
2181 struct comment_char_config_item *item = &config->item[i];
2182
2183 strbuf_addstr(&buf, " git config unset ");
2184 add_config_scope_arg(repo, &buf, item);
2185 if (get_comment_key_flags(config, item->path, item->key_id) == KEY_SEEN_TWICE)
2186 strbuf_addstr(&buf, "--all ");
2187 strbuf_addf(&buf, "%s\n", comment_key_name(item->key_id));
2188 }
2189 advise(_("\nTo use the default comment string (#) please run\n\n%s"),
2190 buf.buf);
2191 strbuf_release(&buf);
2192 }
2193
2194 static void add_comment_char_advice(struct repository *repo,
2195 struct comment_char_config *config)
2196 {
2197 struct strbuf buf = STRBUF_INIT;
2198 struct comment_char_config_item *item;
2199 /* TRANSLATORS this is a place holder for the value of core.commentString */
2200 const char *placeholder = _("<comment string>");
2201
2202 /*
2203 * If auto is set in the last file that we saw advise the user how to
2204 * update their config.
2205 */
2206 if (!config->auto_set_in_file)
2207 return;
2208
2209 add_unset_auto_comment_char_advice(repo, config);
2210 item = &config->item[config->nr - 1];
2211 strbuf_reset(&buf);
2212 strbuf_addstr(&buf, " git config set ");
2213 add_config_scope_arg(repo, &buf, item);
2214 strbuf_addf(&buf, "%s %s\n", comment_key_name(item->key_id),
2215 placeholder);
2216 advise(_("\nTo set a custom comment string please run\n\n"
2217 "%s\nwhere '%s' is the string you wish to use.\n"),
2218 buf.buf, placeholder);
2219 strbuf_release(&buf);
2220 }
2221
2222 #undef KEY_SEEN_ONCE
2223 #undef KEY_SEEN_TWICE
2224 #undef COMMENT_KEY_SHIFT
2225 #undef COMMENT_KEY_MASK
2226
2227 struct repo_config {
2228 struct repository *repo;
2229 struct comment_char_config comment_char_config;
2230 };
2231
2232 #define REPO_CONFIG_INIT(repo_) { \
2233 .comment_char_config = COMMENT_CHAR_CFG_INIT, \
2234 .repo = repo_, \
2235 };
2236
2237 static void repo_config_release(struct repo_config *config)
2238 {
2239 comment_char_config_release(&config->comment_char_config);
2240 }
2241
2242 #ifdef WITH_BREAKING_CHANGES
2243 static void check_auto_comment_char_config(struct repository *repo,
2244 struct comment_char_config *config)
2245 {
2246 if (!config->auto_set)
2247 return;
2248
2249 die_message(_("Support for '%s=auto' has been removed in Git 3.0"),
2250 comment_key_name(config->last_key_id));
2251 add_comment_char_advice(repo, config);
2252 die(NULL);
2253 }
2254 #else
2255 static void check_auto_comment_char_config(struct repository *repo,
2256 struct comment_char_config *config)
2257 {
2258 extern bool warn_on_auto_comment_char;
2259 const char *DEPRECATED_CONFIG_ENV =
2260 "GIT_AUTO_COMMENT_CHAR_CONFIG_WARNING_GIVEN";
2261
2262 if (!config->auto_set || !warn_on_auto_comment_char)
2263 return;
2264
2265 /*
2266 * Use an environment variable to ensure that subprocesses do not repeat
2267 * the warning.
2268 */
2269 if (git_env_bool(DEPRECATED_CONFIG_ENV, false))
2270 return;
2271
2272 setenv(DEPRECATED_CONFIG_ENV, "true", true);
2273
2274 warning(_("Support for '%s=auto' is deprecated and will be removed in "
2275 "Git 3.0"), comment_key_name(config->last_key_id));
2276 add_comment_char_advice(repo, config);
2277 }
2278 #endif /* WITH_BREAKING_CHANGES */
2279
2280 static void check_deprecated_config(struct repo_config *config)
2281 {
2282 if (!config->repo->check_deprecated_config)
2283 return;
2284
2285 check_auto_comment_char_config(config->repo,
2286 &config->comment_char_config);
2287 }
2288
2289 static int repo_config_callback(const char *key, const char *value,
2290 const struct config_context *ctx, void *data)
2291 {
2292 struct repo_config *config = data;
2293
2294 comment_char_callback(key, value, ctx, &config->comment_char_config);
2295 return config_set_callback(key, value, ctx, config->repo->config);
2296 }
2297
2298 /* Functions use to read configuration from a repository */
2299 static void repo_read_config(struct repository *repo)
2300 {
2301 struct config_options opts = { 0 };
2302 struct repo_config config = REPO_CONFIG_INIT(repo);
2303
2304 opts.respect_includes = 1;
2305 opts.commondir = repo->commondir;
2306 opts.git_dir = repo->gitdir;
2307
2308 if (!repo->config)
2309 CALLOC_ARRAY(repo->config, 1);
2310 else
2311 git_configset_clear(repo->config);
2312
2313 git_configset_init(repo->config);
2314 if (config_with_options(repo_config_callback, &config, NULL, repo,
2315 &opts) < 0)
2316 /*
2317 * config_with_options() normally returns only
2318 * zero, as most errors are fatal, and
2319 * non-fatal potential errors are guarded by "if"
2320 * statements that are entered only when no error is
2321 * possible.
2322 *
2323 * If we ever encounter a non-fatal error, it means
2324 * something went really wrong and we should stop
2325 * immediately.
2326 */
2327 die(_("unknown error occurred while reading the configuration files"));
2328 check_deprecated_config(&config);
2329 repo_config_release(&config);
2330 }
2331
2332 static void git_config_check_init(struct repository *repo)
2333 {
2334 if (repo->config && repo->config->hash_initialized)
2335 return;
2336 repo_read_config(repo);
2337 }
2338
2339 void repo_config_clear(struct repository *repo)
2340 {
2341 if (!repo->config || !repo->config->hash_initialized)
2342 return;
2343 git_configset_clear(repo->config);
2344 }
2345
2346 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2347 {
2348 if (!repo) {
2349 read_very_early_config(fn, data);
2350 return;
2351 }
2352 git_config_check_init(repo);
2353 configset_iter(repo->config, fn, data);
2354 }
2355
2356 int repo_config_get(struct repository *repo, const char *key)
2357 {
2358 git_config_check_init(repo);
2359 return git_configset_get(repo->config, key);
2360 }
2361
2362 int repo_config_get_value(struct repository *repo,
2363 const char *key, const char **value)
2364 {
2365 git_config_check_init(repo);
2366 return git_configset_get_value(repo->config, key, value, NULL);
2367 }
2368
2369 int repo_config_get_value_multi(struct repository *repo, const char *key,
2370 const struct string_list **dest)
2371 {
2372 git_config_check_init(repo);
2373 return git_configset_get_value_multi(repo->config, key, dest);
2374 }
2375
2376 int repo_config_get_string_multi(struct repository *repo, const char *key,
2377 const struct string_list **dest)
2378 {
2379 git_config_check_init(repo);
2380 return git_configset_get_string_multi(repo->config, key, dest);
2381 }
2382
2383 int repo_config_get_string(struct repository *repo,
2384 const char *key, char **dest)
2385 {
2386 int ret;
2387 git_config_check_init(repo);
2388 ret = git_configset_get_string(repo->config, key, dest);
2389 if (ret < 0)
2390 git_die_config(repo, key, NULL);
2391 return ret;
2392 }
2393
2394 int repo_config_get_string_tmp(struct repository *repo,
2395 const char *key, const char **dest)
2396 {
2397 int ret;
2398 git_config_check_init(repo);
2399 ret = git_configset_get_string_tmp(repo->config, key, dest);
2400 if (ret < 0)
2401 git_die_config(repo, key, NULL);
2402 return ret;
2403 }
2404
2405 int repo_config_get_int(struct repository *repo,
2406 const char *key, int *dest)
2407 {
2408 git_config_check_init(repo);
2409 return git_configset_get_int(repo->config, key, dest);
2410 }
2411
2412 int repo_config_get_uint(struct repository *repo,
2413 const char *key, unsigned int *dest)
2414 {
2415 git_config_check_init(repo);
2416 return git_configset_get_uint(repo->config, key, dest);
2417 }
2418
2419 int repo_config_get_ulong(struct repository *repo,
2420 const char *key, unsigned long *dest)
2421 {
2422 git_config_check_init(repo);
2423 return git_configset_get_ulong(repo->config, key, dest);
2424 }
2425
2426 int repo_config_get_bool(struct repository *repo,
2427 const char *key, int *dest)
2428 {
2429 git_config_check_init(repo);
2430 return git_configset_get_bool(repo->config, key, dest);
2431 }
2432
2433 int repo_config_get_bool_or_int(struct repository *repo,
2434 const char *key, int *is_bool, int *dest)
2435 {
2436 git_config_check_init(repo);
2437 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2438 }
2439
2440 int repo_config_get_maybe_bool(struct repository *repo,
2441 const char *key, int *dest)
2442 {
2443 git_config_check_init(repo);
2444 return git_configset_get_maybe_bool(repo->config, key, dest);
2445 }
2446
2447 int repo_config_get_pathname(struct repository *repo,
2448 const char *key, char **dest)
2449 {
2450 int ret;
2451 git_config_check_init(repo);
2452 ret = git_configset_get_pathname(repo->config, key, dest);
2453 if (ret < 0)
2454 git_die_config(repo, key, NULL);
2455 return ret;
2456 }
2457
2458 /* Read values into protected_config. */
2459 static void read_protected_config(void)
2460 {
2461 struct config_options opts = {
2462 .respect_includes = 1,
2463 .ignore_repo = 1,
2464 .ignore_worktree = 1,
2465 .system_gently = 1,
2466 };
2467
2468 git_configset_init(&protected_config);
2469 config_with_options(config_set_callback, &protected_config, NULL,
2470 NULL, &opts);
2471 }
2472
2473 void git_protected_config(config_fn_t fn, void *data)
2474 {
2475 if (!protected_config.hash_initialized)
2476 read_protected_config();
2477 configset_iter(&protected_config, fn, data);
2478 }
2479
2480 int repo_config_get_expiry(struct repository *r, const char *key, char **output)
2481 {
2482 int ret = repo_config_get_string(r, key, output);
2483
2484 if (ret)
2485 return ret;
2486 if (strcmp(*output, "now")) {
2487 timestamp_t now = approxidate("now");
2488 if (approxidate(*output) >= now)
2489 git_die_config(r, key, _("Invalid %s: '%s'"), key, *output);
2490 }
2491 return ret;
2492 }
2493
2494 int repo_config_get_expiry_in_days(struct repository *r, const char *key,
2495 timestamp_t *expiry, timestamp_t now)
2496 {
2497 const char *expiry_string;
2498 int days;
2499 timestamp_t when;
2500
2501 if (repo_config_get_string_tmp(r, key, &expiry_string))
2502 return 1; /* no such thing */
2503
2504 if (git_parse_int(expiry_string, &days)) {
2505 const intmax_t scale = 86400;
2506 *expiry = now - days * scale;
2507 return 0;
2508 }
2509
2510 if (!parse_expiry_date(expiry_string, &when)) {
2511 *expiry = when;
2512 return 0;
2513 }
2514 return -1; /* thing exists but cannot be parsed */
2515 }
2516
2517 int repo_config_get_split_index(struct repository *r)
2518 {
2519 int val;
2520
2521 if (!repo_config_get_maybe_bool(r, "core.splitindex", &val))
2522 return val;
2523
2524 return -1; /* default value */
2525 }
2526
2527 int repo_config_get_max_percent_split_change(struct repository *r)
2528 {
2529 int val = -1;
2530
2531 if (!repo_config_get_int(r, "splitindex.maxpercentchange", &val)) {
2532 if (0 <= val && val <= 100)
2533 return val;
2534
2535 return error(_("splitIndex.maxPercentChange value '%d' "
2536 "should be between 0 and 100"), val);
2537 }
2538
2539 return -1; /* default value */
2540 }
2541
2542 int repo_config_get_index_threads(struct repository *r, int *dest)
2543 {
2544 int is_bool, val;
2545
2546 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2547 if (val) {
2548 *dest = val;
2549 return 0;
2550 }
2551
2552 if (!repo_config_get_bool_or_int(r, "index.threads", &is_bool, &val)) {
2553 if (is_bool)
2554 *dest = val ? 0 : 1;
2555 else
2556 *dest = val;
2557 return 0;
2558 }
2559
2560 return 1;
2561 }
2562
2563 NORETURN
2564 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2565 {
2566 if (!filename)
2567 die(_("unable to parse '%s' from command-line config"), key);
2568 else
2569 die(_("bad config variable '%s' in file '%s' at line %d"),
2570 key, filename, linenr);
2571 }
2572
2573 void git_die_config(struct repository *r, const char *key, const char *err, ...)
2574 {
2575 const struct string_list *values;
2576 struct key_value_info *kv_info;
2577 report_fn error_fn = get_error_routine();
2578
2579 if (err) {
2580 va_list params;
2581 va_start(params, err);
2582 error_fn(err, params);
2583 va_end(params);
2584 }
2585 if (repo_config_get_value_multi(r, key, &values))
2586 BUG("for key '%s' we must have a value to report on", key);
2587 kv_info = values->items[values->nr - 1].util;
2588 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2589 }
2590
2591 /*
2592 * Find all the stuff for repo_config_set() below.
2593 */
2594
2595 struct config_store_data {
2596 size_t baselen;
2597 char *key;
2598 int do_not_match;
2599 const char *fixed_value;
2600 regex_t *value_pattern;
2601 int multi_replace;
2602 struct {
2603 size_t begin, end;
2604 enum config_event_t type;
2605 int is_keys_section;
2606 } *parsed;
2607 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2608 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2609 };
2610 #define CONFIG_STORE_INIT { 0 }
2611
2612 static void config_store_data_clear(struct config_store_data *store)
2613 {
2614 free(store->key);
2615 if (store->value_pattern != NULL &&
2616 store->value_pattern != CONFIG_REGEX_NONE) {
2617 regfree(store->value_pattern);
2618 free(store->value_pattern);
2619 }
2620 free(store->parsed);
2621 free(store->seen);
2622 memset(store, 0, sizeof(*store));
2623 }
2624
2625 static int matches(const char *key, const char *value,
2626 const struct config_store_data *store)
2627 {
2628 if (strcmp(key, store->key))
2629 return 0; /* not ours */
2630 if (store->fixed_value && value)
2631 return !strcmp(store->fixed_value, value);
2632 if (!store->value_pattern)
2633 return 1; /* always matches */
2634 if (store->value_pattern == CONFIG_REGEX_NONE)
2635 return 0; /* never matches */
2636
2637 return store->do_not_match ^
2638 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2639 }
2640
2641 static int store_aux_event(enum config_event_t type, size_t begin, size_t end,
2642 struct config_source *cs, void *data)
2643 {
2644 struct config_store_data *store = data;
2645
2646 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2647 store->parsed[store->parsed_nr].begin = begin;
2648 store->parsed[store->parsed_nr].end = end;
2649 store->parsed[store->parsed_nr].type = type;
2650
2651 if (type == CONFIG_EVENT_SECTION) {
2652 int (*cmpfn)(const char *, const char *, size_t);
2653
2654 if (cs->var.len < 2 || cs->var.buf[cs->var.len - 1] != '.')
2655 return error(_("invalid section name '%s'"), cs->var.buf);
2656
2657 if (cs->subsection_case_sensitive)
2658 cmpfn = strncasecmp;
2659 else
2660 cmpfn = strncmp;
2661
2662 /* Is this the section we were looking for? */
2663 store->is_keys_section =
2664 store->parsed[store->parsed_nr].is_keys_section =
2665 cs->var.len - 1 == store->baselen &&
2666 !cmpfn(cs->var.buf, store->key, store->baselen);
2667 if (store->is_keys_section) {
2668 store->section_seen = 1;
2669 ALLOC_GROW(store->seen, store->seen_nr + 1,
2670 store->seen_alloc);
2671 store->seen[store->seen_nr] = store->parsed_nr;
2672 }
2673 }
2674
2675 store->parsed_nr++;
2676
2677 return 0;
2678 }
2679
2680 static int store_aux(const char *key, const char *value,
2681 const struct config_context *ctx UNUSED, void *cb)
2682 {
2683 struct config_store_data *store = cb;
2684
2685 if (store->key_seen) {
2686 if (matches(key, value, store)) {
2687 if (store->seen_nr == 1 && store->multi_replace == 0) {
2688 warning(_("%s has multiple values"), key);
2689 }
2690
2691 ALLOC_GROW(store->seen, store->seen_nr + 1,
2692 store->seen_alloc);
2693
2694 store->seen[store->seen_nr] = store->parsed_nr;
2695 store->seen_nr++;
2696 }
2697 } else if (store->is_keys_section) {
2698 /*
2699 * Do not increment matches yet: this may not be a match, but we
2700 * are in the desired section.
2701 */
2702 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2703 store->seen[store->seen_nr] = store->parsed_nr;
2704 store->section_seen = 1;
2705
2706 if (matches(key, value, store)) {
2707 store->seen_nr++;
2708 store->key_seen = 1;
2709 }
2710 }
2711
2712 return 0;
2713 }
2714
2715 static int write_error(const char *filename)
2716 {
2717 error(_("failed to write new configuration file %s"), filename);
2718
2719 /* Same error code as "failed to rename". */
2720 return 4;
2721 }
2722
2723 static struct strbuf store_create_section(const char *key,
2724 const struct config_store_data *store)
2725 {
2726 const char *dot;
2727 size_t i;
2728 struct strbuf sb = STRBUF_INIT;
2729
2730 dot = memchr(key, '.', store->baselen);
2731 if (dot) {
2732 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2733 for (i = dot - key + 1; i < store->baselen; i++) {
2734 if (key[i] == '"' || key[i] == '\\')
2735 strbuf_addch(&sb, '\\');
2736 strbuf_addch(&sb, key[i]);
2737 }
2738 strbuf_addstr(&sb, "\"]\n");
2739 } else {
2740 strbuf_addch(&sb, '[');
2741 strbuf_add(&sb, key, store->baselen);
2742 strbuf_addstr(&sb, "]\n");
2743 }
2744
2745 return sb;
2746 }
2747
2748 static ssize_t write_section(int fd, const char *key,
2749 const struct config_store_data *store)
2750 {
2751 struct strbuf sb = store_create_section(key, store);
2752 ssize_t ret;
2753
2754 ret = write_in_full(fd, sb.buf, sb.len);
2755 strbuf_release(&sb);
2756
2757 return ret;
2758 }
2759
2760 static ssize_t write_pair(int fd, const char *key, const char *value,
2761 const char *comment,
2762 const struct config_store_data *store)
2763 {
2764 int i;
2765 ssize_t ret;
2766 const char *quote = "";
2767 struct strbuf sb = STRBUF_INIT;
2768
2769 /*
2770 * Check to see if the value needs to be surrounded with a dq pair.
2771 * Note that problematic characters are always backslash-quoted; this
2772 * check is about not losing leading or trailing SP and strings that
2773 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2774 * configuration parser.
2775 */
2776 if (value[0] == ' ')
2777 quote = "\"";
2778 for (i = 0; value[i]; i++)
2779 if (value[i] == ';' || value[i] == '#' || value[i] == '\r')
2780 quote = "\"";
2781 if (i && value[i - 1] == ' ')
2782 quote = "\"";
2783
2784 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
2785
2786 for (i = 0; value[i]; i++)
2787 switch (value[i]) {
2788 case '\n':
2789 strbuf_addstr(&sb, "\\n");
2790 break;
2791 case '\t':
2792 strbuf_addstr(&sb, "\\t");
2793 break;
2794 case '"':
2795 case '\\':
2796 strbuf_addch(&sb, '\\');
2797 /* fallthrough */
2798 default:
2799 strbuf_addch(&sb, value[i]);
2800 break;
2801 }
2802
2803 if (comment)
2804 strbuf_addf(&sb, "%s%s\n", quote, comment);
2805 else
2806 strbuf_addf(&sb, "%s\n", quote);
2807
2808 ret = write_in_full(fd, sb.buf, sb.len);
2809 strbuf_release(&sb);
2810
2811 return ret;
2812 }
2813
2814 /*
2815 * If we are about to unset the last key(s) in a section, and if there are
2816 * no comments surrounding (or included in) the section, we will want to
2817 * extend begin/end to remove the entire section.
2818 *
2819 * Note: the parameter `seen_ptr` points to the index into the store.seen
2820 * array. * This index may be incremented if a section has more than one
2821 * entry (which all are to be removed).
2822 */
2823 static void maybe_remove_section(struct config_store_data *store,
2824 size_t *begin_offset, size_t *end_offset,
2825 unsigned *seen_ptr)
2826 {
2827 size_t begin;
2828 int section_seen = 0;
2829 unsigned int i, seen;
2830
2831 /*
2832 * First, ensure that this is the first key, and that there are no
2833 * comments before the entry nor before the section header.
2834 */
2835 seen = *seen_ptr;
2836 for (i = store->seen[seen]; i > 0; i--) {
2837 enum config_event_t type = store->parsed[i - 1].type;
2838
2839 if (type == CONFIG_EVENT_COMMENT)
2840 /* There is a comment before this entry or section */
2841 return;
2842 if (type == CONFIG_EVENT_ENTRY) {
2843 if (!section_seen)
2844 /* This is not the section's first entry. */
2845 return;
2846 /* We encountered no comment before the section. */
2847 break;
2848 }
2849 if (type == CONFIG_EVENT_SECTION) {
2850 if (!store->parsed[i - 1].is_keys_section)
2851 break;
2852 section_seen = 1;
2853 }
2854 }
2855 begin = store->parsed[i].begin;
2856
2857 /*
2858 * Next, make sure that we are removing the last key(s) in the section,
2859 * and that there are no comments that are possibly about the current
2860 * section.
2861 */
2862 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
2863 enum config_event_t type = store->parsed[i].type;
2864
2865 if (type == CONFIG_EVENT_COMMENT)
2866 return;
2867 if (type == CONFIG_EVENT_SECTION) {
2868 if (store->parsed[i].is_keys_section)
2869 continue;
2870 break;
2871 }
2872 if (type == CONFIG_EVENT_ENTRY) {
2873 if (++seen < store->seen_nr &&
2874 i == store->seen[seen])
2875 /* We want to remove this entry, too */
2876 continue;
2877 /* There is another entry in this section. */
2878 return;
2879 }
2880 }
2881
2882 /*
2883 * We are really removing the last entry/entries from this section, and
2884 * there are no enclosed or surrounding comments. Remove the entire,
2885 * now-empty section.
2886 */
2887 *seen_ptr = seen;
2888 *begin_offset = begin;
2889 if (i < store->parsed_nr)
2890 *end_offset = store->parsed[i].begin;
2891 else
2892 *end_offset = store->parsed[store->parsed_nr - 1].end;
2893 }
2894
2895 int repo_config_set_in_file_gently(struct repository *r, const char *config_filename,
2896 const char *key, const char *comment, const char *value)
2897 {
2898 return repo_config_set_multivar_in_file_gently(r, config_filename, key, value, NULL, comment, 0);
2899 }
2900
2901 void repo_config_set_in_file(struct repository *r, const char *config_filename,
2902 const char *key, const char *value)
2903 {
2904 repo_config_set_multivar_in_file(r, config_filename, key, value, NULL, 0);
2905 }
2906
2907 int repo_config_set_gently(struct repository *r, const char *key, const char *value)
2908 {
2909 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
2910 }
2911
2912 int repo_config_set_worktree_gently(struct repository *r,
2913 const char *key, const char *value)
2914 {
2915 /* Only use worktree-specific config if it is already enabled. */
2916 if (r->repository_format_worktree_config) {
2917 char *file = repo_git_path(r, "config.worktree");
2918 int ret = repo_config_set_multivar_in_file_gently(
2919 r, file, key, value, NULL, NULL, 0);
2920 free(file);
2921 return ret;
2922 }
2923 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
2924 }
2925
2926 void repo_config_set(struct repository *r, const char *key, const char *value)
2927 {
2928 repo_config_set_multivar(r, key, value, NULL, 0);
2929
2930 trace2_cmd_set_config(key, value);
2931 }
2932
2933 char *git_config_prepare_comment_string(const char *comment)
2934 {
2935 size_t leading_blanks;
2936 char *prepared;
2937
2938 if (!comment)
2939 return NULL;
2940
2941 if (strchr(comment, '\n'))
2942 die(_("no multi-line comment allowed: '%s'"), comment);
2943
2944 /*
2945 * If it begins with one or more leading whitespace characters
2946 * followed by '#", the comment string is used as-is.
2947 *
2948 * If it begins with '#', a SP is inserted between the comment
2949 * and the value the comment is about.
2950 *
2951 * Otherwise, the value is followed by a SP followed by '#'
2952 * followed by SP and then the comment string comes.
2953 */
2954
2955 leading_blanks = strspn(comment, " \t");
2956 if (leading_blanks && comment[leading_blanks] == '#')
2957 prepared = xstrdup(comment); /* use it as-is */
2958 else if (comment[0] == '#')
2959 prepared = xstrfmt(" %s", comment);
2960 else
2961 prepared = xstrfmt(" # %s", comment);
2962
2963 return prepared;
2964 }
2965
2966 /*
2967 * How long to retry acquiring config.lock when another process holds
2968 * it. Default matches core.packedRefsTimeout; override via
2969 * core.configLockTimeout.
2970 */
2971 static long config_lock_timeout_ms(struct repository *r)
2972 {
2973 static int configured;
2974 static int timeout_ms = 1000;
2975
2976 if (!configured) {
2977 repo_config_get_int(r, "core.configlocktimeout", &timeout_ms);
2978 configured = 1;
2979 }
2980
2981 return timeout_ms;
2982 }
2983
2984 static void validate_comment_string(const char *comment)
2985 {
2986 size_t leading_blanks;
2987
2988 if (!comment)
2989 return;
2990 /*
2991 * The front-end must have massaged the comment string
2992 * properly before calling us.
2993 */
2994 if (strchr(comment, '\n'))
2995 BUG("multi-line comments are not permitted: '%s'", comment);
2996
2997 leading_blanks = strspn(comment, " \t");
2998 if (!leading_blanks || comment[leading_blanks] != '#')
2999 BUG("comment must begin with one or more SP followed by '#': '%s'",
3000 comment);
3001 }
3002
3003 /*
3004 * If value==NULL, unset in (remove from) config,
3005 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3006 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3007 * (only add a new one)
3008 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3009 * key/values are removed before a single new pair is written. If the
3010 * flag is not present, then replace only the first match.
3011 *
3012 * Returns 0 on success.
3013 *
3014 * This function does this:
3015 *
3016 * - it locks the config file by creating ".git/config.lock"
3017 *
3018 * - it then parses the config using store_aux() as validator to find
3019 * the position on the key/value pair to replace. If it is to be unset,
3020 * it must be found exactly once.
3021 *
3022 * - the config file is mmap()ed and the part before the match (if any) is
3023 * written to the lock file, then the changed part and the rest.
3024 *
3025 * - the config file is removed and the lock file rename()d to it.
3026 *
3027 */
3028 int repo_config_set_multivar_in_file_gently(struct repository *r,
3029 const char *config_filename,
3030 const char *key, const char *value,
3031 const char *value_pattern,
3032 const char *comment,
3033 unsigned flags)
3034 {
3035 int fd = -1, in_fd = -1;
3036 int ret;
3037 struct lock_file lock = LOCK_INIT;
3038 char *filename_buf = NULL;
3039 char *contents = NULL;
3040 size_t contents_sz;
3041 struct config_store_data store = CONFIG_STORE_INIT;
3042 bool saved_check_deprecated_config = r->check_deprecated_config;
3043
3044 /*
3045 * Do not warn or die if there are deprecated config settings as
3046 * we want the user to be able to change those settings by running
3047 * "git config".
3048 */
3049 r->check_deprecated_config = false;
3050
3051 validate_comment_string(comment);
3052
3053 /* parse-key returns negative; flip the sign to feed exit(3) */
3054 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3055 if (ret)
3056 goto out_free;
3057
3058 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3059
3060 if (!config_filename)
3061 config_filename = filename_buf = repo_git_path(r, "config");
3062
3063 /*
3064 * The lock serves a purpose in addition to locking: the new
3065 * contents of .git/config will be written into it.
3066 */
3067 fd = repo_hold_lock_file_for_update_timeout(r, &lock, config_filename, 0,
3068 config_lock_timeout_ms(r));
3069 if (fd < 0) {
3070 error_errno(_("could not lock config file %s"), config_filename);
3071 ret = CONFIG_NO_LOCK;
3072 goto out_free;
3073 }
3074
3075 /*
3076 * If .git/config does not exist yet, write a minimal version.
3077 */
3078 in_fd = open(config_filename, O_RDONLY);
3079 if ( in_fd < 0 ) {
3080 if ( ENOENT != errno ) {
3081 error_errno(_("opening %s"), config_filename);
3082 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3083 goto out_free;
3084 }
3085 /* if nothing to unset, error out */
3086 if (!value) {
3087 ret = CONFIG_NOTHING_SET;
3088 goto out_free;
3089 }
3090
3091 free(store.key);
3092 store.key = xstrdup(key);
3093 if (write_section(fd, key, &store) < 0 ||
3094 write_pair(fd, key, value, comment, &store) < 0)
3095 goto write_err_out;
3096 } else {
3097 struct stat st;
3098 size_t copy_begin, copy_end;
3099 unsigned i;
3100 int new_line = 0;
3101 struct config_options opts;
3102
3103 if (!value_pattern)
3104 store.value_pattern = NULL;
3105 else if (value_pattern == CONFIG_REGEX_NONE)
3106 store.value_pattern = CONFIG_REGEX_NONE;
3107 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3108 store.fixed_value = value_pattern;
3109 else {
3110 if (value_pattern[0] == '!') {
3111 store.do_not_match = 1;
3112 value_pattern++;
3113 } else
3114 store.do_not_match = 0;
3115
3116 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3117 if (regcomp(store.value_pattern, value_pattern,
3118 REG_EXTENDED)) {
3119 error(_("invalid pattern: %s"), value_pattern);
3120 FREE_AND_NULL(store.value_pattern);
3121 ret = CONFIG_INVALID_PATTERN;
3122 goto out_free;
3123 }
3124 }
3125
3126 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3127 store.parsed[0].end = 0;
3128
3129 memset(&opts, 0, sizeof(opts));
3130 opts.event_fn = store_aux_event;
3131 opts.event_fn_data = &store;
3132
3133 /*
3134 * After this, store.parsed will contain offsets of all the
3135 * parsed elements, and store.seen will contain a list of
3136 * matches, as indices into store.parsed.
3137 *
3138 * As a side effect, we make sure to transform only a valid
3139 * existing config file.
3140 */
3141 if (git_config_from_file_with_options(store_aux,
3142 config_filename,
3143 &store, CONFIG_SCOPE_UNKNOWN,
3144 &opts)) {
3145 error(_("invalid config file %s"), config_filename);
3146 ret = CONFIG_INVALID_FILE;
3147 goto out_free;
3148 }
3149
3150 /* if nothing to unset, or too many matches, error out */
3151 if ((store.seen_nr == 0 && value == NULL) ||
3152 (store.seen_nr > 1 && !store.multi_replace)) {
3153 ret = CONFIG_NOTHING_SET;
3154 goto out_free;
3155 }
3156
3157 if (fstat(in_fd, &st) == -1) {
3158 error_errno(_("fstat on %s failed"), config_filename);
3159 ret = CONFIG_INVALID_FILE;
3160 goto out_free;
3161 }
3162
3163 contents_sz = xsize_t(st.st_size);
3164 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3165 MAP_PRIVATE, in_fd, 0);
3166 if (contents == MAP_FAILED) {
3167 if (errno == ENODEV && S_ISDIR(st.st_mode))
3168 errno = EISDIR;
3169 error_errno(_("unable to mmap '%s'%s"),
3170 config_filename, mmap_os_err());
3171 ret = CONFIG_INVALID_FILE;
3172 contents = NULL;
3173 goto out_free;
3174 }
3175 close(in_fd);
3176 in_fd = -1;
3177
3178 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3179 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3180 ret = CONFIG_NO_WRITE;
3181 goto out_free;
3182 }
3183
3184 if (store.seen_nr == 0) {
3185 if (!store.seen_alloc) {
3186 /* Did not see key nor section */
3187 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3188 store.seen[0] = store.parsed_nr
3189 - !!store.parsed_nr;
3190 }
3191 store.seen_nr = 1;
3192 }
3193
3194 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3195 size_t replace_end;
3196 int j = store.seen[i];
3197
3198 new_line = 0;
3199 if (!store.key_seen) {
3200 copy_end = store.parsed[j].end;
3201 /* include '\n' when copying section header */
3202 if (copy_end > 0 && copy_end < contents_sz &&
3203 contents[copy_end - 1] != '\n' &&
3204 contents[copy_end] == '\n')
3205 copy_end++;
3206 replace_end = copy_end;
3207 } else {
3208 replace_end = store.parsed[j].end;
3209 copy_end = store.parsed[j].begin;
3210 if (!value)
3211 maybe_remove_section(&store,
3212 &copy_end,
3213 &replace_end, &i);
3214 /*
3215 * Swallow preceding white-space on the same
3216 * line.
3217 */
3218 while (copy_end > 0 ) {
3219 char c = contents[copy_end - 1];
3220
3221 if (isspace(c) && c != '\n')
3222 copy_end--;
3223 else
3224 break;
3225 }
3226 }
3227
3228 if (copy_end > 0 && contents[copy_end-1] != '\n')
3229 new_line = 1;
3230
3231 /* write the first part of the config */
3232 if (copy_end > copy_begin) {
3233 if (write_in_full(fd, contents + copy_begin,
3234 copy_end - copy_begin) < 0)
3235 goto write_err_out;
3236 if (new_line &&
3237 write_str_in_full(fd, "\n") < 0)
3238 goto write_err_out;
3239 }
3240 copy_begin = replace_end;
3241 }
3242
3243 /* write the pair (value == NULL means unset) */
3244 if (value) {
3245 if (!store.section_seen) {
3246 if (write_section(fd, key, &store) < 0)
3247 goto write_err_out;
3248 }
3249 if (write_pair(fd, key, value, comment, &store) < 0)
3250 goto write_err_out;
3251 }
3252
3253 /* write the rest of the config */
3254 if (copy_begin < contents_sz)
3255 if (write_in_full(fd, contents + copy_begin,
3256 contents_sz - copy_begin) < 0)
3257 goto write_err_out;
3258
3259 munmap(contents, contents_sz);
3260 contents = NULL;
3261 }
3262
3263 if (commit_lock_file(&lock) < 0) {
3264 error_errno(_("could not write config file %s"), config_filename);
3265 ret = CONFIG_NO_WRITE;
3266 goto out_free;
3267 }
3268
3269 ret = 0;
3270
3271 /* Invalidate the config cache */
3272 repo_config_clear(r);
3273
3274 out_free:
3275 rollback_lock_file(&lock);
3276 free(filename_buf);
3277 if (contents)
3278 munmap(contents, contents_sz);
3279 if (in_fd >= 0)
3280 close(in_fd);
3281 config_store_data_clear(&store);
3282 r->check_deprecated_config = saved_check_deprecated_config;
3283 return ret;
3284
3285 write_err_out:
3286 ret = write_error(get_lock_file_path(&lock));
3287 goto out_free;
3288 }
3289
3290 void repo_config_set_multivar_in_file(struct repository *r,
3291 const char *config_filename,
3292 const char *key, const char *value,
3293 const char *value_pattern, unsigned flags)
3294 {
3295 if (!repo_config_set_multivar_in_file_gently(r, config_filename, key, value,
3296 value_pattern, NULL, flags))
3297 return;
3298 if (value)
3299 die(_("could not set '%s' to '%s'"), key, value);
3300 else
3301 die(_("could not unset '%s'"), key);
3302 }
3303
3304 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3305 const char *value,
3306 const char *value_pattern, unsigned flags)
3307 {
3308 char *file = repo_git_path(r, "config");
3309 int res = repo_config_set_multivar_in_file_gently(r, file,
3310 key, value,
3311 value_pattern,
3312 NULL, flags);
3313 free(file);
3314 return res;
3315 }
3316
3317 void repo_config_set_multivar(struct repository *r,
3318 const char *key, const char *value,
3319 const char *value_pattern, unsigned flags)
3320 {
3321 char *file = repo_git_path(r, "config");
3322 repo_config_set_multivar_in_file(r, file, key, value,
3323 value_pattern, flags);
3324 free(file);
3325 }
3326
3327 static size_t section_name_match (const char *buf, const char *name)
3328 {
3329 size_t i = 0, j = 0;
3330 int dot = 0;
3331 if (buf[i] != '[')
3332 return 0;
3333 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3334 if (!dot && isspace(buf[i])) {
3335 dot = 1;
3336 if (name[j++] != '.')
3337 break;
3338 for (i++; isspace(buf[i]); i++)
3339 ; /* do nothing */
3340 if (buf[i] != '"')
3341 break;
3342 continue;
3343 }
3344 if (buf[i] == '\\' && dot)
3345 i++;
3346 else if (buf[i] == '"' && dot) {
3347 for (i++; isspace(buf[i]); i++)
3348 ; /* do_nothing */
3349 break;
3350 }
3351 if (buf[i] != name[j++])
3352 break;
3353 }
3354 if (buf[i] == ']' && name[j] == 0) {
3355 /*
3356 * We match, now just find the right length offset by
3357 * gobbling up any whitespace after it, as well
3358 */
3359 i++;
3360 for (; buf[i] && isspace(buf[i]); i++)
3361 ; /* do nothing */
3362 return i;
3363 }
3364 return 0;
3365 }
3366
3367 static int section_name_is_ok(const char *name)
3368 {
3369 /* Empty section names are bogus. */
3370 if (!*name)
3371 return 0;
3372
3373 /*
3374 * Before a dot, we must be alphanumeric or dash. After the first dot,
3375 * anything goes, so we can stop checking.
3376 */
3377 for (; *name && *name != '.'; name++)
3378 if (*name != '-' && !isalnum(*name))
3379 return 0;
3380 return 1;
3381 }
3382
3383 #define GIT_CONFIG_MAX_LINE_LEN (512 * 1024)
3384
3385 /* if new_name == NULL, the section is removed instead */
3386 static int repo_config_copy_or_rename_section_in_file(
3387 struct repository *r,
3388 const char *config_filename,
3389 const char *old_name,
3390 const char *new_name, int copy)
3391 {
3392 int ret = 0, remove = 0;
3393 char *filename_buf = NULL;
3394 struct lock_file lock = LOCK_INIT;
3395 int out_fd;
3396 struct strbuf buf = STRBUF_INIT;
3397 FILE *config_file = NULL;
3398 struct stat st;
3399 struct strbuf copystr = STRBUF_INIT;
3400 struct config_store_data store;
3401 uint32_t line_nr = 0;
3402
3403 memset(&store, 0, sizeof(store));
3404
3405 if (new_name && !section_name_is_ok(new_name)) {
3406 ret = error(_("invalid section name: %s"), new_name);
3407 goto out_no_rollback;
3408 }
3409
3410 if (!config_filename)
3411 config_filename = filename_buf = repo_git_path(r, "config");
3412
3413 out_fd = repo_hold_lock_file_for_update_timeout(r, &lock,
3414 config_filename, 0,
3415 config_lock_timeout_ms(r));
3416 if (out_fd < 0) {
3417 ret = error(_("could not lock config file %s"), config_filename);
3418 goto out;
3419 }
3420
3421 if (!(config_file = fopen(config_filename, "rb"))) {
3422 ret = warn_on_fopen_errors(config_filename);
3423 if (ret)
3424 goto out;
3425 /* no config file means nothing to rename, no error */
3426 goto commit_and_out;
3427 }
3428
3429 if (fstat(fileno(config_file), &st) == -1) {
3430 ret = error_errno(_("fstat on %s failed"), config_filename);
3431 goto out;
3432 }
3433
3434 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3435 ret = error_errno(_("chmod on %s failed"),
3436 get_lock_file_path(&lock));
3437 goto out;
3438 }
3439
3440 while (!strbuf_getwholeline(&buf, config_file, '\n')) {
3441 size_t i, length;
3442 int is_section = 0;
3443 char *output = buf.buf;
3444
3445 line_nr++;
3446
3447 if (buf.len >= GIT_CONFIG_MAX_LINE_LEN) {
3448 ret = error(_("refusing to work with overly long line "
3449 "in '%s' on line %"PRIuMAX),
3450 config_filename, (uintmax_t)line_nr);
3451 goto out;
3452 }
3453
3454 for (i = 0; buf.buf[i] && isspace(buf.buf[i]); i++)
3455 ; /* do nothing */
3456 if (buf.buf[i] == '[') {
3457 /* it's a section */
3458 size_t offset;
3459 is_section = 1;
3460
3461 /*
3462 * When encountering a new section under -c we
3463 * need to flush out any section we're already
3464 * coping and begin anew. There might be
3465 * multiple [branch "$name"] sections.
3466 */
3467 if (copystr.len > 0) {
3468 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3469 ret = write_error(get_lock_file_path(&lock));
3470 goto out;
3471 }
3472 strbuf_reset(&copystr);
3473 }
3474
3475 offset = section_name_match(&buf.buf[i], old_name);
3476 if (offset > 0) {
3477 ret++;
3478 if (!new_name) {
3479 remove = 1;
3480 continue;
3481 }
3482 store.baselen = strlen(new_name);
3483 if (!copy) {
3484 if (write_section(out_fd, new_name, &store) < 0) {
3485 ret = write_error(get_lock_file_path(&lock));
3486 goto out;
3487 }
3488 /*
3489 * We wrote out the new section, with
3490 * a newline, now skip the old
3491 * section's length
3492 */
3493 output += offset + i;
3494 if (strlen(output) > 0) {
3495 /*
3496 * More content means there's
3497 * a declaration to put on the
3498 * next line; indent with a
3499 * tab
3500 */
3501 output -= 1;
3502 output[0] = '\t';
3503 }
3504 } else {
3505 strbuf_release(&copystr);
3506 copystr = store_create_section(new_name, &store);
3507 }
3508 }
3509 remove = 0;
3510 }
3511 if (remove)
3512 continue;
3513 length = strlen(output);
3514
3515 if (!is_section && copystr.len > 0) {
3516 strbuf_add(&copystr, output, length);
3517 }
3518
3519 if (write_in_full(out_fd, output, length) < 0) {
3520 ret = write_error(get_lock_file_path(&lock));
3521 goto out;
3522 }
3523 }
3524
3525 /*
3526 * Copy a trailing section at the end of the config, won't be
3527 * flushed by the usual "flush because we have a new section
3528 * logic in the loop above.
3529 */
3530 if (copystr.len > 0) {
3531 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3532 ret = write_error(get_lock_file_path(&lock));
3533 goto out;
3534 }
3535 strbuf_reset(&copystr);
3536 }
3537
3538 fclose(config_file);
3539 config_file = NULL;
3540 commit_and_out:
3541 if (commit_lock_file(&lock) < 0)
3542 ret = error_errno(_("could not write config file %s"),
3543 config_filename);
3544 out:
3545 if (config_file)
3546 fclose(config_file);
3547 rollback_lock_file(&lock);
3548 out_no_rollback:
3549 free(filename_buf);
3550 config_store_data_clear(&store);
3551 strbuf_release(&buf);
3552 strbuf_release(&copystr);
3553 return ret;
3554 }
3555
3556 int repo_config_rename_section_in_file(struct repository *r, const char *config_filename,
3557 const char *old_name, const char *new_name)
3558 {
3559 return repo_config_copy_or_rename_section_in_file(r, config_filename,
3560 old_name, new_name, 0);
3561 }
3562
3563 int repo_config_rename_section(struct repository *r, const char *old_name, const char *new_name)
3564 {
3565 return repo_config_rename_section_in_file(r, NULL, old_name, new_name);
3566 }
3567
3568 int repo_config_copy_section_in_file(struct repository *r, const char *config_filename,
3569 const char *old_name, const char *new_name)
3570 {
3571 return repo_config_copy_or_rename_section_in_file(r, config_filename,
3572 old_name, new_name, 1);
3573 }
3574
3575 int repo_config_copy_section(struct repository *r, const char *old_name, const char *new_name)
3576 {
3577 return repo_config_copy_section_in_file(r, NULL, old_name, new_name);
3578 }
3579
3580 /*
3581 * Call this to report error for your variable that should not
3582 * get a boolean value (i.e. "[my] var" means "true").
3583 */
3584 #undef config_error_nonbool
3585 int config_error_nonbool(const char *var)
3586 {
3587 return error(_("missing value for '%s'"), var);
3588 }
3589
3590 int parse_config_key(const char *var,
3591 const char *section,
3592 const char **subsection, size_t *subsection_len,
3593 const char **key)
3594 {
3595 const char *dot;
3596
3597 /* Does it start with "section." ? */
3598 if (!skip_prefix(var, section, &var) || *var != '.')
3599 return -1;
3600
3601 /*
3602 * Find the key; we don't know yet if we have a subsection, but we must
3603 * parse backwards from the end, since the subsection may have dots in
3604 * it, too.
3605 */
3606 dot = strrchr(var, '.');
3607 *key = dot + 1;
3608
3609 /* Did we have a subsection at all? */
3610 if (dot == var) {
3611 if (subsection) {
3612 *subsection = NULL;
3613 *subsection_len = 0;
3614 }
3615 }
3616 else {
3617 if (!subsection)
3618 return -1;
3619 *subsection = var + 1;
3620 *subsection_len = dot - *subsection;
3621 }
3622
3623 return 0;
3624 }
3625
3626 const char *config_origin_type_name(enum config_origin_type type)
3627 {
3628 switch (type) {
3629 case CONFIG_ORIGIN_BLOB:
3630 return "blob";
3631 case CONFIG_ORIGIN_FILE:
3632 return "file";
3633 case CONFIG_ORIGIN_STDIN:
3634 return "standard input";
3635 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3636 return "submodule-blob";
3637 case CONFIG_ORIGIN_CMDLINE:
3638 return "command line";
3639 default:
3640 BUG("unknown config origin type");
3641 }
3642 }
3643
3644 const char *config_scope_name(enum config_scope scope)
3645 {
3646 switch (scope) {
3647 case CONFIG_SCOPE_SYSTEM:
3648 return "system";
3649 case CONFIG_SCOPE_GLOBAL:
3650 return "global";
3651 case CONFIG_SCOPE_LOCAL:
3652 return "local";
3653 case CONFIG_SCOPE_WORKTREE:
3654 return "worktree";
3655 case CONFIG_SCOPE_COMMAND:
3656 return "command";
3657 case CONFIG_SCOPE_SUBMODULE:
3658 return "submodule";
3659 default:
3660 return "unknown";
3661 }
3662 }
3663
3664 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3665 {
3666 int i;
3667
3668 for (i = 0; i < nr_mapping; i++) {
3669 const char *name = mapping[i];
3670
3671 if (name && !strcasecmp(var, name))
3672 return i;
3673 }
3674 return -1;
3675 }