237 points · by signa11 · 2y ago · 233 comments
Oh my god. This makes me so happy. This is the most lovely think I've read in the world of computing since the unix gods decided that newlines were to be a single character.
The philosophy underlying the sentence "Wouldn’t it be nice if the naive scripts were just correct now?" is incredibly positive. We are surrounded by arrogant jerks who break old code by aggressively enforcing stricter compliance of some stupid rules. But here come these posix heros who do the exact opposite: make old code correct! There is hope in mankind after all.
I guess it's still advisable to rename those files, I don't know how things like cp, mv or rsync will behave when copying such files in the future.
> the following utilities are now either encouraged to error out if they are to create a filename that contains a newline, and/or encouraged to error out if they are *about to print a pathname that contains a newline* in a context where newlines may be used as a separator
It then proceeds to list a bunch of utilities including diff, file, find, grep, head, du, etc., none of which create files directly.
These utilities could be updated to reject newlines in file paths if they're going to print in a "newline delimited" form - but for some of these utilities, that's the only available form.
"On the number of
associative foobars
of degree blah -
Johnson and Anderson.pdf"
all the time. It is very convenient for non-technical academics to have a descriptive file name, and to be able to see it entirely in the navigator they use newlines.
(And if they're that incompetent, why does the article imply they are worth quoting and listening to?)
For example, it contains a directory where all file and subdirectory names are in unary, consisting only of repetitions of the newline character. A correct script should be able to enumerate, access and modify files in there without issue.
to surprise the next person or script to do "rm -rf $TMPDIR/foo"...
First: text is not well defined. Is it ASCII? Is it UTF-8? Some programs can spew UTF-32 with proper locale configured, it's a mess.
Second: encoding and decoding of objects to text is not defined at all. Those problems with filenames is just one example. Using newline as a separator is a natural thing that is easy to implement, yet it is wrong.
In my opinion two things should be done:
1. Standardise on UTF-8. No other encodings allowed.
2. Standardise on JSON. It is good enough to serve as universal exchange format, tools like `jq` exist for some time now.
So any utility must read and write JSON objects with some standard env set. And shells can be developed with better syntax to deal with JSON. This way you can write something like
`ps aux | while read row; do echo ${row.user} ${row.pid}; done`
Please don't use that underdefined joke of a spec. Define "PosixJson" and use that instead. Right now it's not even clear what the result of parsing {"a": 1234678901234567890} is. Is this a parse error? A bigint? A float/double? Quiet wraparound? Something else? I've seen all these behaviors in real world JSON implementations across different languages.
See https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1...
> 3.387 Text File
> A file that contains characters organized into zero or more lines. The lines do not contain NUL characters and none can exceed {LINE_MAX} bytes in length, including the <newline> character.
So, if you have some non-printable characters like BEL/␇/ASCII 0x07, that's still a text file.
(and I believe what bytes count as a valid character depend on your `LC_CTYPE`).
But the moment you have a line longer than {LINE_MAX} bytes (which can depend on which POSIX environment you have), suddenly your text file is now a binary file.
You never have to worry about whether you're dealing with ASCII vs. UTF-8, but rather if you're dealing with UTF-8 vs. ISO-8859-1, or worse, Shift JIS or similar.
Command line scripting is supposed to be adhoc and hack.
But then, how well would it work for ad-hoc usage, which is probably one of the biggest uses of shells?
If you can't get the immensity of the cleverness of Unix foundations, you should not talk about them.
That idea is what made it possible for you to type that sentence in the first place.
I haven't seen any other tool with so much general utility and availability.
> to loop over a string array and print its contents
Is incredibly easy in bash and bash like shells. As highlighted the issue is that tools like 'ls' don't create "a string array." They create one giant string that has to be parsed. The rules in the shell are different than in other languages but it /will/ do most of the parsing for you, or all of it, if you do it carefully.
This is a fine tradeoff. As evidenced by it's wide usage and lack of convincing replacements.
> availability
That's the real reason why we use Unix shell. It's not good, but it's available. Like a cheap hooker.
> but it /will/ do most of the parsing for you, or all of it, if you do it carefully.
"It mostly works if you're careful" doesn't sound very convincing to me.
I tried both python and lua interactively, but they are a pain when it comes to handling files. You have to type much more to get the same things done.
Compatible with most bash scripts
Compared to what?
$ ll /bin/dash
-rwxr-xr-x. 1 root root 113536 Nov 5 2018 /bin/dash
I happen to have an old powershell installed: $ rpm -qi powershell | grep Size
Size : 126588370
A strict POSIX shell is always going to be vastly smaller, for many reasons.I would prefer that the POSIX shell was an LR-parsed language, but you can't have everything.
Dear anal_reactor, what is a "string array"? I have used unix shells since nearly 30 years and never heard about them. And I consider myself a script-fu master!
There are two array-like constructions in the shell: list of words (separated by spaces) and list of lines (separated by newlines). Both cases are implemented as a single string, and the shell makes it trivial to iterate through its components.
All they did is introduce new error cases in C programs while not actually fixing anything for shell scripts.
If anything, it's going to result in more exploits as people write shell scripts with the assumption that newlines cannot appear in filenames.
If you’re not familiar with humans, there are several manuals available online.
Caveats for cursed hardware standards demanding two-byte encodings like USB.
you're probably guilty of the sin you preach and is showing wrongly decoded utf8 and don't even know.
- find(1p) now supports -print0
- xargs(1p) now supports the -0 argument
- newlines in filenames now should throw errors in many utilities
- a complier implementing the c17 standard is now required
- ulimit is expanded
- renice can use relative values
- a timeout utility has been added
- make adds support for $^ $+ ::= :::= != ?= +=
- logger is improved
- gettext is adopted
- readlink and realpath are adopted
- rm now supports -d to remove empty directories and -v for verbose
- various improvements to printf, sed, testThe find utility has print0, and xargs has -0. Notibly, xargs also has -P for running processes in parallel.
rm has both -d and -v.
The renice command appears to be able to use relative adjustments with -n.
There is a timeout command.
There is a readlink command, but no realpath (but a manual page exists for it as a system call).
All active Unix-like operating systems aim to implement the new interfaces as they're defined.
-e Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR above), exits with a non-zero status
-u Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansionI totally agree. Although I'd say that there isn't anything "remarkably simple" about writing a bash script. Anything in the shell scripting world that seems remarkably simple is just because one hasn't realised the ghosts and horrors that lurk in the shadows.
But I'll use -e anytime. It feels like having a protective proton pack at least.
It's at: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V...
(no permalink, search for "pipefail")
export VAR=$(cmd1 | cmd2)
does not count as a pipefail when cmd1 or cmd2 fail but VAR=$(cmd1 | cmd2)
does, so the "correct" way to set an environment variable from a pipeline's output is actually VAR=$(cmd1 | cmd2)
export VARAnd that is fine; but sometimes you want to treat a pipeline as a "single command" and then you can use pipefail to abort the pipeline on error. Then you can handle the error at the granularity of the entire pipeline without caring which part failed.
Lastly, I am confused as to the "silent" failures; maybe you are thinking of combining this with `set -e`? Then yes, that is bad and I recommend against the combination; but then again, I and most advanced scripters recommend against shotgunning `set -e` in the first place. Use it in specific portions of the script when appropriate, and use proper error handling otherwise.
https://www.austingroupbugs.net/view.php?id=251
At some point they decided to narrow the change to just ban the newline character.
Which I personally think is a pity. Allowing escape in file names is a security risk because it enables you to embed ECMA-48 escape sequences in file names. Secure terminal emulators shouldn’t be made vulnerable by arbitrary escape sequences, but there are “too smart for their own good” terminal emulators out there that have escape sequences that let you do crazy things like run arbitrary executables.
I think the decision forbidding newline in pathname is also wrong. It may break tons of existing code.
Like what? I am genuinely curious: Shift-JIS, GB2312, Big5, and all of the EUC variants do not use bytes that correspond to C0 characters in ASCII.
The only reasonable fix is to enhance bash and shell IDEs to track for each variable whether it could possibly include all filename-valid characters (e.g. if it comes from read with no options then it can't contain \n) and warn (off by default unless stderr is a terminal) if they can't and it's used as a filename (conservatively determined when used as arguments to processes), and also warn when using find without -print0, etc. noninteractively and perhaps interactively as well.
Enforcing that a newline isn't part of a path, ensures the security of those systems that are commonly relied on.
Well, only badly written programs. nushell handles this fine, as will any program that doesn't try to do everything as plain strings:
~> touch "foo\nbar"
~> ls foo* | print
╭───┬──────┬──────┬──────┬──────────╮
│ # │ name │ type │ size │ modified │
├───┼──────┼──────┼──────┼──────────┤
│ 0 │ foo │ file │ 0 B │ now │
│ │ bar │ │ │ │
╰───┴──────┴──────┴──────┴──────────╯
However after reading it they're only making them illegal for the posix utilities from the 70s that aren't written properly, so I think that makes sense.Finally. Now let's do the rest: https://dwheeler.com/essays/fixing-unix-linux-filenames.html
Filenames should be boring printable normalized UTF-8. I have never, not once, seen a good reason that a filename should be able to contain random binary gobbledygook
Ensuring normalization is hard. Where should you do it? There's only one good place: in the filesystem. But if you normalize on create then you'd better use the same form that everyone else uses, but, what's that? Input methods generally produce NFC, but there's no guarantee that they will not produce something else. HFS+ normalizes to NFD on create.
ZFS uses form-insensitivity -- much like case-insensitivity, but for form. The reason ZFS went this was exactly that HFS+ and input methods differ as to forms. I pushed hard for this way back when. IMO form-insensitivity is the best way forward.
But as for guaranteeing that filenames are UTF-8... that's much harder. The best thing to do is to not allow the use of non-UTF-8, non-ASCII, non-C locales -- not a guarantee, but pretty good.
SRC != ls *.c
is fine in a makefile as far as POSIX is concerned, because:> Applications shall select target names from the set of characters consisting solely of slashes, hyphens, periods, underscores, digits, and alphabetics from the portable character set
… makes PowerShell start to look damn good.
The way I feel posix, and other descriptive standards work best is when they describe what every one is already doing. This is opposed to prescriptive standards which try focus on how the "correct" way to do somthing, prescriptive standards tend to be over engineered and may or may not actually work.
see also: descriptive and prescriptive dictionaries. http://www.englishplus.com/news/news1100.htm
For shell scripts part of a large system, that's probably fine. For small scripts, that's not very practical. You are not only adding a compilation step, you're also requiring distribution of multiple files. That's a pain.
It just kind of kills the convenience of a simple shell script. I would probably end up writing a makefile to manage all of this and at that point I am only a hop skip and jump away from using a compiled language instead of shell.
But restricting this at syscall level is definite insanity, among with excuses.
Is this really good?
If you can't rely on anything concrete being guaranteed, and it is open to interpretation what "modern" or "major toolchains" are, why have a standard?
(Listed in the Sortix article linked in OP.)
[1]: There's some explanation in this recent post: https://dotat.at/@/2024-10-22-tmp.html
Pathnames can neither contain NUL nor '/'.
Re: `find -print0` / `xargs -0`:
> Previous POSIX releases have considered -print0 before, but never ended up adopting it because using a null terminator meant that any utility that would need to process that output would need to have a new option to parse that type of output.
What nonsense. Just add the `-0` or similar options as needed.
> More precisely, this approach does not resolve our original problem. xargs(1p) can’t sort, and therefore we still have to handle that logic separately, unless sort(1p) also grows this support, even after read(1p). This problem continues with every other type of use-case. Importantly, it breaks the interoperability that POSIX was made to uphold.
More nonsense.
> A bunch of C functions3 are now encouraged to report EILSEQ if the last component of a pathname to a file they are to create contains a newline (put differently, they’re to error out instead of creating a filename that contains a newline).
Ok, that's tolerable. Ditto utilities (notice here they were able to make a list of utilities).
-z, --zero-terminated: end lines with 0 byte, not newline
I wish it would have been c99. What does c17 add exactly, more C++-esque complexity or not? Why was it not c99 (or perhaps even c11) over c17? Genuine questions.
Multithreading support and such (atomics, thread-local storage and a guarantee that `errno` is in TLS), explicitly aligned types and allocations, dedicated types for strings known to be Unicode, _Noreturn, _Generic, _Static_assert, anonymous structs and unions in the nested position, quick_exit, timespec, exclusive mode ("x") in f[re]open, CMPLX macros.
I'm not even sure which one can be C++-ish bullshit possibly except for about two points:
- Multithreading does seem farfetched for causal users. In fact, I do think it could have been minimized without any actual harm, but multithreading itself needed to be specified because it greatly affects a memory model. (Before C11, C had no thread-aware memory model and different threading implementations were subtly different beyond what the standard stated.) Even JavaScript, originally without no notion of threads, eventually got a thread-aware memory model due to shared web workers. But that never meant JS itself need multithreading support in its standard library, and C could have done the same.
- `_Generic` is even more debatable, though I believe it was the only way forward when we accept <tgmath.h>, which is known to be a response to Fortran (other responses include `restrict`) and was impossible to implement in the portable manner before C11. As long as it retains its scary underline and title case, I guess it's fine.
> "guarantee that `errno` is in TLS"
I suppose that does not mean that I can just avoid setting errno to 0 before calling a function after which I check for errno, right?
Yeah, I do have an issue with stuff like "_Generic" but I assume I can just simply not use it.
What is "quick_exit" exactly and what does it solve?
As for multithreading, I stick to phtread. Is any of the new features a replacement for that or what?
At any rate, why C17 over C11 then?
You have the correct insight about errnos. The new guarantee only means that other threads are not possible to mess with your errnos, but cleaning errnos will be still useful within an individual thread.
exit is not guaranteed to work correctly when called simultaneously from multipe threads, while quick_exit will be okay even in that situation. I think this behavior was not even specified before C11, and only specified after observing existing implementations.
It is expected that libc threading routines are thin wrappers around pthread in Linux. That's why I do think it can be minimized; the only actual problem before C11 was the lack of thread-aware memory model. No need to actually be able to create threads from libc to be honest, especially given that each platform now almost always has a single dominant threading implementation like pthread.
[1] https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm
I mean, that is already true.
7.5 ¶2: [...] and `errno` which expands to a modifiable lvalue that has type `int`, the value of which is set to a positive error number by several library functions. It is unspecified whether `errno` is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual object, or a program defines an identifier with the name `errno`, the behavior is undefined.
7.5 ¶3: The value of `errno` is zero at program startup, but is never set to zero by any library function. The value of `errno` may be set to nonzero by a library function call whether or not there is an error, provided the use of `errno` is not documented in the description of the function in this International Standard.
The fact that `errno` can expand to an lvalue does reflect what is required for multithreading implementations among others, but that's about all.