Skip to content

Fix file URL for Terminal.app using a UTF-8 locale - #2601

Closed
ghost wants to merge 2 commits into
masterfrom
unknown repository
Closed

ghost wants to merge 2 commits into
masterfrom
unknown repository

Conversation

@ghost

@ghost ghost commented Dec 11, 2015

Copy link
Copy Markdown

Steps to reproduce the problem (locale is en_US.UTF-8):

  1. mkdir Äpfel
  2. cd Äpfel
  3. switch to a new tab with the same setting and $PWD by pressing cmd-T
  4. now $PWD is /Users/myname

Solution: Set locale to C in order to read one byte at a time, so the expected output %XX does not become %XXX or %XXXX.

@faho

faho commented Dec 12, 2015

Copy link
Copy Markdown
Member

This fix will result in sed being run with a different locale than the rest of the function, since you're not exporting LC_ALL. I'm not sure if that can cause issues, though.

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

UTF-8 is ASCII compatible.

@faho

faho commented Dec 12, 2015

Copy link
Copy Markdown
Member

UTF-8 is ASCII-compatible for those characters that are in ASCII, and then only if you ignore the 8th bit (which pretty much everyone does nowadays).

But that doesn't quite answer the question. Is there a failure case?

Thinking further about it, sed isn't the issue - printf is. Can that deal with getting incomplete UTF-8 characters? Because it'll be running in a UTF-8 locale. And since "Ä" is already two-byte, it apparently can.

I still don't quite like the solution here, but it's probably necessary since Terminal.app seems to expect it that way. Does it break any other terminals that use this function?

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

@faho

faho commented Dec 12, 2015

Copy link
Copy Markdown
Member

Though it's weird that in #2598, command printf (I guess that means the OSX one, which is probably a bsd-ish one) works without hacking the locale.

Builtin printf is an import of a rather old version of GNU printf, IIRC, so it's possible there's bugs _there. Could you check if it works with a new GNU printf as well?

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

Sorry, I gave the wrong evidence above. But I believe that the POSIX stardard allowed locale "C" to deal with UTF-8 strings. I'll look into the source code again later.

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

For your concerns about the BSD one:

$ type -a printf
printf is a builtin
printf is /opt/local/libexec/gnubin/printf
printf is /usr/bin/printf

$ echo $PATH
... /opt/local/libexec/gnubin /Users/myname/.local/opt/fish/bin ... /usr/bin ...
# And printf is a builtin, not in fish/bin

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

No, I've said that his code causes problems (with the gnu one on my mac). The original one used in the repo is the builtin.

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

Using /usr/bin/printf from mac cause no warinings, but the problems are still there: Wrong proxy icon & switch to a wrong path. And I don't know if /usr/bin/printf works for other terminals.

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

The warnings from the newer GNU printf on my mac are caused by "'"$lines"'". It takes the other characters after the first ' and one following character as invalid arguments. However, the correct result is still print to stdout. By directing stderr to /dev/null, my gnu printf can work for these issues too (with LC_ALL=C).

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

I've modified the patch, also make the code more readable and forward-compatible (although fish is using a modified version of the gnu printf).

New GNU printf manual: http://www.gnu.org/software/coreutils/manual/html_node/printf-invocation.html

If the leading character of a numeric argument is ‘"’ or ‘'’ then its value is the numeric value of the immediately following character. Any remaining characters are silently ignored if the POSIXLY_CORRECT environment variable is set; otherwise, a warning is printed. For example, ‘printf "%d" "'a"’ outputs ‘97’ on hosts that use the ASCII character set, since ‘a’ has the numeric value 97 in ASCII.

The corresponding source code of the builtin printf:

void builtin_printf_state_t::verify_numeric(const wchar_t *s, const wchar_t *end, int errcode)
{
if (errcode != 0)
{
this->fatal_error(L"%ls: %s", s, strerror(errcode));
}
else if (*end)
{
if (s == end)
this->fatal_error(_(L"%ls: expected a numeric value"), s);
else
this->fatal_error(_(L"%ls: value not completely converted"), s);
}
}
template<typename T>
static T raw_string_to_scalar_type(const wchar_t *s, wchar_t ** end);
// we use wcstoll instead of wcstoimax because FreeBSD 8 has busted wcstoumax and wcstoimax - see #626
template<>
intmax_t raw_string_to_scalar_type(const wchar_t *s, wchar_t ** end)
{
return wcstoll(s, end, 0);
}
template<>
uintmax_t raw_string_to_scalar_type(const wchar_t *s, wchar_t ** end)
{
return wcstoull(s, end, 0);
}
template<>
long double raw_string_to_scalar_type(const wchar_t *s, wchar_t ** end)
{
return C_STRTOD(s, end);
}
template<typename T>
static T string_to_scalar_type(const wchar_t *s, builtin_printf_state_t *state)
{
T val;
if (*s == L'\"' || *s == L'\'')
{
wchar_t ch = *++s;
val = ch;
}
else
{
wchar_t *end = NULL;
errno = 0;
val = raw_string_to_scalar_type<T>(s, &end);
state->verify_numeric(s, end, errno);
}
return val;
}

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

For other terminals (VTE-based, gnome-terminal in #906), I think the builtin printf does not care about locale when getting the scalar value from a wide character. So we must know the spec of the file URI. I guess it is in https://en.wikipedia.org/wiki/File_URI_scheme ??

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

From RFC1630:

escape                 % hex hex

and RFC1738:

escape         = "%" hex hex

If so, we should read one byte at a time.

@ghost

ghost commented Dec 12, 2015

Copy link
Copy Markdown
Author

Changed again for dealing with NUL and EOL.

@faho

faho commented Dec 13, 2015

Copy link
Copy Markdown
Member

Can anyone with access to Terminal.app test this? @ridiculousfish?

@krader1961

Copy link
Copy Markdown
Contributor

@faho I've confirmed that the problem exists without this change and does not exist with it applied on Mac OS X 10.11.2 (the most recent version available). But there is a bug. Note that the set -l LC_ALL C removes the exported attribute if that var was already exported. You can see this for yourself:

$ set -x LC_ALL en_US.UTF-8
$ env | grep LC_ALL
LC_ALL=en_US.UTF-8
$ function wtf
    set -l LC_ALL C
    env
end
$ wtf | grep LC_ALL
$ echo LC_ALL
en_US.UTF-8
$ env | grep LC_ALL

Notice that after invoking wtf the LC_ALL var is still defined but is no longer in the subprocess environment. This is arguably a fish bug but it does mean this fix can't be accepted as is until that bug is fixed or alternatively the set -l LC_ALL in this change should become set -lx LC_CALL.

@faho

faho commented Dec 14, 2015

Copy link
Copy Markdown
Member

Note that the set -l LC_ALL C removes the exported attribute if that var was already exported.

Wow! That deserves its own issue I think.

This is arguably a fish bug

I do believe so.

alternatively the set -l LC_ALL in this change should become set -lx LC_ALL.

Most likely the better solution - it also seems that it won't add the export bit, so it seems safe. @jakwings?

@ghost

ghost commented Dec 14, 2015

Copy link
Copy Markdown
Author

IFS and many other variables are affected too! Let's wait until that bug is fixed.

@krader1961

Copy link
Copy Markdown
Contributor

IFS and many other variables are affected too!

In theory, yes. In practice, no, because the other vars you're touching aren't exported except by people who don't know what they're doing.

Let's wait until that bug is fixed.

I don't see why this shouldn't be merged once my recommendation is added to the PR. Should LANG continue to be exported even though you did not include the -x option? Should your making a local change without explicitly saying the new value should be exported result in the var not being exported to any external command? If the answer is yes then external commands won't get the LANG setting in effect for the shell. That seems like a bug to me. Alternatively, we can define the semantics to be that the pre-existing value is still exported to external commands and the set -l only affects the shell code executed within the scope of that function. I'll add this discussion to issue #2611 but don't see why the answers to these questions need to delay merging this fix.

@ghost

ghost commented Dec 15, 2015

Copy link
Copy Markdown
Author

Hmm..Only the builtin read needs LC_ALL, but it does no harm if LC_ALL is exported.

Changed to -lx now.

@ghost

ghost commented Dec 15, 2015

Copy link
Copy Markdown
Author

Wait, I met this warning after this -lx change:

fish: Wide character 776 has no narrow representation

Diaeresis (0x308, ¨)

@ghost

ghost commented Dec 15, 2015

Copy link
Copy Markdown
Author

No, I just checked every $char with od -A x -t x1z -v (output to /dev/stderr), there is no 776 (0x308) there.

The single quote to used to turn $char into the scalar value. Normally printf only accepts a number for %x.

@krader1961

Copy link
Copy Markdown
Contributor

No, I just checked every $char with od -A x -t x1z -v (output to /dev/stderr), there is no 776 (0x308) there.

There wouldn't be since the od command explicitly uses the C locale in order to operate on individual bytes. So it can't recognize values above 255 decimal by design. Somewhere in your data there is a Unicode code point with value 776. The question is which fish command is being fed a non-ASCII value with LC_ALL=C.

@ghost

ghost commented Dec 15, 2015

Copy link
Copy Markdown
Author

od can show multiple bytes, I see only one byte, so there is no 776.

Some tests:

  • change printf ... into just echo: still warns
  • change sed ... into just cat: still warns
  • change (printf ... | sed ...) into (echo | cat): still warns
  • change (printf ... | sed ...) into (echo): no warning
  • change (printf ... | sed ...) into (echo | sed ''): warns
  • remove (printf ... | sed ...): no warning

I'm confused...

@krader1961

Copy link
Copy Markdown
Contributor

Yes, you are confused :-) The od command shows "multiple bytes" but does not recognize values greater than a single eight-bit byte (decimal 255). That means it cannot, by definition, show a value with a decimal value of 776. You seem to be confusing bytes with characters (chars). The od command does not use or recognize any character encoding. The od command by design ignores the LANG/LC_ALL setting.

P.S. I'm obviously ignoring atypical systems like very old Honeywell computers which had a 9-bit byte. Or CDC Cyber super computers with a 60-bit word length. Such systems are not relevant to this issue.

@ghost

ghost commented Dec 15, 2015

Copy link
Copy Markdown
Author

The simple tests above are not related to od or $char, here is a simple test:

function __fish_urlencode --description "URL-encode stdin"
  # Set locale to C and IFS to "" in order to split a line into bytes.
  set -lx LC_ALL C
  # `set -lx IFS ""` causes the same warning
  set -l IFS ''
  set -l output
  echo | cat
  # will discard empty lines and end-of-line
  #while read --array --local chars
  #  for char in $chars
  #    set output $output (printf '%%%02x' "'$char" | sed -e 's/%2[fF]/\//g')
  #  end
  #end
  echo $output
end

Not sure if we are talking about the same version of od:

$ od --version
od (GNU coreutils) 8.24
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

$ echo -n 'Äpfel' | od -A x -t x1z -v
000000 c3 84 70 66 65 6c                                >�.pfel<
000006

If there is 776, I think there could be two bytes:

$ printf '\u0308' | od -A x -t x1z -v
000000 cc 88                                            >�.<
000002

@ghost

ghost commented Dec 15, 2015

Copy link
Copy Markdown
Author

So now there are at least two problems about the exported variables.

Also, the `sed` command should be moved to the last echo for optimization:
function __fish_urlencode --description "URL-encode stdin"
    # Set locale to C and IFS to "" in order to split a line into bytes.
    set -l LC_ALL C
    set -l IFS ''
    set -l output
    # will discard empty lines and end-of-line
    while read --array --local chars
        for char in $chars
            set output $output (printf '%%%02x' "'$char")
        end
    end
    echo -s $output | sed -e 's/%2[fF]/\//g'
end

Well, I've done it in another way.

I will commit later, maybe until the bugs are fixed.

@ghost

ghost commented Dec 16, 2015

Copy link
Copy Markdown
Author

Updated (rebased, so unfortunately two code comments from @krader1961 are flushed away).

As the original script does, the printf format %02x is reused for all elements in the cartesian product "'"$chars. In the original script, there is one more ' after $lines, but that is redundant.

@ghost

ghost commented Dec 30, 2015

Copy link
Copy Markdown
Author

ohmyzsh/ohmyzsh#3582 uses iconv to transform non-utf-8 strings, don't know if it is worth it.

@krader1961

Copy link
Copy Markdown
Contributor

@jakwings: Do you still care about getting this change merged?

@ghost

ghost commented Feb 7, 2016

Copy link
Copy Markdown
Author

@krader1961 What about issue #2611?

@krader1961

Copy link
Copy Markdown
Contributor

Issue #2611 is really orthogonal to your change since you should be explicitly exporting the var rather than relying on the nested context inheriting the export bit.

@ghost

ghost commented Feb 7, 2016

Copy link
Copy Markdown
Author

No, I'm not relying on the export bit (especially IFS). As I pointed out in a comment above, either set -lx LC_ALL or set -lx IFS can cause a mysterious warning:

fish: Wide character 776 has no narrow representation

If it was just that easy by exporting variables, we could have solved this problem ~2 months ago.

@ghost

ghost commented Feb 7, 2016

Copy link
Copy Markdown
Author

Notes (because @krader1961's comments in the code review were flushed away after a git rebase):

Environment variables LC_ALL and IFS are intended to be used only by the builtin function read, and set var value is the only way to set env for read. (env VAR=VAL read will run /usr/bin/read, so …)

@krader1961

Copy link
Copy Markdown
Contributor

Nowhere did I suggest exporting IFS; only LC_ALL to work around issue #2611. IFS, despite the all-caps name, should not be exported as it is private to the current shell session.

The "no narrow representation" warning message only occurs when an environment var (such as $PWD) has a character whose codepoint is greater than 255 (i.e., a non ISO-8859 char) and you spawn an external command.

In other words, you can't start fish in a UTF-8 locale, create an env var with a non-ISO-8859 char, then switch to a ISO-8859/ASCII/C locale. Which is basically what your fix is doing. The problem is that exporting LC_ALL=C once PWD contains /tmp/Äpfel causes the printf subcommand pipeline in

set output $output (printf '%%%02x' "'"$chars | sed -e 's/%2[     fF]/\//g')

to spawn a fish shell with LC_ALL=C. Since the $PWD environment contains unicode "wide" chars the shell complains when trying to serialize the "wide" character (i.e., the unicode combining diaeresis 776 or 0x308) to a single byte for export as required by LC_ALL=C.

You can't change the encoding to C (or other ISO-8859 encoding) once a non-ISO-8859 character is captured in an environment var because the char has already been encoded as a "wide" character. This fix is fundamentally flawed irrespective of issue #2611. Whether or not this can be fixed in the __fish_urlencode function without deeper changes to the fish implementation is TBD.

@krader1961

Copy link
Copy Markdown
Contributor

Also note that the function we're discussing is used in exactly one place in the fish source: setting the title of the Apple Terminal session. Which is not to imply fixing this is unimportant. However, fixing this doesn't necessarily have to be done using the bare minimum of non-fish commands. In other words, using something like a python script to url-encode the unicode string might be acceptable.

* When using a UTF-8 locale, set locale to C temporarily in order to
  read one byte at a time.
* Use the builtin printf in a forward-compatible way. (GNU)
* Improve the readability of the code.
@ghost

ghost commented Feb 9, 2016

Copy link
Copy Markdown
Author

You're right, LC_ALL can pollute other processes in that damn posix way.

After grepping LC_ and IFS in the repo, I see that LC_* hardly appear, so I should use a more conservative method (wrapping read in begin; end). I have pushed a new commit. Should I add a notice for -lx?

@krader1961

Copy link
Copy Markdown
Contributor

Should I add a notice for -lx?

Not sure what you're asking. The -x shouldn't be necessary and doesn't do anything in this situation other than workaround a bug. Including it is "more correct" in so far as you would normally export it so that subshells from (...) command substitutions also get the modified value.

Also, nice trick leveraging a begin...end block to minimize the scope of the LC_ALL change. I was thinking about adding a --raw or --bytes option to read to force it to treat each byte independent of the others thus inhibiting utf-8 to unicode transformations.

@ghost

ghost commented Feb 10, 2016

Copy link
Copy Markdown
Author

Yep, -x is just a workaround here.

@krader1961

Copy link
Copy Markdown
Contributor

@jakwings do you, or anyone else, have an objection to merging this? Looks good to me.

@ghost

ghost commented Feb 17, 2016

Copy link
Copy Markdown
Author

@krader1961 No. This is by far the simplest resolution. If code comment is needed, please add it anyway.

@krader1961

Copy link
Copy Markdown
Contributor

Thanks. Merged as squashed commit 1c8c297.

@ghost

ghost commented Feb 17, 2016

Copy link
Copy Markdown
Author

@krader1961 Are you sure you are not merging the latest patch? That looks like my very first submit.

@lilyball

Copy link
Copy Markdown
Contributor

I had not seen this before, but this function as written is really strange. It's hex-encoding everything, and then de-encoding %2f by using an invocation of sed. Hex-encoding everything is weird enough, but not awful, but there's really no call for the sed invocation here when you could just use string replace.

Personally, I'm also in favor of only hex-encoding the bytes that need to be hex-encoded, but that does mean building up the string character-by-character instead of using one invocation of printf.

From my own local fish config, here's the function I'm using to urlencode. It doesn't touch LC_ALL or LC_CTYPE, so it probably fails on non-ASCII input, but it does urlencode the string without invoking any external programs. Though I haven't actually benchmarked it yet. (I also err on the side of using printf '%s' instead of echo because echo $foo can misbehave if $foo begins with what looks like a flag, though that is rather unlikely to happen with $PWD).

# Percent-encode the path
set -l url_path ''
set -l IFS ''
printf '%s' $PWD | read -alz chars
for c in $chars
    if string match -q -r '[/._~A-Za-z0-9-]' $c
        set url_path $url_path$c
    else
        set url_path (printf '%s%%%02X' $url_path "'$c")
    end
end

@krader1961

Copy link
Copy Markdown
Contributor

@jakwings: Yeah, I screwed up the merge. I think I've fixed it. Please check.

@zanchey

zanchey commented Feb 26, 2016

Copy link
Copy Markdown
Member

@kballard, your code works fine on a directory called snowman☃, so I'm going to replace the current implementation with yours. No it doesn't - sorry for the noise.

@floam

floam commented Feb 26, 2016

Copy link
Copy Markdown
Member

I use a kballard-inspired function locally, so as not to percent-encode the ASCII, works here:

function __fish_urlencode --description "URL-encode stdin"
    set -l chars
    # Set locale to C and IFS to "" in order to split a line into bytes.
    while begin; set -lx LC_ALL C; set -lx IFS ''; read --array chars; end
        if count $chars > /dev/null
            for c in $chars
                if string match -q -r '[/._~A-Za-z0-9-]' $c
                    printf $c
                else
                    printf '%%%02X' "'$c"
                end
            end
        end
    end
end

above:
screenshot 2016-02-26 at 10 59 46 am
HEAD:
screenshot 2016-02-26 at 11 01 00 am

@lilyball

Copy link
Copy Markdown
Contributor

I just pushed a modified version of this as d8a4974. It's similar to @floam's version but it handles newlines and NULs properly.

@zanchey zanchey added this to the next-2.x milestone Feb 28, 2016
@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Apr 17, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants