Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ test:
lint:
golint ./...
go vet ./...
errcheck ./...
errcheck -ignoretests ./...

gometalinter:
gometalinter --vendor --cyclo-over=25 --line-length=150 --dupl-threshold=150 --min-occurrences=3 --enable=misspell --deadline=10m --exclude=SA1022
Expand Down
151 changes: 150 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,34 @@ To setup multiple auth users, you can specify the `-basic-auth` option multiple
The credentials for basic authentication may also be provided via the `SH_BASIC_AUTH` environment variable.
You can specify the preferred HTTP-method (via `METHOD:` prefix for path): `shell2http GET:/date date`

Endpoint options
----------------

Some settings are set per endpoint, as a query string in the path argument (it is not a part of the URL path):

[METHOD:]/path[?option=value&option2=value2...]

shell2http "/live?stream=1" "tail -F some.log"
shell2http "GET:/events?sse=1" "tail -F some.log"
shell2http "/ws?websocket=1&allow-origin=same-site" 'while read line; do echo "got: $line"; done'

| Option | Description |
|------------------|-------------|
| `stream=1` | send the command output to the client as it is written, without waiting for the command to finish |
| `sse=1` | the same as `stream`, but each line of the output is sent as a [Server-Sent Event](https://html.spec.whatwg.org/multipage/server-sent-events.html) |
| `websocket=1` | connect the command to the client by [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket): messages from the client are written to STDIN, each line of the output is sent as a message |
| `allow-origin=…` | the web pages allowed to open the WebSocket (only with `websocket=1`): `same-origin` (default), `same-site`, `*` or a comma-separated list of origins |

* the only allowed value is `1` (except `allow-origin`), to disable an option just don't set it
* an unknown option, a value other than `1` (`/path?sse`, `/path?sse=true`), an empty `?`,
more than one of `stream`, `sse` and `websocket`, or a `websocket` path with a method other than `GET` is an error on start
* the options are not a part of the path, so `/live?stream=1` and `/live` are the same path (a duplicate),
the path still can have different commands for different methods (`GET:/live?sse=1` and `POST:/live`)
* without options an endpoint works as usual: the output is sent after the command has finished

Remember to quote the path argument, `?`, `&` and `*` are special characters for the shell.
See [Live output](#live-output-stream-and-sse) and [WebSocket](#websocket) for details.

Install
-------

Expand All @@ -86,7 +114,7 @@ MacOS:

Download binaries from: [releases](https://github.com/msoap/shell2http/releases/latest) (MacOS/Linux/Windows/RaspberryPi)

For Docker users, availeble tags see in [Docker Hub](https://hub.docker.com/r/msoap/shell2http):
For Docker users, available tags see in [Docker Hub](https://hub.docker.com/r/msoap/shell2http):

docker pull msoap/shell2http

Expand Down Expand Up @@ -160,6 +188,46 @@ shell2http -form /slow 'sleep ${v_duration:-1}; echo "sleep ${v_duration:-1} sec
```
</details>

<details><summary>Live output of a log file (stream and SSE)</summary>

```sh
shell2http "/live?stream=1" "tail -F /var/log/system.log" "/events?sse=1" "tail -F /var/log/system.log"
```

Read the stream with curl (`-N` - don't buffer the output):

curl -N http://localhost:8080/live
curl -N http://localhost:8080/events

Or in a browser with [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource):

```js
const events = new EventSource("/events");
events.onmessage = (e) => console.log(e.data);
events.addEventListener("exit", (e) => { console.log("exit code:", e.data); events.close(); });
```
</details>

<details><summary>Interactive command in a browser (WebSocket)</summary>

```sh
shell2http "/ws?websocket=1" 'while read -r line; do echo "$line" | rev; done'
```

Open `http://localhost:8080/` and run in the browser console:

```js
const ws = new WebSocket(`ws://${location.host}/ws`);
ws.onmessage = (e) => console.log(e.data);
ws.onclose = (e) => console.log("exit code:", e.reason);
ws.onopen = () => ws.send("hello"); // prints "olleh"
```

Or from the command line, eg with [websocat](https://github.com/vi/websocat): `websocat ws://localhost:8080/ws`

A page with all live output modes (stream, SSE and WebSocket): [examples/stream](examples/stream)
</details>

<details><summary>Run command in background (don't wait for it to finish)</summary>

Redirect stdout and stderr of the background command, otherwise the request waits for it to finish:
Expand Down Expand Up @@ -338,6 +406,87 @@ shell2http -cgi -form /reflect 'echo "Content-Type: text/plain"; echo; echo "$v_

The first empty line ends the headers block, everything after it is sent as the body as is.

### Live output (stream and SSE)

With the `stream=1` or `sse=1` [endpoint option](#endpoint-options) the output is sent to the client while the command is running:

* the response headers are sent at once, with status `200`
* `stream=1`: the output is sent as is, as `text/plain; charset=utf-8`;
the exit code is sent at the end as the `X-Shell2http-Exit-Code` HTTP trailer
* `sse=1`: the output is sent as `text/event-stream`, each line of stdout is a `data:` event (default type `message`),
a line longer than 64KB is split into several events. With `-include-stderr` the stderr lines are sent as `stderr` events.
When the command has finished, an `exit` event with the exit code is sent:

data: first line

event: stderr
data: some error

event: exit
data: 0

* the command (the shell and all processes it started) is killed when the client disconnects,
on `-timeout` or on shutdown of shell2http (Unix only, on Windows only the shell process is killed)
* a browser `EventSource` reconnects (and runs the command again) when the stream ends,
close it on the `exit` event if the command is not endless

Not all options work for streaming endpoints:

* `-cache` - the output is not cached
* `-500` - not applicable, the status is sent before the command has finished
* `-show-errors` - not applicable, an exec error is not appended to the output (see the exit code instead)
* `-cgi` - CGI variables and the request body on STDIN work as usual, but headers are not parsed from the output
* `-one-thread` - an endless stream holds the lock, so all other requests wait for it

Many programs buffer their output when it is not a terminal, so it comes in big chunks with a delay
(eg: `grep`, `awk`, `sed`, `python`). Use line buffering for them:
`grep --line-buffered`, `sed -u`, `python -u`, `stdbuf -oL some_command`.

A reverse proxy may buffer the response too: shell2http sends the `X-Accel-Buffering: no` header for nginx,
for other proxies disable buffering for streaming paths in their settings.

### WebSocket

With the `websocket=1` [endpoint option](#endpoint-options) the command is started when a client opens a WebSocket
(`new WebSocket("ws://host:8080/path")` in a browser), and works while the connection is open:

* each message from the client (text or binary) is written to STDIN of the command with `\n` appended,
so `read line` in a script gets one message; a message bigger than 64KB closes the connection.
If the command doesn't read STDIN, and more than 64 messages are waiting (in addition to the 64KB pipe buffer),
the command is stopped
* each line of stdout is sent as a message (without `\n`, `\r\n`), a line longer than 64KB is split into several messages,
a line that is not valid UTF-8 is sent as a binary message. With `-include-stderr` the stderr lines are sent too
* when the command has finished, the connection is closed with the code `1000` and the exit code as the reason
(`event.reason` in `onclose`), `-1` for a killed command
* the command (the shell and all processes it started) is killed when the client closes the connection,
on `-timeout` or on shutdown of shell2http, like for [streaming endpoints](#live-output-stream-and-sse)
* the path accepts only WebSocket handshakes (`GET` without a body), a plain request gets `400`
* `-form`, `-cgi` (variables only, there is no request body) and `-basic-auth` work as usual,
the options not working for streaming endpoints don't work here either

A browser connects a WebSocket from any web page, with the cookies and saved basic auth credentials of the site,
so the `Origin` of a page is checked with the `allow-origin` option (a page that is not allowed gets `403`):

* `same-origin` (default) - the host and port of `Origin` are the same as in the `Host` header
(`http://localhost:8080` for `localhost:8080`)
* `same-site` - the same registrable domain, any port and subdomain (`https://app.example.com` for `api.example.com`)
* `*` - any page, use it only for a command that is safe to run by anyone
* `https://a.com,http://localhost:3000` - only these origins (scheme, host and port as the browser sends them)

A request without `Origin` (not from a browser: `websocat`, scripts) is always allowed.
Behind a reverse proxy the `Host` header must be passed to shell2http as is, or use a list of origins.

### Shutdown

On `Ctrl-C` (`SIGINT`) or `SIGTERM` shell2http stops accepting new requests, kills running commands
and waits up to 3 seconds for running requests to finish (a second `Ctrl-C` stops it at once):

* streaming endpoints and commands with `-timeout` run in their own process group,
the shell and all processes it started are killed (on Windows only `Ctrl-C`, and only the shell process is killed)
* other commands are in the process group of shell2http: `Ctrl-C` in a terminal reaches them as usual,
but on `SIGTERM` (eg: `kill <pid>`) they are not killed and shell2http waits for them up to 3 seconds
* background processes of finished commands (`some_command >/dev/null 2>&1 &`) keep running

See also
--------

Expand Down
56 changes: 34 additions & 22 deletions config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"context"
"flag"
"fmt"
"log"
Expand All @@ -11,6 +12,7 @@ import (
"runtime"
"strconv"
"strings"
"sync"
)

type authUsers struct {
Expand Down Expand Up @@ -48,28 +50,38 @@ func (au authUsers) isAllow(user, pass string) bool {

// Config - config struct
type Config struct {
port int // server port
cache int // caching command out (in seconds)
timeout int // timeout for shell command (in seconds)
host string // server host
exportVars string // list of environment vars for export to script
shell string // custom shell
defaultShell string // shell by default
defaultShOpt string // shell option for one-liner (-c or /C)
cert string // SSL certificate
key string // SSL private key path
auth authUsers // basic authentication
exportAllVars bool // export all current environment vars
setCGI bool // set CGI variables
setForm bool // parse form from URL
noIndex bool // don't generate index page
addExit bool // add /exit command
oneThread bool // run each shell commands in one thread
showErrors bool // returns the standard output even if the command exits with a non-zero exit code
includeStderr bool // also returns output written to stderr (default is stdout only)
intServerErr bool // return 500 error if shell status code != 0
formCheckRe *regexp.Regexp // regexp for check form fields
maxUploadSize int64 // max size of request body parsed by -form (in bytes), 0 - no limit
port int // server port
cache int // caching command out (in seconds)
timeout int // timeout for shell command (in seconds)
host string // server host
exportVars string // list of environment vars for export to script
shell string // custom shell
defaultShell string // shell by default
defaultShOpt string // shell option for one-liner (-c or /C)
cert string // SSL certificate
key string // SSL private key path
auth authUsers // basic authentication
exportAllVars bool // export all current environment vars
setCGI bool // set CGI variables
setForm bool // parse form from URL
noIndex bool // don't generate index page
addExit bool // add /exit command
oneThread bool // run each shell commands in one thread
showErrors bool // returns the standard output even if the command exits with a non-zero exit code
includeStderr bool // also returns output written to stderr (default is stdout only)
intServerErr bool // return 500 error if shell status code != 0
formCheckRe *regexp.Regexp // regexp for check form fields
maxUploadSize int64 // max size of request body parsed by -form (in bytes), 0 - no limit
shutdownCtx context.Context // canceled on SIGINT/SIGTERM, nil - never
hijacked *sync.WaitGroup // running handlers of hijacked connections (websocket), server.Shutdown doesn't wait for them, nil - not tracked
}

// commandContext - parent context for commands that must be killed when the server is shutting down
func (cfg Config) commandContext() context.Context {
if cfg.shutdownCtx == nil {
return context.Background()
}
return cfg.shutdownCtx
}

// getConfig - parse arguments
Expand Down
15 changes: 15 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,21 @@ The credentials for basic authentication may also be provided via the SH_BASIC_A
The SH_MAX_UPLOAD_SIZE environment variable limits the size (in bytes) of a request body parsed by -form, by default there is no limit.
You can specify the preferred HTTP-method (via "METHOD:" prefix for path): shell2http GET:/date date

Endpoint options are set as a query string in the path argument: "[METHOD:]/path[?option=1&...]",
the only allowed value is "1" (except allow-origin):

- stream=1 -- send the command output as it is written, without waiting for the command to finish
- sse=1 -- the same, but each line of the output is sent as a Server-Sent Event, and an "exit" event at the end
- websocket=1 -- connect the command by WebSocket: each message from the client is written to stdin with "\n" appended,
each line of the output is sent as a message, the connection is closed with the exit code as the close reason
- allow-origin=... -- the web pages allowed to open the WebSocket (by the Origin header): same-origin (default),
same-site, * (any) or a comma-separated list of origins (https://a.com,http://localhost:3000)

For streaming and WebSocket endpoints the command is killed when the client disconnects or on Ctrl-C/SIGTERM. Example:

shell2http "/live?stream=1" "tail -F some.log" "/events?sse=1" "tail -F some.log"
shell2http "/ws?websocket=1&allow-origin=same-site" 'while read line; do echo "got: $line"; done'

Examples:

shell2http /top "top -l 1 | head -10"
Expand Down
21 changes: 21 additions & 0 deletions examples/stream/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<title>shell2http live output</title>
<p><a href="/stream">/stream</a> <button onclick="sse()">/sse</button>
<form onsubmit="ws.send(msg.value); msg.value = ''; return false">
<input id="msg" placeholder="message to /ws"> <button>send</button>
</form>
<pre id="out"></pre>
<script>
const log = (s) => out.textContent += s + "\n";

function sse() {
const events = new EventSource("/sse");
events.onmessage = (e) => log("sse: " + e.data);
// close it, otherwise EventSource reconnects and runs the command again
events.addEventListener("exit", (e) => { log("sse exit code: " + e.data); events.close(); });
}

const ws = new WebSocket("ws" + location.origin.slice(4) + "/ws"); // ws:// or wss://
ws.onmessage = (e) => log("ws: " + e.data);
ws.onclose = (e) => log("ws exit code: " + e.reason);
</script>
16 changes: 16 additions & 0 deletions examples/stream/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/bin/sh

# All live output modes of shell2http, open http://localhost:8080/ in a browser, or:
# curl -N http://localhost:8080/stream
# curl -N http://localhost:8080/sse
# websocat ws://localhost:8080/ws
#
# from the repository: SHELL2HTTP="go run ../.." ./run.sh

cd "$(dirname "$0")" || exit 1

${SHELL2HTTP:-shell2http} \
GET:/ 'cat index.html' \
"/stream?stream=1" 'for i in 1 2 3 4 5; do echo "tick $i"; sleep 1; done' \
"/sse?sse=1" 'for i in 1 2 3 4 5; do echo "tick $i"; sleep 1; done; exit 3' \
"/ws?websocket=1" 'while read -r line; do echo "$line" | tr a-z A-Z; done'
8 changes: 7 additions & 1 deletion exec_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@

package main

import "os/exec"
import (
"os"
"os/exec"
)

// shutdownSignals - signals for shutdown of the server, running commands with a context are killed
var shutdownSignals = []os.Signal{os.Interrupt}

// setProcessGroup - process groups are not supported, on timeout only the shell process is killed
func setProcessGroup(_ *exec.Cmd) {}
3 changes: 3 additions & 0 deletions exec_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import (
"syscall"
)

// shutdownSignals - signals for shutdown of the server, running commands in own process groups are killed
var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}

// setProcessGroup - run the command in its own process group, and kill the whole group
// (the shell and everything it started) when the command context is done
func setProcessGroup(cmd *exec.Cmd) {
Expand Down
5 changes: 5 additions & 0 deletions exec_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ func Test_getShellHandler_CGIPathAndServer(t *testing.T) {
}

func Test_getShellHandler_CGIResponseHeaders(t *testing.T) {
t.Parallel()
data := []struct {
name string
cmd string
Expand Down Expand Up @@ -179,6 +180,7 @@ func Test_getShellHandler_CGIResponseHeaders(t *testing.T) {
}

func Test_execShellCommand_timeoutKillsProcessGroup(t *testing.T) {
t.Parallel()
appConfig := testConfig(1)
shell, params, err := getShellAndParams("sleep 5; echo done", appConfig)
if err != nil {
Expand All @@ -201,6 +203,7 @@ func Test_execShellCommand_timeoutKillsProcessGroup(t *testing.T) {
}

func Test_execShellCommand_timeoutBackgroundHoldsOutput(t *testing.T) {
t.Parallel()
appConfig := testConfig(10)
shell, params, err := getShellAndParams("sleep 5 & echo started", appConfig)
if err != nil {
Expand All @@ -220,6 +223,7 @@ func Test_execShellCommand_timeoutBackgroundHoldsOutput(t *testing.T) {
}

func Test_execShellCommand_detachedProcessSurvives(t *testing.T) {
t.Parallel()
for _, timeout := range []int{0, 1} {
appConfig := testConfig(timeout)
shell, params, err := getShellAndParams("sleep 5 >/dev/null 2>&1 & echo $!", appConfig)
Expand Down Expand Up @@ -250,6 +254,7 @@ func Test_execShellCommand_detachedProcessSurvives(t *testing.T) {
}

func Test_execShellCommand_clientDisconnect(t *testing.T) {
t.Parallel()
for _, timeout := range []int{0, 5} {
appConfig := testConfig(timeout)
finished := filepath.Join(t.TempDir(), "finished")
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ module github.com/msoap/shell2http
go 1.25

require (
github.com/gorilla/websocket v1.5.3
github.com/mattn/go-shellwords v1.0.14
github.com/msoap/raphanus v0.14.5
golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48
)
Loading