config: reject bogus section names for --rename-section

You can feed junk to "git config --rename-section", which will result in a config file that git will not even parse (so you cannot fix it with git-config). We already have syntactic sanity checks when setting a variable; let's do the same for section names. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Apr 25, 2012 at 21:47 UTC 94a35b1aea88f1ad882cdd111e01410fb6d3eb46
2 files changed +31 -1
config.c
+23 -1
@@ -1552,20 +1552,42 @@ static int section_name_match (const char *buf, const char *name)
1552 return 0;
1553 }
1554
1555 +static int section_name_is_ok(const char *name)
1556 +{
1557 + /* Empty section names are bogus. */
1558 + if (!*name)
1559 + return 0;
1560 +
1561 + /*
1562 + * Before a dot, we must be alphanumeric or dash. After the first dot,
1563 + * anything goes, so we can stop checking.
1564 + */
1565 + for (; *name && *name != '.'; name++)
1566 + if (*name != '-' && !isalnum(*name))
1567 + return 0;
1568 + return 1;
1569 +}
1570 +
1571 /* if new_name == NULL, the section is removed instead */
1572 int git_config_rename_section_in_file(const char *config_filename,
1573 const char *old_name, const char *new_name)
1574 {
1575 int ret = 0, remove = 0;
1576 char *filename_buf = NULL;
1561 - struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1577 + struct lock_file *lock;
1578 int out_fd;
1579 char buf[1024];
1580 FILE *config_file;
1581
1582 + if (new_name && !section_name_is_ok(new_name)) {
1583 + ret = error("invalid section name: %s", new_name);
1584 + goto out;
1585 + }
1586 +
1587 if (!config_filename)
1588 config_filename = filename_buf = git_pathdup("config");
1589
1590 + lock = xcalloc(sizeof(struct lock_file), 1);
1591 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1592 if (out_fd < 0) {
1593 ret = error("could not lock config file %s", config_filename);
t/t1300-repo-config.sh
+8
@@ -550,6 +550,14 @@ EOF
550
551 test_expect_success "rename succeeded" "test_cmp expect .git/config"
552
553 +test_expect_success 'renaming empty section name is rejected' '
554 + test_must_fail git config --rename-section branch.zwei ""
555 +'
556 +
557 +test_expect_success 'renaming to bogus section is rejected' '
558 + test_must_fail git config --rename-section branch.zwei "bogus name"
559 +'
560 +
561 cat >> .git/config << EOF
562 [branch "zwei"] a = 1 [branch "vier"]
563 EOF