This avoids the following behavior which is possible with some non UTF-8
locales:

    $ printf '.x\261!#^:s\\LS_COLORS\\\47 ;touch hello;echo \47\n' \
        > .dircolors
    $ ls -d hello
    ls: cannot access 'hello': No such file or directory
    $ LC_ALL=zh_CN.gbk tcsh -f -c 'eval "`src/dircolors -c .dircolors`"'
    setenv LS_COLORS '*.x�\'''= ; touch hello ; echo '\'':'
    \:
    $ ls -d hello
    hello

* src/dircolors.c (append_quoted): Make sure a backslash before '!' is
placed after a single quote.
* tests/misc/dircolors.pl (@Tests): Adjust a test case and add two
additional ones.

Discovered by Anthropic's OSS Scanner, as bug ANT-2026-WSXNQH8Y.
---
 src/dircolors.c         | 17 ++++++++++++++---
 tests/misc/dircolors.pl |  9 +++++++--
 2 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/src/dircolors.c b/src/dircolors.c
index 9cdc309d0..18cb28257 100644
--- a/src/dircolors.c
+++ b/src/dircolors.c
@@ -239,10 +239,21 @@ append_quoted (char const *str)
             break;
 
           case '!':
-            /* Prevent 'csh' from doing history substitution.  */
-            if (syntax == SHELL_SYNTAX_C)
-              APPEND_CHAR ('\\');
             need_backslash = true;
+            if (syntax == SHELL_SYNTAX_C)
+              {
+                /* Prevent 'csh' from doing history substitution.
+                   Make sure that the backslash always follows a single
+                   quote to prevent the previous character from combining
+                   with a backslash to create a single multi-byte character,
+                   leaving the '!' unescaped.  */
+                APPEND_CHAR ('\'');
+                APPEND_CHAR ('\\');
+                APPEND_CHAR ('!');
+                APPEND_CHAR ('\'');
+                ++str;
+                continue;
+              }
             break;
 
           case ':':
diff --git a/tests/misc/dircolors.pl b/tests/misc/dircolors.pl
index 9abe35869..bd6448b0c 100755
--- a/tests/misc/dircolors.pl
+++ b/tests/misc/dircolors.pl
@@ -79,10 +79,15 @@ my @Tests =
      ['print-ls-colors', '--print-ls-colors', {IN => "OWT 40;33\n"},
       {OUT => "\x1B[40;33mtw\t40;33\x1B[0m\n"}],
 
-     ['csh-history-sub', '-c',
+     ['csh-history-sub-1', '-c',
       {IN => "*.a!#^:s\\LS_COLORS\\' ; touch ./a; echo '\n"},
-      {OUT => ("setenv LS_COLORS '*.a\\!#^:s\\LS_COLORS\\'\\''=; "
+      {OUT => ("setenv LS_COLORS '*.a'\\!'#^:s\\LS_COLORS\\'\\''=; "
                . "touch ./a; echo '\\'':'\n")}],
+     ['csh-history-sub-2', '-c', {IN => "*.a\xB1!b 01;31\n"},
+      {OUT => "setenv LS_COLORS '*.a\xB1'\\!'b=01;31:'\n"}],
+
+     ['sh-no-history-sub-1', '-b', {IN => "*.a!b 01;31\n"},
+      {OUT => "LS_COLORS='*.a!b=01;31:';\nexport LS_COLORS\n"}],
 
      # CAREFUL: always specify the -b option, unless explicitly testing
      # for csh syntax output, or --print-ls-color output.
-- 
2.56.1


Reply via email to