config.con commit config.c:store_write_pair(): don't read the byte before a malloc'd buffer. (6281f39)
   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
  10#define MAXNAME (256)
  11
  12static FILE *config_file;
  13static const char *config_file_name;
  14static int config_linenr;
  15static int zlib_compression_seen;
  16
  17static int get_next_char(void)
  18{
  19        int c;
  20        FILE *f;
  21
  22        c = '\n';
  23        if ((f = config_file) != NULL) {
  24                c = fgetc(f);
  25                if (c == '\r') {
  26                        /* DOS like systems */
  27                        c = fgetc(f);
  28                        if (c != '\n') {
  29                                ungetc(c, f);
  30                                c = '\r';
  31                        }
  32                }
  33                if (c == '\n')
  34                        config_linenr++;
  35                if (c == EOF) {
  36                        config_file = NULL;
  37                        c = '\n';
  38                }
  39        }
  40        return c;
  41}
  42
  43static char *parse_value(void)
  44{
  45        static char value[1024];
  46        int quote = 0, comment = 0, len = 0, space = 0;
  47
  48        for (;;) {
  49                int c = get_next_char();
  50                if (len >= sizeof(value))
  51                        return NULL;
  52                if (c == '\n') {
  53                        if (quote)
  54                                return NULL;
  55                        value[len] = 0;
  56                        return value;
  57                }
  58                if (comment)
  59                        continue;
  60                if (isspace(c) && !quote) {
  61                        space = 1;
  62                        continue;
  63                }
  64                if (!quote) {
  65                        if (c == ';' || c == '#') {
  66                                comment = 1;
  67                                continue;
  68                        }
  69                }
  70                if (space) {
  71                        if (len)
  72                                value[len++] = ' ';
  73                        space = 0;
  74                }
  75                if (c == '\\') {
  76                        c = get_next_char();
  77                        switch (c) {
  78                        case '\n':
  79                                continue;
  80                        case 't':
  81                                c = '\t';
  82                                break;
  83                        case 'b':
  84                                c = '\b';
  85                                break;
  86                        case 'n':
  87                                c = '\n';
  88                                break;
  89                        /* Some characters escape as themselves */
  90                        case '\\': case '"':
  91                                break;
  92                        /* Reject unknown escape sequences */
  93                        default:
  94                                return NULL;
  95                        }
  96                        value[len++] = c;
  97                        continue;
  98                }
  99                if (c == '"') {
 100                        quote = 1-quote;
 101                        continue;
 102                }
 103                value[len++] = c;
 104        }
 105}
 106
 107static inline int iskeychar(int c)
 108{
 109        return isalnum(c) || c == '-';
 110}
 111
 112static int get_value(config_fn_t fn, char *name, unsigned int len)
 113{
 114        int c;
 115        char *value;
 116
 117        /* Get the full name */
 118        for (;;) {
 119                c = get_next_char();
 120                if (c == EOF)
 121                        break;
 122                if (!iskeychar(c))
 123                        break;
 124                name[len++] = tolower(c);
 125                if (len >= MAXNAME)
 126                        return -1;
 127        }
 128        name[len] = 0;
 129        while (c == ' ' || c == '\t')
 130                c = get_next_char();
 131
 132        value = NULL;
 133        if (c != '\n') {
 134                if (c != '=')
 135                        return -1;
 136                value = parse_value();
 137                if (!value)
 138                        return -1;
 139        }
 140        return fn(name, value);
 141}
 142
 143static int get_extended_base_var(char *name, int baselen, int c)
 144{
 145        do {
 146                if (c == '\n')
 147                        return -1;
 148                c = get_next_char();
 149        } while (isspace(c));
 150
 151        /* We require the format to be '[base "extension"]' */
 152        if (c != '"')
 153                return -1;
 154        name[baselen++] = '.';
 155
 156        for (;;) {
 157                int c = get_next_char();
 158                if (c == '\n')
 159                        return -1;
 160                if (c == '"')
 161                        break;
 162                if (c == '\\') {
 163                        c = get_next_char();
 164                        if (c == '\n')
 165                                return -1;
 166                }
 167                name[baselen++] = c;
 168                if (baselen > MAXNAME / 2)
 169                        return -1;
 170        }
 171
 172        /* Final ']' */
 173        if (get_next_char() != ']')
 174                return -1;
 175        return baselen;
 176}
 177
 178static int get_base_var(char *name)
 179{
 180        int baselen = 0;
 181
 182        for (;;) {
 183                int c = get_next_char();
 184                if (c == EOF)
 185                        return -1;
 186                if (c == ']')
 187                        return baselen;
 188                if (isspace(c))
 189                        return get_extended_base_var(name, baselen, c);
 190                if (!iskeychar(c) && c != '.')
 191                        return -1;
 192                if (baselen > MAXNAME / 2)
 193                        return -1;
 194                name[baselen++] = tolower(c);
 195        }
 196}
 197
 198static int git_parse_file(config_fn_t fn)
 199{
 200        int comment = 0;
 201        int baselen = 0;
 202        static char var[MAXNAME];
 203
 204        for (;;) {
 205                int c = get_next_char();
 206                if (c == '\n') {
 207                        /* EOF? */
 208                        if (!config_file)
 209                                return 0;
 210                        comment = 0;
 211                        continue;
 212                }
 213                if (comment || isspace(c))
 214                        continue;
 215                if (c == '#' || c == ';') {
 216                        comment = 1;
 217                        continue;
 218                }
 219                if (c == '[') {
 220                        baselen = get_base_var(var);
 221                        if (baselen <= 0)
 222                                break;
 223                        var[baselen++] = '.';
 224                        var[baselen] = 0;
 225                        continue;
 226                }
 227                if (!isalpha(c))
 228                        break;
 229                var[baselen] = tolower(c);
 230                if (get_value(fn, var, baselen+1) < 0)
 231                        break;
 232        }
 233        die("bad config file line %d in %s", config_linenr, config_file_name);
 234}
 235
 236static unsigned long get_unit_factor(const char *end)
 237{
 238        if (!*end)
 239                return 1;
 240        else if (!strcasecmp(end, "k"))
 241                return 1024;
 242        else if (!strcasecmp(end, "m"))
 243                return 1024 * 1024;
 244        else if (!strcasecmp(end, "g"))
 245                return 1024 * 1024 * 1024;
 246        die("unknown unit: '%s'", end);
 247}
 248
 249int git_parse_long(const char *value, long *ret)
 250{
 251        if (value && *value) {
 252                char *end;
 253                long val = strtol(value, &end, 0);
 254                *ret = val * get_unit_factor(end);
 255                return 1;
 256        }
 257        return 0;
 258}
 259
 260int git_parse_ulong(const char *value, unsigned long *ret)
 261{
 262        if (value && *value) {
 263                char *end;
 264                unsigned long val = strtoul(value, &end, 0);
 265                *ret = val * get_unit_factor(end);
 266                return 1;
 267        }
 268        return 0;
 269}
 270
 271int git_config_int(const char *name, const char *value)
 272{
 273        long ret;
 274        if (!git_parse_long(value, &ret))
 275                die("bad config value for '%s' in %s", name, config_file_name);
 276        return ret;
 277}
 278
 279unsigned long git_config_ulong(const char *name, const char *value)
 280{
 281        unsigned long ret;
 282        if (!git_parse_ulong(value, &ret))
 283                die("bad config value for '%s' in %s", name, config_file_name);
 284        return ret;
 285}
 286
 287int git_config_bool(const char *name, const char *value)
 288{
 289        if (!value)
 290                return 1;
 291        if (!*value)
 292                return 0;
 293        if (!strcasecmp(value, "true") || !strcasecmp(value, "yes"))
 294                return 1;
 295        if (!strcasecmp(value, "false") || !strcasecmp(value, "no"))
 296                return 0;
 297        return git_config_int(name, value) != 0;
 298}
 299
 300int git_default_config(const char *var, const char *value)
 301{
 302        /* This needs a better name */
 303        if (!strcmp(var, "core.filemode")) {
 304                trust_executable_bit = git_config_bool(var, value);
 305                return 0;
 306        }
 307
 308        if (!strcmp(var, "core.quotepath")) {
 309                quote_path_fully = git_config_bool(var, value);
 310                return 0;
 311        }
 312
 313        if (!strcmp(var, "core.symlinks")) {
 314                has_symlinks = git_config_bool(var, value);
 315                return 0;
 316        }
 317
 318        if (!strcmp(var, "core.bare")) {
 319                is_bare_repository_cfg = git_config_bool(var, value);
 320                return 0;
 321        }
 322
 323        if (!strcmp(var, "core.ignorestat")) {
 324                assume_unchanged = git_config_bool(var, value);
 325                return 0;
 326        }
 327
 328        if (!strcmp(var, "core.prefersymlinkrefs")) {
 329                prefer_symlink_refs = git_config_bool(var, value);
 330                return 0;
 331        }
 332
 333        if (!strcmp(var, "core.logallrefupdates")) {
 334                log_all_ref_updates = git_config_bool(var, value);
 335                return 0;
 336        }
 337
 338        if (!strcmp(var, "core.warnambiguousrefs")) {
 339                warn_ambiguous_refs = git_config_bool(var, value);
 340                return 0;
 341        }
 342
 343        if (!strcmp(var, "core.loosecompression")) {
 344                int level = git_config_int(var, value);
 345                if (level == -1)
 346                        level = Z_DEFAULT_COMPRESSION;
 347                else if (level < 0 || level > Z_BEST_COMPRESSION)
 348                        die("bad zlib compression level %d", level);
 349                zlib_compression_level = level;
 350                zlib_compression_seen = 1;
 351                return 0;
 352        }
 353
 354        if (!strcmp(var, "core.compression")) {
 355                int level = git_config_int(var, value);
 356                if (level == -1)
 357                        level = Z_DEFAULT_COMPRESSION;
 358                else if (level < 0 || level > Z_BEST_COMPRESSION)
 359                        die("bad zlib compression level %d", level);
 360                core_compression_level = level;
 361                core_compression_seen = 1;
 362                if (!zlib_compression_seen)
 363                        zlib_compression_level = level;
 364                return 0;
 365        }
 366
 367        if (!strcmp(var, "core.packedgitwindowsize")) {
 368                int pgsz_x2 = getpagesize() * 2;
 369                packed_git_window_size = git_config_int(var, value);
 370
 371                /* This value must be multiple of (pagesize * 2) */
 372                packed_git_window_size /= pgsz_x2;
 373                if (packed_git_window_size < 1)
 374                        packed_git_window_size = 1;
 375                packed_git_window_size *= pgsz_x2;
 376                return 0;
 377        }
 378
 379        if (!strcmp(var, "core.packedgitlimit")) {
 380                packed_git_limit = git_config_int(var, value);
 381                return 0;
 382        }
 383
 384        if (!strcmp(var, "core.deltabasecachelimit")) {
 385                delta_base_cache_limit = git_config_int(var, value);
 386                return 0;
 387        }
 388
 389        if (!strcmp(var, "core.autocrlf")) {
 390                if (value && !strcasecmp(value, "input")) {
 391                        auto_crlf = -1;
 392                        return 0;
 393                }
 394                auto_crlf = git_config_bool(var, value);
 395                return 0;
 396        }
 397
 398        if (!strcmp(var, "user.name")) {
 399                strlcpy(git_default_name, value, sizeof(git_default_name));
 400                return 0;
 401        }
 402
 403        if (!strcmp(var, "user.email")) {
 404                strlcpy(git_default_email, value, sizeof(git_default_email));
 405                return 0;
 406        }
 407
 408        if (!strcmp(var, "i18n.commitencoding")) {
 409                git_commit_encoding = xstrdup(value);
 410                return 0;
 411        }
 412
 413        if (!strcmp(var, "i18n.logoutputencoding")) {
 414                git_log_output_encoding = xstrdup(value);
 415                return 0;
 416        }
 417
 418
 419        if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
 420                pager_use_color = git_config_bool(var,value);
 421                return 0;
 422        }
 423
 424        if (!strcmp(var, "core.pager")) {
 425                pager_program = xstrdup(value);
 426                return 0;
 427        }
 428
 429        if (!strcmp(var, "core.editor")) {
 430                editor_program = xstrdup(value);
 431                return 0;
 432        }
 433
 434        if (!strcmp(var, "core.excludesfile")) {
 435                if (!value)
 436                        die("core.excludesfile without value");
 437                excludes_file = xstrdup(value);
 438                return 0;
 439        }
 440
 441        /* Add other config variables here and to Documentation/config.txt. */
 442        return 0;
 443}
 444
 445int git_config_from_file(config_fn_t fn, const char *filename)
 446{
 447        int ret;
 448        FILE *f = fopen(filename, "r");
 449
 450        ret = -1;
 451        if (f) {
 452                config_file = f;
 453                config_file_name = filename;
 454                config_linenr = 1;
 455                ret = git_parse_file(fn);
 456                fclose(f);
 457                config_file_name = NULL;
 458        }
 459        return ret;
 460}
 461
 462int git_config(config_fn_t fn)
 463{
 464        int ret = 0;
 465        char *repo_config = NULL;
 466        const char *home = NULL, *filename;
 467
 468        /* $GIT_CONFIG makes git read _only_ the given config file,
 469         * $GIT_CONFIG_LOCAL will make it process it in addition to the
 470         * global config file, the same way it would the per-repository
 471         * config file otherwise. */
 472        filename = getenv(CONFIG_ENVIRONMENT);
 473        if (!filename) {
 474                if (!access(ETC_GITCONFIG, R_OK))
 475                        ret += git_config_from_file(fn, ETC_GITCONFIG);
 476                home = getenv("HOME");
 477                filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
 478                if (!filename)
 479                        filename = repo_config = xstrdup(git_path("config"));
 480        }
 481
 482        if (home) {
 483                char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
 484                if (!access(user_config, R_OK))
 485                        ret = git_config_from_file(fn, user_config);
 486                free(user_config);
 487        }
 488
 489        ret += git_config_from_file(fn, filename);
 490        free(repo_config);
 491        return ret;
 492}
 493
 494/*
 495 * Find all the stuff for git_config_set() below.
 496 */
 497
 498#define MAX_MATCHES 512
 499
 500static struct {
 501        int baselen;
 502        char* key;
 503        int do_not_match;
 504        regex_t* value_regex;
 505        int multi_replace;
 506        size_t offset[MAX_MATCHES];
 507        enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
 508        int seen;
 509} store;
 510
 511static int matches(const char* key, const char* value)
 512{
 513        return !strcmp(key, store.key) &&
 514                (store.value_regex == NULL ||
 515                 (store.do_not_match ^
 516                  !regexec(store.value_regex, value, 0, NULL, 0)));
 517}
 518
 519static int store_aux(const char* key, const char* value)
 520{
 521        const char *ep;
 522        size_t section_len;
 523
 524        switch (store.state) {
 525        case KEY_SEEN:
 526                if (matches(key, value)) {
 527                        if (store.seen == 1 && store.multi_replace == 0) {
 528                                fprintf(stderr,
 529                                        "Warning: %s has multiple values\n",
 530                                        key);
 531                        } else if (store.seen >= MAX_MATCHES) {
 532                                fprintf(stderr, "Too many matches\n");
 533                                return 1;
 534                        }
 535
 536                        store.offset[store.seen] = ftell(config_file);
 537                        store.seen++;
 538                }
 539                break;
 540        case SECTION_SEEN:
 541                /*
 542                 * What we are looking for is in store.key (both
 543                 * section and var), and its section part is baselen
 544                 * long.  We found key (again, both section and var).
 545                 * We would want to know if this key is in the same
 546                 * section as what we are looking for.  We already
 547                 * know we are in the same section as what should
 548                 * hold store.key.
 549                 */
 550                ep = strrchr(key, '.');
 551                section_len = ep - key;
 552
 553                if ((section_len != store.baselen) ||
 554                    memcmp(key, store.key, section_len+1)) {
 555                        store.state = SECTION_END_SEEN;
 556                        break;
 557                }
 558
 559                /*
 560                 * Do not increment matches: this is no match, but we
 561                 * just made sure we are in the desired section.
 562                 */
 563                store.offset[store.seen] = ftell(config_file);
 564                /* fallthru */
 565        case SECTION_END_SEEN:
 566        case START:
 567                if (matches(key, value)) {
 568                        store.offset[store.seen] = ftell(config_file);
 569                        store.state = KEY_SEEN;
 570                        store.seen++;
 571                } else {
 572                        if (strrchr(key, '.') - key == store.baselen &&
 573                              !strncmp(key, store.key, store.baselen)) {
 574                                        store.state = SECTION_SEEN;
 575                                        store.offset[store.seen] = ftell(config_file);
 576                        }
 577                }
 578        }
 579        return 0;
 580}
 581
 582static int write_error(void)
 583{
 584        fprintf(stderr, "Failed to write new configuration file\n");
 585
 586        /* Same error code as "failed to rename". */
 587        return 4;
 588}
 589
 590static int store_write_section(int fd, const char* key)
 591{
 592        const char *dot = strchr(key, '.');
 593        int len1 = store.baselen, len2 = -1;
 594
 595        dot = strchr(key, '.');
 596        if (dot) {
 597                int dotlen = dot - key;
 598                if (dotlen < len1) {
 599                        len2 = len1 - dotlen - 1;
 600                        len1 = dotlen;
 601                }
 602        }
 603
 604        if (write_in_full(fd, "[", 1) != 1 ||
 605            write_in_full(fd, key, len1) != len1)
 606                return 0;
 607        if (len2 >= 0) {
 608                if (write_in_full(fd, " \"", 2) != 2)
 609                        return 0;
 610                while (--len2 >= 0) {
 611                        unsigned char c = *++dot;
 612                        if (c == '"')
 613                                if (write_in_full(fd, "\\", 1) != 1)
 614                                        return 0;
 615                        if (write_in_full(fd, &c, 1) != 1)
 616                                return 0;
 617                }
 618                if (write_in_full(fd, "\"", 1) != 1)
 619                        return 0;
 620        }
 621        if (write_in_full(fd, "]\n", 2) != 2)
 622                return 0;
 623
 624        return 1;
 625}
 626
 627static int store_write_pair(int fd, const char* key, const char* value)
 628{
 629        int i;
 630        int length = strlen(key+store.baselen+1);
 631        int quote = 0;
 632
 633        /*
 634         * Check to see if the value needs to be surrounded with a dq pair.
 635         * Note that problematic characters are always backslash-quoted; this
 636         * check is about not losing leading or trailing SP and strings that
 637         * follow beginning-of-comment characters (i.e. ';' and '#') by the
 638         * configuration parser.
 639         */
 640        if (value[0] == ' ')
 641                quote = 1;
 642        for (i = 0; value[i]; i++)
 643                if (value[i] == ';' || value[i] == '#')
 644                        quote = 1;
 645        if (i && value[i-1] == ' ')
 646                quote = 1;
 647
 648        if (write_in_full(fd, "\t", 1) != 1 ||
 649            write_in_full(fd, key+store.baselen+1, length) != length ||
 650            write_in_full(fd, " = ", 3) != 3)
 651                return 0;
 652        if (quote && write_in_full(fd, "\"", 1) != 1)
 653                return 0;
 654        for (i = 0; value[i]; i++)
 655                switch (value[i]) {
 656                case '\n':
 657                        if (write_in_full(fd, "\\n", 2) != 2)
 658                                return 0;
 659                        break;
 660                case '\t':
 661                        if (write_in_full(fd, "\\t", 2) != 2)
 662                                return 0;
 663                        break;
 664                case '"':
 665                case '\\':
 666                        if (write_in_full(fd, "\\", 1) != 1)
 667                                return 0;
 668                default:
 669                        if (write_in_full(fd, value+i, 1) != 1)
 670                                return 0;
 671                        break;
 672                }
 673        if (quote && write_in_full(fd, "\"", 1) != 1)
 674                return 0;
 675        if (write_in_full(fd, "\n", 1) != 1)
 676                return 0;
 677        return 1;
 678}
 679
 680static ssize_t find_beginning_of_line(const char* contents, size_t size,
 681        size_t offset_, int* found_bracket)
 682{
 683        size_t equal_offset = size, bracket_offset = size;
 684        ssize_t offset;
 685
 686        for (offset = offset_-2; offset > 0
 687                        && contents[offset] != '\n'; offset--)
 688                switch (contents[offset]) {
 689                        case '=': equal_offset = offset; break;
 690                        case ']': bracket_offset = offset; break;
 691                }
 692        if (bracket_offset < equal_offset) {
 693                *found_bracket = 1;
 694                offset = bracket_offset+1;
 695        } else
 696                offset++;
 697
 698        return offset;
 699}
 700
 701int git_config_set(const char* key, const char* value)
 702{
 703        return git_config_set_multivar(key, value, NULL, 0);
 704}
 705
 706/*
 707 * If value==NULL, unset in (remove from) config,
 708 * if value_regex!=NULL, disregard key/value pairs where value does not match.
 709 * if multi_replace==0, nothing, or only one matching key/value is replaced,
 710 *     else all matching key/values (regardless how many) are removed,
 711 *     before the new pair is written.
 712 *
 713 * Returns 0 on success.
 714 *
 715 * This function does this:
 716 *
 717 * - it locks the config file by creating ".git/config.lock"
 718 *
 719 * - it then parses the config using store_aux() as validator to find
 720 *   the position on the key/value pair to replace. If it is to be unset,
 721 *   it must be found exactly once.
 722 *
 723 * - the config file is mmap()ed and the part before the match (if any) is
 724 *   written to the lock file, then the changed part and the rest.
 725 *
 726 * - the config file is removed and the lock file rename()d to it.
 727 *
 728 */
 729int git_config_set_multivar(const char* key, const char* value,
 730        const char* value_regex, int multi_replace)
 731{
 732        int i, dot;
 733        int fd = -1, in_fd;
 734        int ret;
 735        char* config_filename;
 736        struct lock_file *lock = NULL;
 737        const char* last_dot = strrchr(key, '.');
 738
 739        config_filename = getenv(CONFIG_ENVIRONMENT);
 740        if (!config_filename) {
 741                config_filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
 742                if (!config_filename)
 743                        config_filename  = git_path("config");
 744        }
 745        config_filename = xstrdup(config_filename);
 746
 747        /*
 748         * Since "key" actually contains the section name and the real
 749         * key name separated by a dot, we have to know where the dot is.
 750         */
 751
 752        if (last_dot == NULL) {
 753                fprintf(stderr, "key does not contain a section: %s\n", key);
 754                ret = 2;
 755                goto out_free;
 756        }
 757        store.baselen = last_dot - key;
 758
 759        store.multi_replace = multi_replace;
 760
 761        /*
 762         * Validate the key and while at it, lower case it for matching.
 763         */
 764        store.key = xmalloc(strlen(key) + 1);
 765        dot = 0;
 766        for (i = 0; key[i]; i++) {
 767                unsigned char c = key[i];
 768                if (c == '.')
 769                        dot = 1;
 770                /* Leave the extended basename untouched.. */
 771                if (!dot || i > store.baselen) {
 772                        if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
 773                                fprintf(stderr, "invalid key: %s\n", key);
 774                                free(store.key);
 775                                ret = 1;
 776                                goto out_free;
 777                        }
 778                        c = tolower(c);
 779                } else if (c == '\n') {
 780                        fprintf(stderr, "invalid key (newline): %s\n", key);
 781                        free(store.key);
 782                        ret = 1;
 783                        goto out_free;
 784                }
 785                store.key[i] = c;
 786        }
 787        store.key[i] = 0;
 788
 789        /*
 790         * The lock serves a purpose in addition to locking: the new
 791         * contents of .git/config will be written into it.
 792         */
 793        lock = xcalloc(sizeof(struct lock_file), 1);
 794        fd = hold_lock_file_for_update(lock, config_filename, 0);
 795        if (fd < 0) {
 796                fprintf(stderr, "could not lock config file\n");
 797                free(store.key);
 798                ret = -1;
 799                goto out_free;
 800        }
 801
 802        /*
 803         * If .git/config does not exist yet, write a minimal version.
 804         */
 805        in_fd = open(config_filename, O_RDONLY);
 806        if ( in_fd < 0 ) {
 807                free(store.key);
 808
 809                if ( ENOENT != errno ) {
 810                        error("opening %s: %s", config_filename,
 811                              strerror(errno));
 812                        ret = 3; /* same as "invalid config file" */
 813                        goto out_free;
 814                }
 815                /* if nothing to unset, error out */
 816                if (value == NULL) {
 817                        ret = 5;
 818                        goto out_free;
 819                }
 820
 821                store.key = (char*)key;
 822                if (!store_write_section(fd, key) ||
 823                    !store_write_pair(fd, key, value))
 824                        goto write_err_out;
 825        } else {
 826                struct stat st;
 827                char* contents;
 828                size_t contents_sz, copy_begin, copy_end;
 829                int i, new_line = 0;
 830
 831                if (value_regex == NULL)
 832                        store.value_regex = NULL;
 833                else {
 834                        if (value_regex[0] == '!') {
 835                                store.do_not_match = 1;
 836                                value_regex++;
 837                        } else
 838                                store.do_not_match = 0;
 839
 840                        store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
 841                        if (regcomp(store.value_regex, value_regex,
 842                                        REG_EXTENDED)) {
 843                                fprintf(stderr, "Invalid pattern: %s\n",
 844                                        value_regex);
 845                                free(store.value_regex);
 846                                ret = 6;
 847                                goto out_free;
 848                        }
 849                }
 850
 851                store.offset[0] = 0;
 852                store.state = START;
 853                store.seen = 0;
 854
 855                /*
 856                 * After this, store.offset will contain the *end* offset
 857                 * of the last match, or remain at 0 if no match was found.
 858                 * As a side effect, we make sure to transform only a valid
 859                 * existing config file.
 860                 */
 861                if (git_config_from_file(store_aux, config_filename)) {
 862                        fprintf(stderr, "invalid config file\n");
 863                        free(store.key);
 864                        if (store.value_regex != NULL) {
 865                                regfree(store.value_regex);
 866                                free(store.value_regex);
 867                        }
 868                        ret = 3;
 869                        goto out_free;
 870                }
 871
 872                free(store.key);
 873                if (store.value_regex != NULL) {
 874                        regfree(store.value_regex);
 875                        free(store.value_regex);
 876                }
 877
 878                /* if nothing to unset, or too many matches, error out */
 879                if ((store.seen == 0 && value == NULL) ||
 880                                (store.seen > 1 && multi_replace == 0)) {
 881                        ret = 5;
 882                        goto out_free;
 883                }
 884
 885                fstat(in_fd, &st);
 886                contents_sz = xsize_t(st.st_size);
 887                contents = xmmap(NULL, contents_sz, PROT_READ,
 888                        MAP_PRIVATE, in_fd, 0);
 889                close(in_fd);
 890
 891                if (store.seen == 0)
 892                        store.seen = 1;
 893
 894                for (i = 0, copy_begin = 0; i < store.seen; i++) {
 895                        if (store.offset[i] == 0) {
 896                                store.offset[i] = copy_end = contents_sz;
 897                        } else if (store.state != KEY_SEEN) {
 898                                copy_end = store.offset[i];
 899                        } else
 900                                copy_end = find_beginning_of_line(
 901                                        contents, contents_sz,
 902                                        store.offset[i]-2, &new_line);
 903
 904                        /* write the first part of the config */
 905                        if (copy_end > copy_begin) {
 906                                if (write_in_full(fd, contents + copy_begin,
 907                                                  copy_end - copy_begin) <
 908                                    copy_end - copy_begin)
 909                                        goto write_err_out;
 910                                if (new_line &&
 911                                    write_in_full(fd, "\n", 1) != 1)
 912                                        goto write_err_out;
 913                        }
 914                        copy_begin = store.offset[i];
 915                }
 916
 917                /* write the pair (value == NULL means unset) */
 918                if (value != NULL) {
 919                        if (store.state == START) {
 920                                if (!store_write_section(fd, key))
 921                                        goto write_err_out;
 922                        }
 923                        if (!store_write_pair(fd, key, value))
 924                                goto write_err_out;
 925                }
 926
 927                /* write the rest of the config */
 928                if (copy_begin < contents_sz)
 929                        if (write_in_full(fd, contents + copy_begin,
 930                                          contents_sz - copy_begin) <
 931                            contents_sz - copy_begin)
 932                                goto write_err_out;
 933
 934                munmap(contents, contents_sz);
 935        }
 936
 937        if (close(fd) || commit_lock_file(lock) < 0) {
 938                fprintf(stderr, "Cannot commit config file!\n");
 939                ret = 4;
 940                goto out_free;
 941        }
 942
 943        /* fd is closed, so don't try to close it below. */
 944        fd = -1;
 945        /*
 946         * lock is committed, so don't try to roll it back below.
 947         * NOTE: Since lockfile.c keeps a linked list of all created
 948         * lock_file structures, it isn't safe to free(lock).  It's
 949         * better to just leave it hanging around.
 950         */
 951        lock = NULL;
 952        ret = 0;
 953
 954out_free:
 955        if (0 <= fd)
 956                close(fd);
 957        if (lock)
 958                rollback_lock_file(lock);
 959        free(config_filename);
 960        return ret;
 961
 962write_err_out:
 963        ret = write_error();
 964        goto out_free;
 965
 966}
 967
 968static int section_name_match (const char *buf, const char *name)
 969{
 970        int i = 0, j = 0, dot = 0;
 971        for (; buf[i] && buf[i] != ']'; i++) {
 972                if (!dot && isspace(buf[i])) {
 973                        dot = 1;
 974                        if (name[j++] != '.')
 975                                break;
 976                        for (i++; isspace(buf[i]); i++)
 977                                ; /* do nothing */
 978                        if (buf[i] != '"')
 979                                break;
 980                        continue;
 981                }
 982                if (buf[i] == '\\' && dot)
 983                        i++;
 984                else if (buf[i] == '"' && dot) {
 985                        for (i++; isspace(buf[i]); i++)
 986                                ; /* do_nothing */
 987                        break;
 988                }
 989                if (buf[i] != name[j++])
 990                        break;
 991        }
 992        return (buf[i] == ']' && name[j] == 0);
 993}
 994
 995/* if new_name == NULL, the section is removed instead */
 996int git_config_rename_section(const char *old_name, const char *new_name)
 997{
 998        int ret = 0, remove = 0;
 999        char *config_filename;
1000        struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1001        int out_fd;
1002        char buf[1024];
1003
1004        config_filename = getenv(CONFIG_ENVIRONMENT);
1005        if (!config_filename) {
1006                config_filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
1007                if (!config_filename)
1008                        config_filename  = git_path("config");
1009        }
1010        config_filename = xstrdup(config_filename);
1011        out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1012        if (out_fd < 0) {
1013                ret = error("Could not lock config file!");
1014                goto out;
1015        }
1016
1017        if (!(config_file = fopen(config_filename, "rb"))) {
1018                /* no config file means nothing to rename, no error */
1019                goto unlock_and_out;
1020        }
1021
1022        while (fgets(buf, sizeof(buf), config_file)) {
1023                int i;
1024                int length;
1025                for (i = 0; buf[i] && isspace(buf[i]); i++)
1026                        ; /* do nothing */
1027                if (buf[i] == '[') {
1028                        /* it's a section */
1029                        if (section_name_match (&buf[i+1], old_name)) {
1030                                ret++;
1031                                if (new_name == NULL) {
1032                                        remove = 1;
1033                                        continue;
1034                                }
1035                                store.baselen = strlen(new_name);
1036                                if (!store_write_section(out_fd, new_name)) {
1037                                        ret = write_error();
1038                                        goto out;
1039                                }
1040                                continue;
1041                        }
1042                        remove = 0;
1043                }
1044                if (remove)
1045                        continue;
1046                length = strlen(buf);
1047                if (write_in_full(out_fd, buf, length) != length) {
1048                        ret = write_error();
1049                        goto out;
1050                }
1051        }
1052        fclose(config_file);
1053 unlock_and_out:
1054        if (close(out_fd) || commit_lock_file(lock) < 0)
1055                        ret = error("Cannot commit config file!");
1056 out:
1057        free(config_filename);
1058        return ret;
1059}