config.con commit config: avoid segfault when parsing command-line config (c5d6350)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 * Copyright (C) Johannes Schindelin, 2005
   6 *
   7 */
   8#include "cache.h"
   9#include "exec_cmd.h"
  10#include "strbuf.h"
  11#include "quote.h"
  12
  13#define MAXNAME (256)
  14
  15static FILE *config_file;
  16static const char *config_file_name;
  17static int config_linenr;
  18static int config_file_eof;
  19static int zlib_compression_seen;
  20
  21const char *config_exclusive_filename = NULL;
  22
  23static void lowercase(char *p)
  24{
  25        for (; *p; p++)
  26                *p = tolower(*p);
  27}
  28
  29void git_config_push_parameter(const char *text)
  30{
  31        struct strbuf env = STRBUF_INIT;
  32        const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
  33        if (old) {
  34                strbuf_addstr(&env, old);
  35                strbuf_addch(&env, ' ');
  36        }
  37        sq_quote_buf(&env, text);
  38        setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
  39        strbuf_release(&env);
  40}
  41
  42static int git_config_parse_parameter(const char *text,
  43                                      config_fn_t fn, void *data)
  44{
  45        struct strbuf tmp = STRBUF_INIT;
  46        struct strbuf **pair;
  47        strbuf_addstr(&tmp, text);
  48        pair = strbuf_split_max(&tmp, '=', 2);
  49        if (!pair[0])
  50                return error("bogus config parameter: %s", text);
  51        if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
  52                strbuf_setlen(pair[0], pair[0]->len - 1);
  53        strbuf_trim(pair[0]);
  54        if (!pair[0]->len) {
  55                strbuf_list_free(pair);
  56                return error("bogus config parameter: %s", text);
  57        }
  58        lowercase(pair[0]->buf);
  59        if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) {
  60                strbuf_list_free(pair);
  61                return -1;
  62        }
  63        strbuf_list_free(pair);
  64        return 0;
  65}
  66
  67int git_config_from_parameters(config_fn_t fn, void *data)
  68{
  69        const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
  70        char *envw;
  71        const char **argv = NULL;
  72        int nr = 0, alloc = 0;
  73        int i;
  74
  75        if (!env)
  76                return 0;
  77        /* sq_dequote will write over it */
  78        envw = xstrdup(env);
  79
  80        if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
  81                free(envw);
  82                return error("bogus format in " CONFIG_DATA_ENVIRONMENT);
  83        }
  84
  85        for (i = 0; i < nr; i++) {
  86                if (git_config_parse_parameter(argv[i], fn, data) < 0) {
  87                        free(argv);
  88                        free(envw);
  89                        return -1;
  90                }
  91        }
  92
  93        free(argv);
  94        free(envw);
  95        return nr > 0;
  96}
  97
  98static int get_next_char(void)
  99{
 100        int c;
 101        FILE *f;
 102
 103        c = '\n';
 104        if ((f = config_file) != NULL) {
 105                c = fgetc(f);
 106                if (c == '\r') {
 107                        /* DOS like systems */
 108                        c = fgetc(f);
 109                        if (c != '\n') {
 110                                ungetc(c, f);
 111                                c = '\r';
 112                        }
 113                }
 114                if (c == '\n')
 115                        config_linenr++;
 116                if (c == EOF) {
 117                        config_file_eof = 1;
 118                        c = '\n';
 119                }
 120        }
 121        return c;
 122}
 123
 124static char *parse_value(void)
 125{
 126        static char value[1024];
 127        int quote = 0, comment = 0, len = 0, space = 0;
 128
 129        for (;;) {
 130                int c = get_next_char();
 131                if (len >= sizeof(value) - 1)
 132                        return NULL;
 133                if (c == '\n') {
 134                        if (quote)
 135                                return NULL;
 136                        value[len] = 0;
 137                        return value;
 138                }
 139                if (comment)
 140                        continue;
 141                if (isspace(c) && !quote) {
 142                        if (len)
 143                                space++;
 144                        continue;
 145                }
 146                if (!quote) {
 147                        if (c == ';' || c == '#') {
 148                                comment = 1;
 149                                continue;
 150                        }
 151                }
 152                for (; space; space--)
 153                        value[len++] = ' ';
 154                if (c == '\\') {
 155                        c = get_next_char();
 156                        switch (c) {
 157                        case '\n':
 158                                continue;
 159                        case 't':
 160                                c = '\t';
 161                                break;
 162                        case 'b':
 163                                c = '\b';
 164                                break;
 165                        case 'n':
 166                                c = '\n';
 167                                break;
 168                        /* Some characters escape as themselves */
 169                        case '\\': case '"':
 170                                break;
 171                        /* Reject unknown escape sequences */
 172                        default:
 173                                return NULL;
 174                        }
 175                        value[len++] = c;
 176                        continue;
 177                }
 178                if (c == '"') {
 179                        quote = 1-quote;
 180                        continue;
 181                }
 182                value[len++] = c;
 183        }
 184}
 185
 186static inline int iskeychar(int c)
 187{
 188        return isalnum(c) || c == '-';
 189}
 190
 191static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
 192{
 193        int c;
 194        char *value;
 195
 196        /* Get the full name */
 197        for (;;) {
 198                c = get_next_char();
 199                if (config_file_eof)
 200                        break;
 201                if (!iskeychar(c))
 202                        break;
 203                name[len++] = tolower(c);
 204                if (len >= MAXNAME)
 205                        return -1;
 206        }
 207        name[len] = 0;
 208        while (c == ' ' || c == '\t')
 209                c = get_next_char();
 210
 211        value = NULL;
 212        if (c != '\n') {
 213                if (c != '=')
 214                        return -1;
 215                value = parse_value();
 216                if (!value)
 217                        return -1;
 218        }
 219        return fn(name, value, data);
 220}
 221
 222static int get_extended_base_var(char *name, int baselen, int c)
 223{
 224        do {
 225                if (c == '\n')
 226                        return -1;
 227                c = get_next_char();
 228        } while (isspace(c));
 229
 230        /* We require the format to be '[base "extension"]' */
 231        if (c != '"')
 232                return -1;
 233        name[baselen++] = '.';
 234
 235        for (;;) {
 236                int c = get_next_char();
 237                if (c == '\n')
 238                        return -1;
 239                if (c == '"')
 240                        break;
 241                if (c == '\\') {
 242                        c = get_next_char();
 243                        if (c == '\n')
 244                                return -1;
 245                }
 246                name[baselen++] = c;
 247                if (baselen > MAXNAME / 2)
 248                        return -1;
 249        }
 250
 251        /* Final ']' */
 252        if (get_next_char() != ']')
 253                return -1;
 254        return baselen;
 255}
 256
 257static int get_base_var(char *name)
 258{
 259        int baselen = 0;
 260
 261        for (;;) {
 262                int c = get_next_char();
 263                if (config_file_eof)
 264                        return -1;
 265                if (c == ']')
 266                        return baselen;
 267                if (isspace(c))
 268                        return get_extended_base_var(name, baselen, c);
 269                if (!iskeychar(c) && c != '.')
 270                        return -1;
 271                if (baselen > MAXNAME / 2)
 272                        return -1;
 273                name[baselen++] = tolower(c);
 274        }
 275}
 276
 277static int git_parse_file(config_fn_t fn, void *data)
 278{
 279        int comment = 0;
 280        int baselen = 0;
 281        static char var[MAXNAME];
 282
 283        /* U+FEFF Byte Order Mark in UTF8 */
 284        static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
 285        const unsigned char *bomptr = utf8_bom;
 286
 287        for (;;) {
 288                int c = get_next_char();
 289                if (bomptr && *bomptr) {
 290                        /* We are at the file beginning; skip UTF8-encoded BOM
 291                         * if present. Sane editors won't put this in on their
 292                         * own, but e.g. Windows Notepad will do it happily. */
 293                        if ((unsigned char) c == *bomptr) {
 294                                bomptr++;
 295                                continue;
 296                        } else {
 297                                /* Do not tolerate partial BOM. */
 298                                if (bomptr != utf8_bom)
 299                                        break;
 300                                /* No BOM at file beginning. Cool. */
 301                                bomptr = NULL;
 302                        }
 303                }
 304                if (c == '\n') {
 305                        if (config_file_eof)
 306                                return 0;
 307                        comment = 0;
 308                        continue;
 309                }
 310                if (comment || isspace(c))
 311                        continue;
 312                if (c == '#' || c == ';') {
 313                        comment = 1;
 314                        continue;
 315                }
 316                if (c == '[') {
 317                        baselen = get_base_var(var);
 318                        if (baselen <= 0)
 319                                break;
 320                        var[baselen++] = '.';
 321                        var[baselen] = 0;
 322                        continue;
 323                }
 324                if (!isalpha(c))
 325                        break;
 326                var[baselen] = tolower(c);
 327                if (get_value(fn, data, var, baselen+1) < 0)
 328                        break;
 329        }
 330        die("bad config file line %d in %s", config_linenr, config_file_name);
 331}
 332
 333static int parse_unit_factor(const char *end, unsigned long *val)
 334{
 335        if (!*end)
 336                return 1;
 337        else if (!strcasecmp(end, "k")) {
 338                *val *= 1024;
 339                return 1;
 340        }
 341        else if (!strcasecmp(end, "m")) {
 342                *val *= 1024 * 1024;
 343                return 1;
 344        }
 345        else if (!strcasecmp(end, "g")) {
 346                *val *= 1024 * 1024 * 1024;
 347                return 1;
 348        }
 349        return 0;
 350}
 351
 352static int git_parse_long(const char *value, long *ret)
 353{
 354        if (value && *value) {
 355                char *end;
 356                long val = strtol(value, &end, 0);
 357                unsigned long factor = 1;
 358                if (!parse_unit_factor(end, &factor))
 359                        return 0;
 360                *ret = val * factor;
 361                return 1;
 362        }
 363        return 0;
 364}
 365
 366int git_parse_ulong(const char *value, unsigned long *ret)
 367{
 368        if (value && *value) {
 369                char *end;
 370                unsigned long val = strtoul(value, &end, 0);
 371                if (!parse_unit_factor(end, &val))
 372                        return 0;
 373                *ret = val;
 374                return 1;
 375        }
 376        return 0;
 377}
 378
 379static void die_bad_config(const char *name)
 380{
 381        if (config_file_name)
 382                die("bad config value for '%s' in %s", name, config_file_name);
 383        die("bad config value for '%s'", name);
 384}
 385
 386int git_config_int(const char *name, const char *value)
 387{
 388        long ret = 0;
 389        if (!git_parse_long(value, &ret))
 390                die_bad_config(name);
 391        return ret;
 392}
 393
 394unsigned long git_config_ulong(const char *name, const char *value)
 395{
 396        unsigned long ret;
 397        if (!git_parse_ulong(value, &ret))
 398                die_bad_config(name);
 399        return ret;
 400}
 401
 402static int git_config_maybe_bool_text(const char *name, const char *value)
 403{
 404        if (!value)
 405                return 1;
 406        if (!*value)
 407                return 0;
 408        if (!strcasecmp(value, "true")
 409            || !strcasecmp(value, "yes")
 410            || !strcasecmp(value, "on"))
 411                return 1;
 412        if (!strcasecmp(value, "false")
 413            || !strcasecmp(value, "no")
 414            || !strcasecmp(value, "off"))
 415                return 0;
 416        return -1;
 417}
 418
 419int git_config_maybe_bool(const char *name, const char *value)
 420{
 421        long v = git_config_maybe_bool_text(name, value);
 422        if (0 <= v)
 423                return v;
 424        if (git_parse_long(value, &v))
 425                return !!v;
 426        return -1;
 427}
 428
 429int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
 430{
 431        int v = git_config_maybe_bool_text(name, value);
 432        if (0 <= v) {
 433                *is_bool = 1;
 434                return v;
 435        }
 436        *is_bool = 0;
 437        return git_config_int(name, value);
 438}
 439
 440int git_config_bool(const char *name, const char *value)
 441{
 442        int discard;
 443        return !!git_config_bool_or_int(name, value, &discard);
 444}
 445
 446int git_config_string(const char **dest, const char *var, const char *value)
 447{
 448        if (!value)
 449                return config_error_nonbool(var);
 450        *dest = xstrdup(value);
 451        return 0;
 452}
 453
 454int git_config_pathname(const char **dest, const char *var, const char *value)
 455{
 456        if (!value)
 457                return config_error_nonbool(var);
 458        *dest = expand_user_path(value);
 459        if (!*dest)
 460                die("Failed to expand user dir in: '%s'", value);
 461        return 0;
 462}
 463
 464static int git_default_core_config(const char *var, const char *value)
 465{
 466        /* This needs a better name */
 467        if (!strcmp(var, "core.filemode")) {
 468                trust_executable_bit = git_config_bool(var, value);
 469                return 0;
 470        }
 471        if (!strcmp(var, "core.trustctime")) {
 472                trust_ctime = git_config_bool(var, value);
 473                return 0;
 474        }
 475
 476        if (!strcmp(var, "core.quotepath")) {
 477                quote_path_fully = git_config_bool(var, value);
 478                return 0;
 479        }
 480
 481        if (!strcmp(var, "core.symlinks")) {
 482                has_symlinks = git_config_bool(var, value);
 483                return 0;
 484        }
 485
 486        if (!strcmp(var, "core.ignorecase")) {
 487                ignore_case = git_config_bool(var, value);
 488                return 0;
 489        }
 490
 491        if (!strcmp(var, "core.bare")) {
 492                is_bare_repository_cfg = git_config_bool(var, value);
 493                return 0;
 494        }
 495
 496        if (!strcmp(var, "core.ignorestat")) {
 497                assume_unchanged = git_config_bool(var, value);
 498                return 0;
 499        }
 500
 501        if (!strcmp(var, "core.prefersymlinkrefs")) {
 502                prefer_symlink_refs = git_config_bool(var, value);
 503                return 0;
 504        }
 505
 506        if (!strcmp(var, "core.logallrefupdates")) {
 507                log_all_ref_updates = git_config_bool(var, value);
 508                return 0;
 509        }
 510
 511        if (!strcmp(var, "core.warnambiguousrefs")) {
 512                warn_ambiguous_refs = git_config_bool(var, value);
 513                return 0;
 514        }
 515
 516        if (!strcmp(var, "core.abbrev")) {
 517                int abbrev = git_config_int(var, value);
 518                if (abbrev < minimum_abbrev || abbrev > 40)
 519                        return -1;
 520                default_abbrev = abbrev;
 521                return 0;
 522        }
 523
 524        if (!strcmp(var, "core.loosecompression")) {
 525                int level = git_config_int(var, value);
 526                if (level == -1)
 527                        level = Z_DEFAULT_COMPRESSION;
 528                else if (level < 0 || level > Z_BEST_COMPRESSION)
 529                        die("bad zlib compression level %d", level);
 530                zlib_compression_level = level;
 531                zlib_compression_seen = 1;
 532                return 0;
 533        }
 534
 535        if (!strcmp(var, "core.compression")) {
 536                int level = git_config_int(var, value);
 537                if (level == -1)
 538                        level = Z_DEFAULT_COMPRESSION;
 539                else if (level < 0 || level > Z_BEST_COMPRESSION)
 540                        die("bad zlib compression level %d", level);
 541                core_compression_level = level;
 542                core_compression_seen = 1;
 543                if (!zlib_compression_seen)
 544                        zlib_compression_level = level;
 545                return 0;
 546        }
 547
 548        if (!strcmp(var, "core.packedgitwindowsize")) {
 549                int pgsz_x2 = getpagesize() * 2;
 550                packed_git_window_size = git_config_int(var, value);
 551
 552                /* This value must be multiple of (pagesize * 2) */
 553                packed_git_window_size /= pgsz_x2;
 554                if (packed_git_window_size < 1)
 555                        packed_git_window_size = 1;
 556                packed_git_window_size *= pgsz_x2;
 557                return 0;
 558        }
 559
 560        if (!strcmp(var, "core.bigfilethreshold")) {
 561                long n = git_config_int(var, value);
 562                big_file_threshold = 0 < n ? n : 0;
 563                return 0;
 564        }
 565
 566        if (!strcmp(var, "core.packedgitlimit")) {
 567                packed_git_limit = git_config_int(var, value);
 568                return 0;
 569        }
 570
 571        if (!strcmp(var, "core.deltabasecachelimit")) {
 572                delta_base_cache_limit = git_config_int(var, value);
 573                return 0;
 574        }
 575
 576        if (!strcmp(var, "core.autocrlf")) {
 577                if (value && !strcasecmp(value, "input")) {
 578                        if (eol == EOL_CRLF)
 579                                return error("core.autocrlf=input conflicts with core.eol=crlf");
 580                        auto_crlf = AUTO_CRLF_INPUT;
 581                        return 0;
 582                }
 583                auto_crlf = git_config_bool(var, value);
 584                return 0;
 585        }
 586
 587        if (!strcmp(var, "core.safecrlf")) {
 588                if (value && !strcasecmp(value, "warn")) {
 589                        safe_crlf = SAFE_CRLF_WARN;
 590                        return 0;
 591                }
 592                safe_crlf = git_config_bool(var, value);
 593                return 0;
 594        }
 595
 596        if (!strcmp(var, "core.eol")) {
 597                if (value && !strcasecmp(value, "lf"))
 598                        eol = EOL_LF;
 599                else if (value && !strcasecmp(value, "crlf"))
 600                        eol = EOL_CRLF;
 601                else if (value && !strcasecmp(value, "native"))
 602                        eol = EOL_NATIVE;
 603                else
 604                        eol = EOL_UNSET;
 605                if (eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
 606                        return error("core.autocrlf=input conflicts with core.eol=crlf");
 607                return 0;
 608        }
 609
 610        if (!strcmp(var, "core.notesref")) {
 611                notes_ref_name = xstrdup(value);
 612                return 0;
 613        }
 614
 615        if (!strcmp(var, "core.pager"))
 616                return git_config_string(&pager_program, var, value);
 617
 618        if (!strcmp(var, "core.editor"))
 619                return git_config_string(&editor_program, var, value);
 620
 621        if (!strcmp(var, "core.askpass"))
 622                return git_config_string(&askpass_program, var, value);
 623
 624        if (!strcmp(var, "core.excludesfile"))
 625                return git_config_pathname(&excludes_file, var, value);
 626
 627        if (!strcmp(var, "core.whitespace")) {
 628                if (!value)
 629                        return config_error_nonbool(var);
 630                whitespace_rule_cfg = parse_whitespace_rule(value);
 631                return 0;
 632        }
 633
 634        if (!strcmp(var, "core.fsyncobjectfiles")) {
 635                fsync_object_files = git_config_bool(var, value);
 636                return 0;
 637        }
 638
 639        if (!strcmp(var, "core.preloadindex")) {
 640                core_preload_index = git_config_bool(var, value);
 641                return 0;
 642        }
 643
 644        if (!strcmp(var, "core.createobject")) {
 645                if (!strcmp(value, "rename"))
 646                        object_creation_mode = OBJECT_CREATION_USES_RENAMES;
 647                else if (!strcmp(value, "link"))
 648                        object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
 649                else
 650                        die("Invalid mode for object creation: %s", value);
 651                return 0;
 652        }
 653
 654        if (!strcmp(var, "core.sparsecheckout")) {
 655                core_apply_sparse_checkout = git_config_bool(var, value);
 656                return 0;
 657        }
 658
 659        /* Add other config variables here and to Documentation/config.txt. */
 660        return 0;
 661}
 662
 663static int git_default_user_config(const char *var, const char *value)
 664{
 665        if (!strcmp(var, "user.name")) {
 666                if (!value)
 667                        return config_error_nonbool(var);
 668                strlcpy(git_default_name, value, sizeof(git_default_name));
 669                user_ident_explicitly_given |= IDENT_NAME_GIVEN;
 670                return 0;
 671        }
 672
 673        if (!strcmp(var, "user.email")) {
 674                if (!value)
 675                        return config_error_nonbool(var);
 676                strlcpy(git_default_email, value, sizeof(git_default_email));
 677                user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
 678                return 0;
 679        }
 680
 681        /* Add other config variables here and to Documentation/config.txt. */
 682        return 0;
 683}
 684
 685static int git_default_i18n_config(const char *var, const char *value)
 686{
 687        if (!strcmp(var, "i18n.commitencoding"))
 688                return git_config_string(&git_commit_encoding, var, value);
 689
 690        if (!strcmp(var, "i18n.logoutputencoding"))
 691                return git_config_string(&git_log_output_encoding, var, value);
 692
 693        /* Add other config variables here and to Documentation/config.txt. */
 694        return 0;
 695}
 696
 697static int git_default_branch_config(const char *var, const char *value)
 698{
 699        if (!strcmp(var, "branch.autosetupmerge")) {
 700                if (value && !strcasecmp(value, "always")) {
 701                        git_branch_track = BRANCH_TRACK_ALWAYS;
 702                        return 0;
 703                }
 704                git_branch_track = git_config_bool(var, value);
 705                return 0;
 706        }
 707        if (!strcmp(var, "branch.autosetuprebase")) {
 708                if (!value)
 709                        return config_error_nonbool(var);
 710                else if (!strcmp(value, "never"))
 711                        autorebase = AUTOREBASE_NEVER;
 712                else if (!strcmp(value, "local"))
 713                        autorebase = AUTOREBASE_LOCAL;
 714                else if (!strcmp(value, "remote"))
 715                        autorebase = AUTOREBASE_REMOTE;
 716                else if (!strcmp(value, "always"))
 717                        autorebase = AUTOREBASE_ALWAYS;
 718                else
 719                        return error("Malformed value for %s", var);
 720                return 0;
 721        }
 722
 723        /* Add other config variables here and to Documentation/config.txt. */
 724        return 0;
 725}
 726
 727static int git_default_push_config(const char *var, const char *value)
 728{
 729        if (!strcmp(var, "push.default")) {
 730                if (!value)
 731                        return config_error_nonbool(var);
 732                else if (!strcmp(value, "nothing"))
 733                        push_default = PUSH_DEFAULT_NOTHING;
 734                else if (!strcmp(value, "matching"))
 735                        push_default = PUSH_DEFAULT_MATCHING;
 736                else if (!strcmp(value, "upstream"))
 737                        push_default = PUSH_DEFAULT_UPSTREAM;
 738                else if (!strcmp(value, "tracking")) /* deprecated */
 739                        push_default = PUSH_DEFAULT_UPSTREAM;
 740                else if (!strcmp(value, "current"))
 741                        push_default = PUSH_DEFAULT_CURRENT;
 742                else {
 743                        error("Malformed value for %s: %s", var, value);
 744                        return error("Must be one of nothing, matching, "
 745                                     "tracking or current.");
 746                }
 747                return 0;
 748        }
 749
 750        /* Add other config variables here and to Documentation/config.txt. */
 751        return 0;
 752}
 753
 754static int git_default_mailmap_config(const char *var, const char *value)
 755{
 756        if (!strcmp(var, "mailmap.file"))
 757                return git_config_string(&git_mailmap_file, var, value);
 758
 759        /* Add other config variables here and to Documentation/config.txt. */
 760        return 0;
 761}
 762
 763int git_default_config(const char *var, const char *value, void *dummy)
 764{
 765        if (!prefixcmp(var, "core."))
 766                return git_default_core_config(var, value);
 767
 768        if (!prefixcmp(var, "user."))
 769                return git_default_user_config(var, value);
 770
 771        if (!prefixcmp(var, "i18n."))
 772                return git_default_i18n_config(var, value);
 773
 774        if (!prefixcmp(var, "branch."))
 775                return git_default_branch_config(var, value);
 776
 777        if (!prefixcmp(var, "push."))
 778                return git_default_push_config(var, value);
 779
 780        if (!prefixcmp(var, "mailmap."))
 781                return git_default_mailmap_config(var, value);
 782
 783        if (!prefixcmp(var, "advice."))
 784                return git_default_advice_config(var, value);
 785
 786        if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
 787                pager_use_color = git_config_bool(var,value);
 788                return 0;
 789        }
 790
 791        /* Add other config variables here and to Documentation/config.txt. */
 792        return 0;
 793}
 794
 795int git_config_from_file(config_fn_t fn, const char *filename, void *data)
 796{
 797        int ret;
 798        FILE *f = fopen(filename, "r");
 799
 800        ret = -1;
 801        if (f) {
 802                config_file = f;
 803                config_file_name = filename;
 804                config_linenr = 1;
 805                config_file_eof = 0;
 806                ret = git_parse_file(fn, data);
 807                fclose(f);
 808                config_file_name = NULL;
 809        }
 810        return ret;
 811}
 812
 813const char *git_etc_gitconfig(void)
 814{
 815        static const char *system_wide;
 816        if (!system_wide)
 817                system_wide = system_path(ETC_GITCONFIG);
 818        return system_wide;
 819}
 820
 821int git_env_bool(const char *k, int def)
 822{
 823        const char *v = getenv(k);
 824        return v ? git_config_bool(k, v) : def;
 825}
 826
 827int git_config_system(void)
 828{
 829        return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
 830}
 831
 832int git_config_early(config_fn_t fn, void *data, const char *repo_config)
 833{
 834        int ret = 0, found = 0;
 835        const char *home = NULL;
 836
 837        /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
 838        if (config_exclusive_filename)
 839                return git_config_from_file(fn, config_exclusive_filename, data);
 840        if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
 841                ret += git_config_from_file(fn, git_etc_gitconfig(),
 842                                            data);
 843                found += 1;
 844        }
 845
 846        home = getenv("HOME");
 847        if (home) {
 848                char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
 849                if (!access(user_config, R_OK)) {
 850                        ret += git_config_from_file(fn, user_config, data);
 851                        found += 1;
 852                }
 853                free(user_config);
 854        }
 855
 856        if (repo_config && !access(repo_config, R_OK)) {
 857                ret += git_config_from_file(fn, repo_config, data);
 858                found += 1;
 859        }
 860
 861        switch (git_config_from_parameters(fn, data)) {
 862        case -1: /* error */
 863                die("unable to parse command-line config");
 864                break;
 865        case 0: /* found nothing */
 866                break;
 867        default: /* found at least one item */
 868                found++;
 869                break;
 870        }
 871
 872        return ret == 0 ? found : ret;
 873}
 874
 875int git_config(config_fn_t fn, void *data)
 876{
 877        char *repo_config = NULL;
 878        int ret;
 879
 880        repo_config = git_pathdup("config");
 881        ret = git_config_early(fn, data, repo_config);
 882        if (repo_config)
 883                free(repo_config);
 884        return ret;
 885}
 886
 887/*
 888 * Find all the stuff for git_config_set() below.
 889 */
 890
 891#define MAX_MATCHES 512
 892
 893static struct {
 894        int baselen;
 895        char *key;
 896        int do_not_match;
 897        regex_t *value_regex;
 898        int multi_replace;
 899        size_t offset[MAX_MATCHES];
 900        enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
 901        int seen;
 902} store;
 903
 904static int matches(const char *key, const char *value)
 905{
 906        return !strcmp(key, store.key) &&
 907                (store.value_regex == NULL ||
 908                 (store.do_not_match ^
 909                  !regexec(store.value_regex, value, 0, NULL, 0)));
 910}
 911
 912static int store_aux(const char *key, const char *value, void *cb)
 913{
 914        const char *ep;
 915        size_t section_len;
 916
 917        switch (store.state) {
 918        case KEY_SEEN:
 919                if (matches(key, value)) {
 920                        if (store.seen == 1 && store.multi_replace == 0) {
 921                                warning("%s has multiple values", key);
 922                        } else if (store.seen >= MAX_MATCHES) {
 923                                error("too many matches for %s", key);
 924                                return 1;
 925                        }
 926
 927                        store.offset[store.seen] = ftell(config_file);
 928                        store.seen++;
 929                }
 930                break;
 931        case SECTION_SEEN:
 932                /*
 933                 * What we are looking for is in store.key (both
 934                 * section and var), and its section part is baselen
 935                 * long.  We found key (again, both section and var).
 936                 * We would want to know if this key is in the same
 937                 * section as what we are looking for.  We already
 938                 * know we are in the same section as what should
 939                 * hold store.key.
 940                 */
 941                ep = strrchr(key, '.');
 942                section_len = ep - key;
 943
 944                if ((section_len != store.baselen) ||
 945                    memcmp(key, store.key, section_len+1)) {
 946                        store.state = SECTION_END_SEEN;
 947                        break;
 948                }
 949
 950                /*
 951                 * Do not increment matches: this is no match, but we
 952                 * just made sure we are in the desired section.
 953                 */
 954                store.offset[store.seen] = ftell(config_file);
 955                /* fallthru */
 956        case SECTION_END_SEEN:
 957        case START:
 958                if (matches(key, value)) {
 959                        store.offset[store.seen] = ftell(config_file);
 960                        store.state = KEY_SEEN;
 961                        store.seen++;
 962                } else {
 963                        if (strrchr(key, '.') - key == store.baselen &&
 964                              !strncmp(key, store.key, store.baselen)) {
 965                                        store.state = SECTION_SEEN;
 966                                        store.offset[store.seen] = ftell(config_file);
 967                        }
 968                }
 969        }
 970        return 0;
 971}
 972
 973static int write_error(const char *filename)
 974{
 975        error("failed to write new configuration file %s", filename);
 976
 977        /* Same error code as "failed to rename". */
 978        return 4;
 979}
 980
 981static int store_write_section(int fd, const char *key)
 982{
 983        const char *dot;
 984        int i, success;
 985        struct strbuf sb = STRBUF_INIT;
 986
 987        dot = memchr(key, '.', store.baselen);
 988        if (dot) {
 989                strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
 990                for (i = dot - key + 1; i < store.baselen; i++) {
 991                        if (key[i] == '"' || key[i] == '\\')
 992                                strbuf_addch(&sb, '\\');
 993                        strbuf_addch(&sb, key[i]);
 994                }
 995                strbuf_addstr(&sb, "\"]\n");
 996        } else {
 997                strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
 998        }
 999
1000        success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1001        strbuf_release(&sb);
1002
1003        return success;
1004}
1005
1006static int store_write_pair(int fd, const char *key, const char *value)
1007{
1008        int i, success;
1009        int length = strlen(key + store.baselen + 1);
1010        const char *quote = "";
1011        struct strbuf sb = STRBUF_INIT;
1012
1013        /*
1014         * Check to see if the value needs to be surrounded with a dq pair.
1015         * Note that problematic characters are always backslash-quoted; this
1016         * check is about not losing leading or trailing SP and strings that
1017         * follow beginning-of-comment characters (i.e. ';' and '#') by the
1018         * configuration parser.
1019         */
1020        if (value[0] == ' ')
1021                quote = "\"";
1022        for (i = 0; value[i]; i++)
1023                if (value[i] == ';' || value[i] == '#')
1024                        quote = "\"";
1025        if (i && value[i - 1] == ' ')
1026                quote = "\"";
1027
1028        strbuf_addf(&sb, "\t%.*s = %s",
1029                    length, key + store.baselen + 1, quote);
1030
1031        for (i = 0; value[i]; i++)
1032                switch (value[i]) {
1033                case '\n':
1034                        strbuf_addstr(&sb, "\\n");
1035                        break;
1036                case '\t':
1037                        strbuf_addstr(&sb, "\\t");
1038                        break;
1039                case '"':
1040                case '\\':
1041                        strbuf_addch(&sb, '\\');
1042                default:
1043                        strbuf_addch(&sb, value[i]);
1044                        break;
1045                }
1046        strbuf_addf(&sb, "%s\n", quote);
1047
1048        success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1049        strbuf_release(&sb);
1050
1051        return success;
1052}
1053
1054static ssize_t find_beginning_of_line(const char *contents, size_t size,
1055        size_t offset_, int *found_bracket)
1056{
1057        size_t equal_offset = size, bracket_offset = size;
1058        ssize_t offset;
1059
1060contline:
1061        for (offset = offset_-2; offset > 0
1062                        && contents[offset] != '\n'; offset--)
1063                switch (contents[offset]) {
1064                        case '=': equal_offset = offset; break;
1065                        case ']': bracket_offset = offset; break;
1066                }
1067        if (offset > 0 && contents[offset-1] == '\\') {
1068                offset_ = offset;
1069                goto contline;
1070        }
1071        if (bracket_offset < equal_offset) {
1072                *found_bracket = 1;
1073                offset = bracket_offset+1;
1074        } else
1075                offset++;
1076
1077        return offset;
1078}
1079
1080int git_config_set(const char *key, const char *value)
1081{
1082        return git_config_set_multivar(key, value, NULL, 0);
1083}
1084
1085/*
1086 * Auxiliary function to sanity-check and split the key into the section
1087 * identifier and variable name.
1088 *
1089 * Returns 0 on success, -1 when there is an invalid character in the key and
1090 * -2 if there is no section name in the key.
1091 *
1092 * store_key - pointer to char* which will hold a copy of the key with
1093 *             lowercase section and variable name
1094 * baselen - pointer to int which will hold the length of the
1095 *           section + subsection part, can be NULL
1096 */
1097int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1098{
1099        int i, dot, baselen;
1100        const char *last_dot = strrchr(key, '.');
1101
1102        /*
1103         * Since "key" actually contains the section name and the real
1104         * key name separated by a dot, we have to know where the dot is.
1105         */
1106
1107        if (last_dot == NULL || last_dot == key) {
1108                error("key does not contain a section: %s", key);
1109                return -2;
1110        }
1111
1112        if (!last_dot[1]) {
1113                error("key does not contain variable name: %s", key);
1114                return -2;
1115        }
1116
1117        baselen = last_dot - key;
1118        if (baselen_)
1119                *baselen_ = baselen;
1120
1121        /*
1122         * Validate the key and while at it, lower case it for matching.
1123         */
1124        *store_key = xmalloc(strlen(key) + 1);
1125
1126        dot = 0;
1127        for (i = 0; key[i]; i++) {
1128                unsigned char c = key[i];
1129                if (c == '.')
1130                        dot = 1;
1131                /* Leave the extended basename untouched.. */
1132                if (!dot || i > baselen) {
1133                        if (!iskeychar(c) ||
1134                            (i == baselen + 1 && !isalpha(c))) {
1135                                error("invalid key: %s", key);
1136                                goto out_free_ret_1;
1137                        }
1138                        c = tolower(c);
1139                } else if (c == '\n') {
1140                        error("invalid key (newline): %s", key);
1141                        goto out_free_ret_1;
1142                }
1143                (*store_key)[i] = c;
1144        }
1145        (*store_key)[i] = 0;
1146
1147        return 0;
1148
1149out_free_ret_1:
1150        free(*store_key);
1151        return -1;
1152}
1153
1154/*
1155 * If value==NULL, unset in (remove from) config,
1156 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1157 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1158 *     else all matching key/values (regardless how many) are removed,
1159 *     before the new pair is written.
1160 *
1161 * Returns 0 on success.
1162 *
1163 * This function does this:
1164 *
1165 * - it locks the config file by creating ".git/config.lock"
1166 *
1167 * - it then parses the config using store_aux() as validator to find
1168 *   the position on the key/value pair to replace. If it is to be unset,
1169 *   it must be found exactly once.
1170 *
1171 * - the config file is mmap()ed and the part before the match (if any) is
1172 *   written to the lock file, then the changed part and the rest.
1173 *
1174 * - the config file is removed and the lock file rename()d to it.
1175 *
1176 */
1177int git_config_set_multivar(const char *key, const char *value,
1178        const char *value_regex, int multi_replace)
1179{
1180        int fd = -1, in_fd;
1181        int ret;
1182        char *config_filename;
1183        struct lock_file *lock = NULL;
1184
1185        if (config_exclusive_filename)
1186                config_filename = xstrdup(config_exclusive_filename);
1187        else
1188                config_filename = git_pathdup("config");
1189
1190        /* parse-key returns negative; flip the sign to feed exit(3) */
1191        ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
1192        if (ret)
1193                goto out_free;
1194
1195        store.multi_replace = multi_replace;
1196
1197
1198        /*
1199         * The lock serves a purpose in addition to locking: the new
1200         * contents of .git/config will be written into it.
1201         */
1202        lock = xcalloc(sizeof(struct lock_file), 1);
1203        fd = hold_lock_file_for_update(lock, config_filename, 0);
1204        if (fd < 0) {
1205                error("could not lock config file %s: %s", config_filename, strerror(errno));
1206                free(store.key);
1207                ret = -1;
1208                goto out_free;
1209        }
1210
1211        /*
1212         * If .git/config does not exist yet, write a minimal version.
1213         */
1214        in_fd = open(config_filename, O_RDONLY);
1215        if ( in_fd < 0 ) {
1216                free(store.key);
1217
1218                if ( ENOENT != errno ) {
1219                        error("opening %s: %s", config_filename,
1220                              strerror(errno));
1221                        ret = 3; /* same as "invalid config file" */
1222                        goto out_free;
1223                }
1224                /* if nothing to unset, error out */
1225                if (value == NULL) {
1226                        ret = 5;
1227                        goto out_free;
1228                }
1229
1230                store.key = (char *)key;
1231                if (!store_write_section(fd, key) ||
1232                    !store_write_pair(fd, key, value))
1233                        goto write_err_out;
1234        } else {
1235                struct stat st;
1236                char *contents;
1237                size_t contents_sz, copy_begin, copy_end;
1238                int i, new_line = 0;
1239
1240                if (value_regex == NULL)
1241                        store.value_regex = NULL;
1242                else {
1243                        if (value_regex[0] == '!') {
1244                                store.do_not_match = 1;
1245                                value_regex++;
1246                        } else
1247                                store.do_not_match = 0;
1248
1249                        store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1250                        if (regcomp(store.value_regex, value_regex,
1251                                        REG_EXTENDED)) {
1252                                error("invalid pattern: %s", value_regex);
1253                                free(store.value_regex);
1254                                ret = 6;
1255                                goto out_free;
1256                        }
1257                }
1258
1259                store.offset[0] = 0;
1260                store.state = START;
1261                store.seen = 0;
1262
1263                /*
1264                 * After this, store.offset will contain the *end* offset
1265                 * of the last match, or remain at 0 if no match was found.
1266                 * As a side effect, we make sure to transform only a valid
1267                 * existing config file.
1268                 */
1269                if (git_config_from_file(store_aux, config_filename, NULL)) {
1270                        error("invalid config file %s", config_filename);
1271                        free(store.key);
1272                        if (store.value_regex != NULL) {
1273                                regfree(store.value_regex);
1274                                free(store.value_regex);
1275                        }
1276                        ret = 3;
1277                        goto out_free;
1278                }
1279
1280                free(store.key);
1281                if (store.value_regex != NULL) {
1282                        regfree(store.value_regex);
1283                        free(store.value_regex);
1284                }
1285
1286                /* if nothing to unset, or too many matches, error out */
1287                if ((store.seen == 0 && value == NULL) ||
1288                                (store.seen > 1 && multi_replace == 0)) {
1289                        ret = 5;
1290                        goto out_free;
1291                }
1292
1293                fstat(in_fd, &st);
1294                contents_sz = xsize_t(st.st_size);
1295                contents = xmmap(NULL, contents_sz, PROT_READ,
1296                        MAP_PRIVATE, in_fd, 0);
1297                close(in_fd);
1298
1299                if (store.seen == 0)
1300                        store.seen = 1;
1301
1302                for (i = 0, copy_begin = 0; i < store.seen; i++) {
1303                        if (store.offset[i] == 0) {
1304                                store.offset[i] = copy_end = contents_sz;
1305                        } else if (store.state != KEY_SEEN) {
1306                                copy_end = store.offset[i];
1307                        } else
1308                                copy_end = find_beginning_of_line(
1309                                        contents, contents_sz,
1310                                        store.offset[i]-2, &new_line);
1311
1312                        if (copy_end > 0 && contents[copy_end-1] != '\n')
1313                                new_line = 1;
1314
1315                        /* write the first part of the config */
1316                        if (copy_end > copy_begin) {
1317                                if (write_in_full(fd, contents + copy_begin,
1318                                                  copy_end - copy_begin) <
1319                                    copy_end - copy_begin)
1320                                        goto write_err_out;
1321                                if (new_line &&
1322                                    write_str_in_full(fd, "\n") != 1)
1323                                        goto write_err_out;
1324                        }
1325                        copy_begin = store.offset[i];
1326                }
1327
1328                /* write the pair (value == NULL means unset) */
1329                if (value != NULL) {
1330                        if (store.state == START) {
1331                                if (!store_write_section(fd, key))
1332                                        goto write_err_out;
1333                        }
1334                        if (!store_write_pair(fd, key, value))
1335                                goto write_err_out;
1336                }
1337
1338                /* write the rest of the config */
1339                if (copy_begin < contents_sz)
1340                        if (write_in_full(fd, contents + copy_begin,
1341                                          contents_sz - copy_begin) <
1342                            contents_sz - copy_begin)
1343                                goto write_err_out;
1344
1345                munmap(contents, contents_sz);
1346        }
1347
1348        if (commit_lock_file(lock) < 0) {
1349                error("could not commit config file %s", config_filename);
1350                ret = 4;
1351                goto out_free;
1352        }
1353
1354        /*
1355         * lock is committed, so don't try to roll it back below.
1356         * NOTE: Since lockfile.c keeps a linked list of all created
1357         * lock_file structures, it isn't safe to free(lock).  It's
1358         * better to just leave it hanging around.
1359         */
1360        lock = NULL;
1361        ret = 0;
1362
1363out_free:
1364        if (lock)
1365                rollback_lock_file(lock);
1366        free(config_filename);
1367        return ret;
1368
1369write_err_out:
1370        ret = write_error(lock->filename);
1371        goto out_free;
1372
1373}
1374
1375static int section_name_match (const char *buf, const char *name)
1376{
1377        int i = 0, j = 0, dot = 0;
1378        if (buf[i] != '[')
1379                return 0;
1380        for (i = 1; buf[i] && buf[i] != ']'; i++) {
1381                if (!dot && isspace(buf[i])) {
1382                        dot = 1;
1383                        if (name[j++] != '.')
1384                                break;
1385                        for (i++; isspace(buf[i]); i++)
1386                                ; /* do nothing */
1387                        if (buf[i] != '"')
1388                                break;
1389                        continue;
1390                }
1391                if (buf[i] == '\\' && dot)
1392                        i++;
1393                else if (buf[i] == '"' && dot) {
1394                        for (i++; isspace(buf[i]); i++)
1395                                ; /* do_nothing */
1396                        break;
1397                }
1398                if (buf[i] != name[j++])
1399                        break;
1400        }
1401        if (buf[i] == ']' && name[j] == 0) {
1402                /*
1403                 * We match, now just find the right length offset by
1404                 * gobbling up any whitespace after it, as well
1405                 */
1406                i++;
1407                for (; buf[i] && isspace(buf[i]); i++)
1408                        ; /* do nothing */
1409                return i;
1410        }
1411        return 0;
1412}
1413
1414/* if new_name == NULL, the section is removed instead */
1415int git_config_rename_section(const char *old_name, const char *new_name)
1416{
1417        int ret = 0, remove = 0;
1418        char *config_filename;
1419        struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1420        int out_fd;
1421        char buf[1024];
1422
1423        if (config_exclusive_filename)
1424                config_filename = xstrdup(config_exclusive_filename);
1425        else
1426                config_filename = git_pathdup("config");
1427        out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1428        if (out_fd < 0) {
1429                ret = error("could not lock config file %s", config_filename);
1430                goto out;
1431        }
1432
1433        if (!(config_file = fopen(config_filename, "rb"))) {
1434                /* no config file means nothing to rename, no error */
1435                goto unlock_and_out;
1436        }
1437
1438        while (fgets(buf, sizeof(buf), config_file)) {
1439                int i;
1440                int length;
1441                char *output = buf;
1442                for (i = 0; buf[i] && isspace(buf[i]); i++)
1443                        ; /* do nothing */
1444                if (buf[i] == '[') {
1445                        /* it's a section */
1446                        int offset = section_name_match(&buf[i], old_name);
1447                        if (offset > 0) {
1448                                ret++;
1449                                if (new_name == NULL) {
1450                                        remove = 1;
1451                                        continue;
1452                                }
1453                                store.baselen = strlen(new_name);
1454                                if (!store_write_section(out_fd, new_name)) {
1455                                        ret = write_error(lock->filename);
1456                                        goto out;
1457                                }
1458                                /*
1459                                 * We wrote out the new section, with
1460                                 * a newline, now skip the old
1461                                 * section's length
1462                                 */
1463                                output += offset + i;
1464                                if (strlen(output) > 0) {
1465                                        /*
1466                                         * More content means there's
1467                                         * a declaration to put on the
1468                                         * next line; indent with a
1469                                         * tab
1470                                         */
1471                                        output -= 1;
1472                                        output[0] = '\t';
1473                                }
1474                        }
1475                        remove = 0;
1476                }
1477                if (remove)
1478                        continue;
1479                length = strlen(output);
1480                if (write_in_full(out_fd, output, length) != length) {
1481                        ret = write_error(lock->filename);
1482                        goto out;
1483                }
1484        }
1485        fclose(config_file);
1486 unlock_and_out:
1487        if (commit_lock_file(lock) < 0)
1488                ret = error("could not commit config file %s", config_filename);
1489 out:
1490        free(config_filename);
1491        return ret;
1492}
1493
1494/*
1495 * Call this to report error for your variable that should not
1496 * get a boolean value (i.e. "[my] var" means "true").
1497 */
1498int config_error_nonbool(const char *var)
1499{
1500        return error("Missing value for '%s'", var);
1501}