Skip to content

About

Safely execute shell commands and get their output.

Resources

Stars

76 stars

Watchers

89 watching

Forks

Latest commit

 

History

95 Commits

Folders and files

Repository files navigation

SafeShell

SafeShell runs a command and returns its output, like Ruby's backtick operator, but never passes the command to a shell.

With backticks, a file name supplied by a user can run a command of its own:

file = ";blah"
`echo #{file}`  # the shell runs `echo`, then `blah`
# sh reports that it cannot find blah
# => "\n"

SafeShell passes the file name to echo as it is:

SafeShell.execute("echo", file)
# => ";blah\n"

The program can still read an argument that starts with - as an option of its own. Put -- before values a user supplies, where the program supports it, and never let a user choose the program.

Installation

gem install safe_shell

Usage

require "safe_shell"

SafeShell.execute("echo", "Hello, world!")
# => "Hello, world!\n"

The first argument is always the program to run, and it is never passed to a shell, even when it is the only argument. Each remaining argument reaches the program as one literal argument, converted to a String with to_s, so pass the elements of an Array with *. A command string such as "echo #{file}" is therefore looked up as one program named echo ;blah, and fails with Errno::ENOENT. Pass the program and its arguments separately.

Three methods run a command:

# Return the output:
SafeShell.execute("echo", "Hello, world!")

# Return true if the command exits with status zero, false for another
# status, nil if a signal terminated it:
SafeShell.execute?("test", "-f", path)

# Return the output, or raise if the command exits with a non-zero
# status or a signal terminates it:
begin
  SafeShell.execute!("git", "fetch", "origin")
rescue SafeShell::CommandFailedException => e
  warn "#{e.message}: #{e.output}"
end

The exception's message names the command, its arguments and how it ended, as in Shell command ["false"] failed with status 1. The exception also has command, args, status (the Process::Status) and output. Because the message includes every argument, pass secrets to the command through env:, which the message leaves out.

Options

All three methods take the same keyword options:

# Write stdout and stderr to files rather than returning them:
SafeShell.execute("make", stdout: "build.log", stderr: "build.err")

# Add environment variables, or unset one with nil:
SafeShell.execute("printenv", "NAME", env: { "NAME" => "john", "DEBUG" => nil })
  • stdout: and stderr: take the path of a file, as a String or a Pathname. The file is truncated on every call. Both may name the same file, which then holds both streams interleaved.
  • env: takes a Hash of String names to String values. A nil value unsets that variable for the command. A PATH given here decides where the program is found.

To pass options held in a Hash, use **, and only with a Hash your own code built. Whoever controls its values chooses which files are overwritten and which environment the command sees. An option other than stdout:, stderr: and env: raises ArgumentError before any command runs, and so does a Hash given as the command or as an argument, so options passed without ** raise rather than reach the program as an argument.

What a call returns

The command reads an empty stdin. The returned String holds everything the command writes to stdout and stderr, interleaved as it writes them. A stream redirected to a file is left out, so with only stdout: set the String holds the command's stderr, and with both set it is empty. The String holds the bytes exactly as the command wrote them, tagged with Encoding.default_external and never transcoded to Encoding.default_internal.

The call returns once every process holding the command's stdout or stderr has closed them. A background process the command leaves running keeps the call waiting until it exits, unless the command redirects that process's output.

Like the backtick operator, every method sets the variable $? to the command's Process::Status. Where a case under Failures and interruptions says $? does not describe the command, $? may be nil, the status of an earlier command, or the status of another child process, depending on the case and the Ruby implementation.

Failures and interruptions

Ruby collects a finished child process's exit status by waiting for it, also called reaping it.

The command cannot be started. A program that cannot be found or run, or a file named by stdout: or stderr: that cannot be opened, makes all three methods raise a SystemCallError, such as Errno::ENOENT or Errno::EACCES. execute? does not return false, and execute! does not raise CommandFailedException. The files named by stdout: and stderr: are opened, and truncated, before the program starts, so they are truncated even when the program does not exist. $? does not describe the command.

Something else in the process reaps the command first, such as a trap("CHLD") handler that waits for child processes, or trap("CHLD", "IGNORE"), which makes the kernel reap each child as soon as it exits. All three methods may then raise Errno::ECHILD once the command has finished. The command ran, but the output it would have returned and its status are lost. A stream redirected to a file is still written. $? does not describe the command.

The call is interrupted, by a Timeout.timeout around it, Thread#raise, Thread#kill, or a trap handler that raises an exception. SafeShell then cleans up before the exception reaches the caller: it sends the command TERM, gives it a second to exit, sends KILL if it is still running, gives it another second, and reaps it. A second interruption that arrives during the cleanup is held until the cleanup ends. The call normally returns within a second of the interruption, and at most about two seconds after it. A trap handler that raises during the cleanup can add up to a second more, as described below. $? describes the terminated command. Processes the command started are not signalled. The cleanup behaves differently in these cases:

  • A command that has changed its real user ID, as sudo does, cannot be signalled. It is left running, and $? does not describe it.
  • A command still running a second after KILL is left unreaped, and $? does not describe it.
  • A command that something else has already reaped is not signalled, and $? does not describe it.
  • If something else reaped the command and the operating system has since given its process ID to another child of this process, the cleanup signals and reaps that child instead, and $? describes it. The two share a process ID, and the process ID is all SafeShell has to identify the command.
  • On CRuby, an exception raised by a trap handler is not held until the cleanup ends. If it arrives while the cleanup is signalling or waiting for the command, the cleanup sends KILL at once, gives the command a second from then to exit, reaps it, and then raises the exception. If it arrives while SafeShell is closing the command's pipes and files, the cleanup runs as usual and raises it at the end. Either way, the caller receives the trap handler's exception in place of the original interruption. JRuby raises it after the cleanup.

A caller's Thread.handle_interrupt(Object => :never) around the call does not stop a Timeout.timeout, Thread#raise or Thread#kill while SafeShell reads the command's output and waits for it to exit.

Compatibility

GitHub Actions runs the tests on every push, against Ruby 3.0 through 4.0, JRuby and TruffleRuby, on Linux. The gem requires Ruby 3.0 or newer. It is not tested on Windows or macOS.

Test

To run the tests:

bundle install
bundle exec rake

Contributing

Open a pull request with tests for your change.

License

MIT. See LICENSE.

About

Safely execute shell commands and get their output.

Resources

Stars

76 stars

Watchers

89 watching

Forks

Releases

Used by

Contributors

Languages