Commit Graph

1221 Commits

Author SHA1 Message Date
Daniel Kolesa
3ce64010f8 sh(1): fix history file write checking
We cannot just compare histsizeval() against 0, since that returns
a string pointer, which is always non-zero (non-null). The logic
in sethistsize() initializes the history size to 100 with values
that are non-number, and an empty string counts as that. Therefore,
the only time we want to not write into history with HISTSIZE val
set is when it's explicitly 0.

MFC after:	2 weeks
2023-03-20 17:56:56 +01:00
Juraj Lutter
3cf65f8a7f sh(1): Allow non-printing characters in prompt strings
Introduce new prompt format characters:

- '\[' starts the sequence of non-printing chatacters
- '\]' ends the sequence of non-printing characters

Within these sequences, the following characters are now supported:

- '\a' emits ASCII BEL (0x07, 007) character
- '\e' emits ASCII ESC (0x1b, 033) character
- '\r' emits ASCII CR (0x0d, 015) character
- '\n' emits ASCII CRLF sequence

These can be used to embed ANSI sequences into prompt strings.

Example in .shrc:

PS1="\[\e[7m\]\u@\h\[\e[0m\]:\w \\$ "

This tries to maintain some degree of compatibility with GNU bash,
that uses GNU readline library (which behaves slightly different from
BSD editline): It has two "non-printing boundary" characters:

- RL_PROMPT_START_IGNORE (\001)
- RL_PROMPT_END_IGNORE (\002)

while BSD editline only has one (when using EL_PROMPT_ESC setting), so
for this purpose, ASCII \001 was chosen and both \[ and \] emits
this character.

And while here, enlarge PROMPTLEN from 128 to 192 characters.

Reviewed by:		jilles
Approved by:		jilles
Differential Revision:	https://reviews.freebsd.org/D37701
2022-12-22 19:10:48 +01:00
Ed Maste
1dbb9994d4 sh: install hard link with same mode as target
Previously when using NO_ROOT we recorded a METALOG entry for the
/.profile hard link with a different mode than the link target, which is
not permitted.

Reviewed by:	bapt
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D37476
2022-11-23 15:10:02 -05:00
Dag-Erling Smørgrav
8d7221ca2d sh: when loading profile, read only .sh files.
Reviewers: jilles, eugen_grosbein.net, cy

Subscribers: imp

Differential Revision: https://reviews.freebsd.org/D37034
2022-10-22 19:05:31 +02:00
Dag-Erling Smørgrav
d3890a547d sh: when loading profile, skip obvious scratch files.
Differential Revision: https://reviews.freebsd.org/D36856
2022-10-03 14:35:51 +00:00
Dag-Erling Smørgrav
497cdf9673 sh: read more profile files.
Differential Revision: https://reviews.freebsd.org/D36505
MFC after:	1 month
2022-10-01 21:30:56 +00:00
John Baldwin
10297a9ed4 sh: Fix mismatch in array bounds for vforkexecshell().
Reviewed by:	imp, jilles, emaste
Reported by:	GCC -Warray-parameter
Differential Revision:	https://reviews.freebsd.org/D36760
2022-09-28 14:05:07 -07:00
Piotr Pawel Stefaniak
a142345641 sh: nullify ENV in tests
This is to avoid loading .shrc which may contain commands that would
result in output different than expected.

Reviewed by:	jilles
Differential Revision:	https://reviews.freebsd.org/D35876
2022-08-20 13:27:42 +02:00
Piotr Pawel Stefaniak
755a1be6d0 sh: accept fc options grouped behind one '-'
As per Utility Syntax Guidelines, accept both forms: -l -n and -ln.

To do that, anticipate the source string for the next option that will
be parsed by nextopt(). It's not always *argptr, sometimes it is
nextopt_optptr.

To simplify the check for not_fcnumber, slightly modify nextopt() to
always nullify nextopt_optptr in cases where it would have been set
to point to a NUL character.

Reviewed by:	jilles
Differential Revision:	https://reviews.freebsd.org/D35836
2022-08-20 13:26:05 +02:00
Jens Schweikhardt
825225e52f For man page references found in ports, indicate the respective port. 2022-08-14 15:02:06 +02:00
Gordon Bergling
b131efe3e5 sh.1: Fix a mandoc warning
- new sentence, new line

MFC after:	3 days
2022-07-31 16:23:27 +02:00
Piotr Pawel Stefaniak
68700941c7 sh: fix autocompletion for commands that share name with a directory
Provide libedit a special function making it always add a space after
the autocompleted command. The default one adds a slash if the word is
also a name of a directory in the current working directory, but this is
wrong for commands.

Reviewed by:	bapt, jilles
Differential Revision: https://reviews.freebsd.org/D34544
2022-03-28 08:45:03 +02:00
Jilles Tjoelker
5a1a07f2a0 sh: Don't add something to a null pointer
Pointer arithmetic on a null pointer is undefined behavior.

The bug can be reproduced by running bin/sh/tests/builtins/wait6.0 with
UBSAN.

Reported by:	Mark Millard
Reviewed by:	imp
Differential Revision:	https://reviews.freebsd.org/D34011
2022-01-26 23:13:20 +01:00
Bryan Drewery
971677d5fd sh: Avoid some headers when NO_HISTORY is set.
This is more simpler compatibility with using this source on older
systems before libedit was made to install filecomplete.h in
commit b315a7296d.
2021-11-24 17:53:39 -08:00
Jilles Tjoelker
72f750dc7c sh: Fix heredoc at certain places in case and for
After an unescaped newline, there may be a here-document. Some places in
case and for did not check for one.

Reviewed by:	bdrewery
Differential Revision:	https://reviews.freebsd.org/D32628
2021-10-27 21:05:19 +02:00
Ka Ho Ng
fcfa64801a sh: Set PATH envvar after setting HOME in dotfile
In single-user mode, all env vars are absent, so exptilde() would not be
able to expand ~ correctly.
Place the lines setting PATH below HOME, so exptilde() would work as
expected.

Sponsored by:	The FreeBSD Foundation
MFC after:	3 days
Reviewed by:	jilles, emaste
Differential Revision:	https://reviews.freebsd.org/D27003
2021-10-26 22:50:09 +08:00
Baptiste Daroussin
f3aad18d5e sh(1): fix home/del key on mobaxterm env
For $reason mobaxterm default on sending unusual sequence from home/del
key, which makes libedit unabel to catch them and bind them correctly.

mobaxterm seems popular on the windows environment, so add proper
keybinding to default shrc configuration so it works out of box.

Reported by:	lme
2021-10-20 14:00:20 +02:00
Baptiste Daroussin
ef0d94a3d3 sh(1): interactive mode improvement
In the default configuration add 2 bindings which has been requested by
many during the HEADSUP discussion:
* csh like arrow history navigation
* ctrl-arrow to jump from word to words

Add an alias to make the history command exist as an alias to fc -l.
2021-10-20 09:33:04 +02:00
Elyes HAOUAS
48556dff3d src/bin/sh: Fix spelling errors
Pull Request: https://github.com/freebsd/freebsd-src/pull/544
Signed-off-by: Elyes HAOUAS <ehaouas@noos.fr>
2021-10-02 10:39:24 -06:00
Bryan Drewery
e31fb97148 read builtin: Empty variables on timeout
This matches how a non-timeout error is handled.

Reviewed by:	jilles
MFC after:	2 weeks
Differential Revision: https://reviews.freebsd.org/D31876
2021-09-24 11:34:54 -07:00
Stephane Rochoy
d2c233176f sh: Add -o verify to use O_VERIFY when sourcing scripts
Add -o verify to sh to make it use O_VERIFY when
sourcing scripts and reading profiles.

Useful in conjunction with mac_veriexec to help protect at
least some parts of the boot sequence, e.g., /etc/rc*.

Differential revision:	https://reviews.freebsd.org/D30464
Reviewed by:		jilles, sjg
Obtained from:		Stormshield
2021-09-23 10:43:09 +02:00
Piotr Pawel Stefaniak
1f82fb3834 sh: try to avoid overwriting HISTFILE produced by other shells
If an attempt to load history from an existing history file was
unsuccessful, do not try to save command history to that file on exit.
2021-09-22 22:23:32 +02:00
Piotr Pawel Stefaniak
c866d0c798 sh: improve command completion
When there are many matches, find the longest common substring starting
from the beginning of each command and use that to replace input.

As an example: on my system, llv<tab> will be autocompleted to llvm-
and another <tab> will print all matching llvm commands.
2021-09-22 22:23:32 +02:00
Piotr Pawel Stefaniak
9413dfd331 sh: reset sh bindings on bind -e, bind -v
Until this change, any bindings set in histedit() were lost on calls to
bindcmd().

Only bind -e and bind -v call libedit's keymacro_reset(). Currently you
cannot fool libedit/map.c:map_bind() by trying something like bind -le
as when p[0] == '-', it does a switch statement on p[1].
2021-09-22 10:54:51 +02:00
Baptiste Daroussin
908b8e32f9 sh: remove emacs improvements that are now defaults in libedit 2021-09-22 10:27:10 +02:00
Piotr Pawel Stefaniak
b8ff849cbd sh: improve command completion
When multiple matches are found, we keep the provided string on the
input line and print unique matches as suggestions.

But the multiple matches might be the same command found in different
directories, so we should deduplicate the matches first and then decide
whether to autocomplete the command or not, based on the number of
unique matches.
2021-09-19 13:51:45 +02:00
Baptiste Daroussin
3ae61b972b sh: improve emacs mode
in emacs mode ^W should delete the previous word by default
Note that upstreaming this change directly into libedit is in process.

Reported by:	manu
Reviewed by:	jills, pstef, manu
Differential Revision:	https://reviews.freebsd.org/D29493
2021-08-28 16:11:57 +02:00
Piotr Pawel Stefaniak
35b253d9d2 sh: fix NO_HISTORY build
Move code added in b315a7296d ("autocomplete commands") to
conditionally compiled part under #ifndef NO_HISTORY.

Reported by:	bdrewery
Fixes:		b315a7296d
2021-08-19 06:57:06 +02:00
Baptiste Daroussin
988b1bb0c5 sh: implement persistent history storage
Implement persistent history storage:
the strategy is simple at start: loads the existing .sh_history file
at exit dump it.

The implementation respects the HISTFILE variable and its POSIX
definition: ~/.sh_history is used if HISTFILE is not set.

to avoid sh to create the history file, set HISTSIZE to 0 or HISTFILE to
en empty value

Co-authored-by:	pstef
Reviewed by:	jilles
Differential Revision:	https://reviews.freebsd.org/D29493
2021-05-10 18:57:13 +02:00
Piotr Pawel Stefaniak
1a4e959eb3 sh: fix debug build
Approved by:	jilles
2021-04-11 09:23:14 +02:00
Piotr Pawel Stefaniak
5a18515b31 sh: silence sanitizer
Don't add 0 to a null pointer.
Reviewed by:	jilles
2021-04-01 07:31:03 +02:00
Baptiste Daroussin
660045fb53 sh: improve emacs mode
In emacs mode, force ^R to backware search the history
This behaviour is the default in emacs mode for most of the other shells

Note: Note that this can still be overridden via $EDITRC, ~/.editrc or a
bind command after set -o emacs.

MFC after:		1 week
Approved by:		jilles
Reviewed by:		jilles, arichardson, pstef
Differential Revision:	https://reviews.freebsd.org/D29494
2021-03-30 23:49:03 +02:00
Piotr Pawel Stefaniak
b315a7296d sh(1): autocomplete commands
Without this patch, sh can autocomplete file names but not commands from
$PATH. Use libedit's facility to execute custom function for autocomplete,
but yield to the library's standard autocomplete function when cursor is
not at position 0.

Reviewed by:	bapt
Differential Revision:	https://reviews.freebsd.org/D29361
2021-03-29 11:14:27 +02:00
Jilles Tjoelker
52981a1694 sh/tests: Add a second kind of binary scripts without #!
One of the reasons for git commit
e0f5c1387d was to make "actually portable
executables" work. Add a test that is more like those.

MFC after:	1 week
2021-01-03 23:53:37 +01:00
Jilles Tjoelker
ab41d7f371 sh: Explain duplicate tcsetpgrp() calls
This is a comment change only.
2020-12-26 15:27:33 +01:00
Jilles Tjoelker
ccd0a51fda sh: Write absolute path in command -vV and type
POSIX is pretty clear that command -v, command -V and type shall write
absolute pathnames. Therefore, we need to prepend the current directory's
name to relative pathnames.

This can happen either when PATH contains a relative pathname or when the
operand contains a slash but is not an absolute pathname.
2020-09-01 13:19:15 +00:00
Jilles Tjoelker
1cffe8b812 sh: Keep ignored SIGINT/SIGQUIT after set in a background job
If job control is not enabled, a background job (... &) ignores SIGINT and
SIGQUIT, but this can be reverted using the trap builtin in the same shell
environment.

Using the set builtin to change options would also revert SIGINT and SIGQUIT
to their previous dispositions.

This broke due to r317298. Calling setsignal() reverts the effect of
ignoresig().

Reported by:	bdrewery
MFC after:	1 week
2020-08-28 15:35:45 +00:00
Piotr Pawel Stefaniak
9b2a97806f sh(1): print a newline when ^D quits sh
I've always found this a little bit confusing:
> sh
$ ^D> sh
$ ^D>

Reviewed by:	0mp, jilles
MFC after:	1 week
Differential Revision:	https://reviews.freebsd.org/D25813
2020-07-27 18:46:20 +00:00
Jilles Tjoelker
bd11190091 sh: Do not ignore INTOFF during a trap
INTOFF postpones SIGINT processing and INTON enables it again. This is
important so an interactive shell can return to the top level prompt when
Ctrl+C is pressed.

Given that INTON is automatically done when a builtin completes, the part
where onsig() ignores suppressint when in_dotrap is true is both unnecessary
and unsafe. If the trap is for some other signal than SIGINT, arbitrary code
could have been interrupted.

Historically, INTOFF remained in effect for longer.

Reviewed by:	bdrewery
MFC after:	2 weeks
Differential Revision:	https://reviews.freebsd.org/D25270
2020-07-09 20:53:56 +00:00
Mateusz Piotrowski
2c566d312f Fix description of the "\$" sequence for PS1
The manual page documents "\$" to expand to either "$" or "#" followed by
a single space. In reality, the single space character is not appended.

PR:		247791
Submitted by:	kd-dev@pm.me
MFC after:	7 days
2020-07-06 10:05:35 +00:00
Jilles Tjoelker
40276ff30e sh/tests: Re-enable bin.sh.execution.functional_test.bg12.0
This reverts r362646.

PR:		247559
MFC after:	1 week
2020-06-28 21:33:08 +00:00
Jilles Tjoelker
c1602cfd61 sh/tests: Fix flaky execution/bg12.0
When job control is not enabled, the shell ignores SIGINT while waiting for
a foreground process unless that process exits on SIGINT. In this case, the
foreground process is sleep and it does not exit on SIGINT because the
signal is only sent to the shell. Depending on order of events, this could
cause the SIGINT to be unexpectedly ignored.

On lightly loaded bare metal, the chance of this happening tends to be less
than 0.01% but with higher loads and/or virtualization it becomes more
likely.

Starting the sleep in background and using the wait builtin ensures SIGINT
will not be ignored.

PR:		247559
Reported by:	lwhsu
MFC after:	1 week
2020-06-28 21:15:29 +00:00
Li-Wen Hsu
c707e36ef9 Temporarily skip flakey bin.sh.execution.functional_test.bg12 in CI
PR:		238870
Sponsored by:	The FreeBSD Foundation
2020-06-26 09:39:23 +00:00
Jilles Tjoelker
7312c97fa4 sh/tests: Add tests for SIGINT in non-jobc background commands
If job control is not enabled, background commands shall ignore SIGINT and
SIGQUIT, and it shall be possible to override that ignore in the same shell.

MFC after:	1 week
2020-06-14 19:41:24 +00:00
Kyle Evans
dcef4f65ae vfs: add restrictions to read(2) of a directory [1/2]
Historically, we've allowed read() of a directory and some filesystems will
accommodate (e.g. ufs/ffs, msdosfs). From the history department staffed by
Warner: <<EOF

pdp-7 unix seemed to allow reading directories, but they were weird, special
things there so I'm unsure (my pdp-7 assembler sucks).

1st Edition's sources are lost, mostly. The kernel allows it. The
reconstructed sources from 2nd or 3rd edition read it though.

V6 to V7 changed the filesystem format, and should have been a warning, but
reading directories weren't materially changed.

4.1b BSD introduced readdir because of UFS. UFS broke all directory reading
programs in 1983. ls, du, find, etc all had to be rewritten. readdir() and
friends were introduced here.

SysVr3 picked up readdir() in 1987 for the AT&T fork of Unix. SysVr4 updated
all the directory reading programs in 1988 because different filesystem
types were introduced.

In the 90s, these interfaces became completely ubiquitous as PDP-11s running
V7 faded from view and all the folks that initially started on V7 upgraded
to SysV. Linux never supported this (though I've not done the software
archeology to check) because it has always had a pathological diversity of
filesystems.
EOF

Disallowing read(2) on a directory has the side-effect of masking
application bugs from relying on other implementation's behavior
(e.g. Linux) of rejecting these with EISDIR across the board, but allowing
it has been a vector for at least one stack disclosure bug in the past[0].

By POSIX, this is implementation-defined whether read() handles directories
or not. Popular implementations have chosen to reject them, and this seems
sensible: the data you're reading from a directory is not structured in some
unified way across filesystem implementations like with readdir(2), so it is
impossible for applications to portably rely on this.

With this patch, we will reject most read(2) of a dirfd with EISDIR. Users
that know what they're doing can conscientiously set
bsd.security.allow_read_dir=1 to allow read(2) of directories, as it has
proven useful for debugging or recovery. A future commit will further limit
the sysctl to allow only the system root to read(2) directories, to make it
at least relatively safe to leave on for longer periods of time.

While we're adding logic pertaining to directory vnodes to vn_io_fault, an
additional assertion has also been added to ensure that we're not reaching
vn_io_fault with any write request on a directory vnode. Such request would
be a logical error in the kernel, and must be debugged rather than allowing
it to potentially silently error out.

Commented out shell aliases have been placed in root's chsrc/shrc to promote
awareness that grep may become noisy after this change, depending on your
usage.

A tentative MFC plan has been put together to try and make it as trivial as
possible to identify issues and collect reports; note that this will be
strongly re-evaluated. Tentatively, I will MFC this knob with the default as
it is in HEAD to improve our odds of actually getting reports. The future
priv(9) to further restrict the sysctl WILL NOT BE MERGED BACK, so the knob
will be a faithful reversion on stable/12. We will go into the merge
acknowledging that the sysctl default may be flipped back to restore
historical behavior at *any* point if it's warranted.

[0] https://www.freebsd.org/security/advisories/FreeBSD-SA-19:10.ufs.asc

PR:		246412
Reviewed by:	mckusick, kib, emaste, jilles, cy, phk, imp (all previous)
Reviewed by:	rgrimes (latest version)
MFC after:	1 month (note the MFC plan mentioned above)
Relnotes:	absolutely, but will amend previous RELNOTES entry
Differential Revision:	https://reviews.freebsd.org/D24596
2020-06-04 18:09:55 +00:00
Jilles Tjoelker
e0f5c1387d sh: Allow more scripts without #!
Austin Group bugs #1226 and #1250 changed the requirements for shell scripts
without #! (POSIX does not specify #!; this is about the shell execution
when execve(2) returns an [ENOEXEC] error).

POSIX says we shall allow execution if the initial part intended to be
parsed by the shell consists of characters and does not contain the NUL
character.  This allows concatenating a shell script (ending with exec or
exit) and a binary payload.

In order to reject common binary files such as PNG images, check that there
is a lowercase letter or expansion before the last newline before the NUL
character, in addition to the check for the newline character suggested by
POSIX.
2020-05-30 16:00:49 +00:00
Jilles Tjoelker
40b12a0b78 sh: Remove a comment that was obsoleted by r358152
Since r358152, the read builtin has used a buffer.

Also, remove a space at the end of the line in a comment.

No functional change is intended.
2020-05-22 14:46:23 +00:00
Jilles Tjoelker
6bc7175f31 sh: Fix double INTON with vfork
The shell maintains a count of the number of times SIGINT processing has
been disabled via INTOFF, so SIGINT processing resumes when all disables
have enabled again (INTON).

If an error occurs in a vfork() child, the processing of the error enables
SIGINT processing again, and the INTON in vforkexecshell() causes the count
to become negative.

As a result, a later INTOFF may not actually disable SIGINT processing. This
might cause memory corruption if a SIGINT arrives at an inopportune time. As
of r360452, it causes the shell to abort when it would unsafely allocate or
free memory in certain ways.

Note that various places such as errors in non-special builtins
unconditionally reset the count to 0, so the problem might still not always
be visible.

PR:		246497
Reported by:	jbeich
MFC after:	2 weeks
2020-05-16 16:29:23 +00:00
Jilles Tjoelker
1bb4b6a76a sh/tests: Test some obscure cases with aliasing keywords 2020-05-12 21:59:21 +00:00
Jilles Tjoelker
9f9c9549fd sh: Assert INTOFF rather than applying it in ck*
As I noted in https://reviews.freebsd.org/D22756, INTOFF should be in effect
when calling ckmalloc/ckrealloc/ckfree to avoid memory leaks and double
frees. Therefore, change the functions to check if INTOFF is in effect
instead of applying it.

Reviewed by:	bdrewery
Differential Revision:	https://reviews.freebsd.org/D24599
2020-04-28 20:34:27 +00:00