diff --git a/Makefile b/Makefile
index b143647..6e3e960 100644
--- a/Makefile
+++ b/Makefile
@@ -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
diff --git a/README.md b/README.md
index bda7671..0d381be 100644
--- a/README.md
+++ b/README.md
@@ -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
-------
@@ -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
@@ -160,6 +188,46 @@ shell2http -form /slow 'sleep ${v_duration:-1}; echo "sleep ${v_duration:-1} sec
```
+Live output of a log file (stream and SSE)
+
+```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(); });
+```
+
+
+Interactive command in a browser (WebSocket)
+
+```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)
+
+
Run command in background (don't wait for it to finish)
Redirect stdout and stderr of the background command, otherwise the request waits for it to finish:
@@ -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 `) 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
--------
diff --git a/config.go b/config.go
index 0bf22ba..0c8b3dc 100644
--- a/config.go
+++ b/config.go
@@ -1,6 +1,7 @@
package main
import (
+ "context"
"flag"
"fmt"
"log"
@@ -11,6 +12,7 @@ import (
"runtime"
"strconv"
"strings"
+ "sync"
)
type authUsers struct {
@@ -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
diff --git a/doc.go b/doc.go
index b63d946..82ba654 100644
--- a/doc.go
+++ b/doc.go
@@ -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"
diff --git a/examples/stream/index.html b/examples/stream/index.html
new file mode 100644
index 0000000..a97d9dc
--- /dev/null
+++ b/examples/stream/index.html
@@ -0,0 +1,21 @@
+
+shell2http live output
+
+
+
diff --git a/examples/stream/run.sh b/examples/stream/run.sh
new file mode 100755
index 0000000..30a03b0
--- /dev/null
+++ b/examples/stream/run.sh
@@ -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'
diff --git a/exec_other.go b/exec_other.go
index 349bb70..4ef179e 100644
--- a/exec_other.go
+++ b/exec_other.go
@@ -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) {}
diff --git a/exec_unix.go b/exec_unix.go
index cbb3df5..aaad6be 100644
--- a/exec_unix.go
+++ b/exec_unix.go
@@ -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) {
diff --git a/exec_unix_test.go b/exec_unix_test.go
index d522e47..898db55 100644
--- a/exec_unix_test.go
+++ b/exec_unix_test.go
@@ -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
@@ -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 {
@@ -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 {
@@ -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)
@@ -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")
diff --git a/go.mod b/go.mod
index 000f360..95f6b76 100644
--- a/go.mod
+++ b/go.mod
@@ -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
)
diff --git a/go.sum b/go.sum
index 71a8f1c..170e8b9 100644
--- a/go.sum
+++ b/go.sum
@@ -6,6 +6,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s=
github.com/labstack/gommon v0.3.1/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
@@ -29,6 +31,7 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
+golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48 h1:N9Vc/rorQUDes6B9CNdIxAn5jODGj2wzfrei2x4wNj4=
golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/http_middlewares.go b/http_middlewares.go
index 6510d8b..559f671 100644
--- a/http_middlewares.go
+++ b/http_middlewares.go
@@ -1,8 +1,10 @@
package main
import (
+ "bufio"
"fmt"
"log"
+ "net"
"net/http"
"sync"
"time"
@@ -133,6 +135,20 @@ func (rwl *responseWriterLogger) WriteHeader(statusCode int) {
rwl.srcRW.WriteHeader(statusCode)
}
+// Unwrap - get the original http.ResponseWriter, used by http.ResponseController (eg: Flush in the stream mode)
+func (rwl *responseWriterLogger) Unwrap() http.ResponseWriter {
+ return rwl.srcRW
+}
+
+// Hijack - take over the connection (the websocket mode), gorilla/websocket requires http.Hijacker, not Unwrap
+func (rwl *responseWriterLogger) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ conn, brw, err := http.NewResponseController(rwl.srcRW).Hijack()
+ if err == nil {
+ rwl.statusCode = http.StatusSwitchingProtocols
+ }
+ return conn, brw, err
+}
+
func (rwl *responseWriterLogger) StatusCode() int {
if rwl.statusCode == 0 {
return http.StatusOK
diff --git a/shell2http.1 b/shell2http.1
index 69e5af5..58b2773 100644
--- a/shell2http.1
+++ b/shell2http.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "SHELL2HTTP" "" "December 2024" "" ""
+.TH "SHELL2HTTP" "" "November 2026" "" ""
HTTP\-server designed to execute shell commands\. It is suitable for development, prototyping or remote control, facilitates rapid iteration and testing of shell\-based functionalities\. Easy to set up using just two command\-line arguments: URL\-path and shell command\. Next, when an HTTP request is made for the specified path, the stdout of the shell script will be returned, that\'s all\.
.
.SH "Usage"
@@ -18,6 +18,7 @@ options:
\- set environment variables with HTTP\-request information
\- write POST|PUT|PATCH\-data to script STDIN (if is not set \-form or body is not form data)
\- parse headers from script (eg: "Location: URL\en\en")
+ \- the script must always print its own headers block first (see Notes)
\-export\-vars=var : export environment vars ("VAR1,VAR2,\.\.\.")
by default export PATH, HOME, LANG, USER, TMPDIR
\-export\-all\-vars : export all current environment vars
@@ -57,67 +58,84 @@ $filename_ID \-\- uploaded file name from browser
.IP "" 0
.
.P
-With \fB\-form\-check\fR option you can specify the regular expression for checking the form fields\. For example, if you want to allow only variables that contain the only digits, you can specify the following option: \fB\-form\-check=\'^[0\-9]+$\'\fR\. Then only requests like \fBhttp://localhost:8080/path?NNN=123\fR will be produce variable \fB$v_NNN\fR\.
+In variable names all characters except \fBA\-Z\fR, \fBa\-z\fR, \fB0\-9\fR and \fB_\fR are replaced with \fB_\fR, so different parameters can give the same variable (see \fIForm variable names\fR)\.
+.
+.P
+With \fB\-form\-check\fR option you can specify the regular expression for checking the form fields\. For example, if you want to allow only variables that contain the only digits, you can specify the following option: \fB\-form\-check=\'^[0\-9]+$\'\fR\. Then only requests like \fBhttp://localhost:8080/path?NNN=123\fR will be produce variable \fB$v_NNN\fR\. A parameter passed several times (\fB?NNN=1&NNN=2\fR) is joined with \fB,\fR, and the joined value must match too (use \fB\-form\-check=\'^[0\-9,]+$\'\fR to allow it)\. The regexp also applies to the uploaded file name: a file whose name does not match is skipped, without \fB$filepath_ID\fR and \fB$filename_ID\fR\.
+.
+.P
+If the form can not be parsed (malformed body, body over the size limit, failed saving of an uploaded file), the command is not run and the client gets a \fB400\fR, \fB413\fR or \fB500\fR error\.
.
.P
To setup multiple auth users, you can specify the \fB\-basic\-auth\fR option multiple times\. The credentials for basic authentication may also be provided via the \fBSH_BASIC_AUTH\fR environment variable\. You can specify the preferred HTTP\-method (via \fBMETHOD:\fR prefix for path): \fBshell2http GET:/date date\fR
.
-.SH "Install"
-MacOS:
+.SH "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):
.
.IP "" 4
.
.nf
-brew install msoap/tools/shell2http
-# update:
-brew upgrade shell2http
+[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\'
.
.fi
.
.IP "" 0
.
-.P
-Download binaries from: releases \fIhttps://github\.com/msoap/shell2http/releases/latest\fR (MacOS/Linux/Windows/RaspberryPi)
+.IP "\(bu" 4
+the only allowed value is \fB1\fR (except \fBallow\-origin\fR), to disable an option just don\'t set it
+.
+.IP "\(bu" 4
+an unknown option, a value other than \fB1\fR (\fB/path?sse\fR, \fB/path?sse=true\fR), an empty \fB?\fR, more than one of \fBstream\fR, \fBsse\fR and \fBwebsocket\fR, or a \fBwebsocket\fR path with a method other than \fBGET\fR is an error on start
+.
+.IP "\(bu" 4
+the options are not a part of the path, so \fB/live?stream=1\fR and \fB/live\fR are the same path (a duplicate), the path still can have different commands for different methods (\fBGET:/live?sse=1\fR and \fBPOST:/live\fR)
+.
+.IP "\(bu" 4
+without options an endpoint works as usual: the output is sent after the command has finished
+.
+.IP "" 0
.
.P
-For Docker users, availeble tags see in Docker Hub \fIhttps://hub\.docker\.com/r/msoap/shell2http\fR:
+Remember to quote the path argument, \fB?\fR, \fB&\fR and \fB*\fR are special characters for the shell\. See \fILive output\fR and \fIWebSocket\fR for details\.
+.
+.SH "Install"
+MacOS:
.
.IP "" 4
.
.nf
-docker pull msoap/shell2http
+brew install msoap/tools/shell2http
+# update:
+brew upgrade shell2http
.
.fi
.
.IP "" 0
.
.P
-Using snap (Ubuntu or any Linux distribution with snap):
+Download binaries from: releases \fIhttps://github\.com/msoap/shell2http/releases/latest\fR (MacOS/Linux/Windows/RaspberryPi)
+.
+.P
+For Docker users, available tags see in Docker Hub \fIhttps://hub\.docker\.com/r/msoap/shell2http\fR:
.
.IP "" 4
.
.nf
-# install stable version:
-sudo snap install shell2http
-
-# install the latest version:
-sudo snap install \-\-edge shell2http
-
-# update
-sudo snap refresh shell2http
+docker pull msoap/shell2http
.
.fi
.
.IP "" 0
.
.P
-\fINotice\fR: the snap\-package has its own sandbox with the \fB/bin\fR, \fB/usr/bin\fR directories which are not equal to system\-wide \fBPATH\fR directories and commands may not work as expected or not work at all\.
-.
-.P
-Build from source (minimum Go version is 1\.12):
+Build from source (minimum Go version is 1\.25):
.
.IP "" 4
.
@@ -179,7 +197,7 @@ shell2http \-form /form \'echo "$v_from, $v_to"\'
.
.nf
-shell2http \-cgi /user_agent \'echo $HTTP_USER_AGENT\'
+shell2http \-cgi /user_agent \'echo "Content\-Type: text/plain"; echo; echo "$HTTP_USER_AGENT"\'
shell2http \-cgi /set \'touch file; echo "Location: /another_path\en"\' # redirect
shell2http \-cgi /404 \'echo "Status: 404"; echo; echo "404 page"\' # custom HTTP code
.
@@ -237,6 +255,93 @@ shell2http \-form /slow \'sleep ${v_duration:\-1}; echo "sleep ${v_duration:\-1}
.
.P
.
+.SS "Live output of a log file (stream and SSE)"
+.
+.nf
+
+shell2http "/live?stream=1" "tail \-F /var/log/system\.log" "/events?sse=1" "tail \-F /var/log/system\.log"
+.
+.fi
+.
+.P
+Read the stream with curl (\fB\-N\fR \- don\'t buffer the output):
+.
+.IP "" 4
+.
+.nf
+
+curl \-N http://localhost:8080/live
+curl \-N http://localhost:8080/events
+.
+.fi
+.
+.IP "" 0
+.
+.P
+Or in a browser with EventSource \fIhttps://developer\.mozilla\.org/en\-US/docs/Web/API/EventSource\fR:
+.
+.IP "" 4
+.
+.nf
+
+const events = new EventSource("/events");
+events\.onmessage = (e) => console\.log(e\.data);
+events\.addEventListener("exit", (e) => { console\.log("exit code:", e\.data); events\.close(); });
+.
+.fi
+.
+.IP "" 0
+.
+.P
+.
+.SS "Interactive command in a browser (WebSocket)"
+.
+.nf
+
+shell2http "/ws?websocket=1" \'while read \-r line; do echo "$line" | rev; done\'
+.
+.fi
+.
+.P
+Open \fBhttp://localhost:8080/\fR and run in the browser console:
+.
+.IP "" 4
+.
+.nf
+
+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"
+.
+.fi
+.
+.IP "" 0
+.
+.P
+Or from the command line, eg with websocat \fIhttps://github\.com/vi/websocat\fR: \fBwebsocat ws://localhost:8080/ws\fR
+.
+.P
+A page with all live output modes (stream, SSE and WebSocket): \fIexamples/stream\fR
+.
+.SS "Run command in background (don\'t wait for it to finish)"
+Redirect stdout and stderr of the background command, otherwise the request waits for it to finish:
+.
+.IP "" 4
+.
+.nf
+
+shell2http /run \'some_command >/dev/null 2>&1 & echo started\'
+# or keep output in log file:
+shell2http /run \'some_command >/tmp/cmd\.log 2>&1 & echo started\'
+.
+.fi
+.
+.IP "" 0
+.
+.P
+The background process keeps running even after shell2http server is stopped\.
+.
.SS "Proxy with cache in files (for debug API with rate limit)"
get \fBhttp://api\.url/\fR as \fBhttp://localhost:8080/get?url=http://api\.url/\fR
.
@@ -304,8 +409,6 @@ shell2http\.exe \-form \-form\-check="^[0\-9A\-Za\-z_]+$" /test "echo %v_var%"
.P
\fBcmd\fR expands \fB%v_var%\fR before it parses the command line, so characters like \fB&\fR or \fB|\fR in the value run as commands (\fB?var=x%26calc\fR runs \fBcalc\fR)\. Quoting does not help, so on Windows always limit the values with \fB\-form\-check\fR\.
.
-.P
-.
.SS "With HTTP headers"
Send custom HTTP headers:
.
@@ -393,6 +496,209 @@ go run $(go env GOROOT)/src/crypto/tls/generate_cert\.go \-host localhost
.
.IP "" 0
.
+.SH "Environment variables"
+shell2http reads these environment variables on start:
+.
+.P
+Example:
+.
+.IP "" 4
+.
+.nf
+
+SH_MAX_UPLOAD_SIZE=10485760 shell2http \-form POST:/file \'cat $filepath_uplfile > uploaded_file\.dat; echo Ok\'
+.
+.fi
+.
+.IP "" 0
+.
+.P
+Without a limit, uploaded files are saved to the temporary directory (\fB$TMPDIR\fR) and can fill the disk, set \fBSH_MAX_UPLOAD_SIZE\fR if the server is reachable by untrusted clients\.
+.
+.SH "Notes"
+.
+.SS "Caching"
+With \fB\-cache=N\fR option the command output is cached by the request URI (path + query string) only, this is by design\. HTTP method, request body, headers and cookies are not part of the cache key, so within N seconds:
+.
+.IP "\(bu" 4
+requests with the same URI but different methods (\fBGET:/item\fR and \fBDELETE:/item\fR) get the same cached output, the second command is not run
+.
+.IP "\(bu" 4
+POST/PUT/PATCH requests with the same URI but different bodies get the output of the first request
+.
+.IP "\(bu" 4
+in \fB\-cgi\fR mode, output that depends on headers or cookies (\fB$HTTP_COOKIE\fR, \fB$HTTP_USER_AGENT\fR, \.\.\.) is shared between all clients
+.
+.IP "\(bu" 4
+output of failed commands is cached too, and a cache hit is always returned with exit code 0 (no 500 error with \fB\-500\fR, \fBX\-Shell2http\-Exit\-Code: 0\fR)
+.
+.IP "" 0
+.
+.P
+Use \fB\-cache\fR only for idempotent commands whose output depends on the URI alone\.
+.
+.SS "Form variable names"
+In \fB\-form\fR mode a parameter name becomes a variable name with all characters except \fBA\-Z\fR, \fBa\-z\fR, \fB0\-9\fR and \fB_\fR replaced with \fB_\fR (non\-ASCII letters too, one \fB_\fR per character)\. So different parameters can give the same variable: \fBa\-b\fR, \fBa\.b\fR and \fBa_b\fR all become \fB$v_a_b\fR, \fBключ\fR and \fBимя_\fR both become \fB$v_____\fR\. Only one of them is used, the same one for every request:
+.
+.IP "\(bu" 4
+the parameter whose name is already a valid variable name (\fBa_b\fR),
+.
+.IP "\(bu" 4
+otherwise the first one in sorted (byte) order (\fBa\-b\fR before \fBa\.b\fR)\.
+.
+.IP "" 0
+.
+.P
+The other parameters are ignored\. This is decided before \fB\-form\-check\fR: if the chosen parameter doesn\'t match the regexp, the variable is not set, even when another parameter with the same variable name matches\. The same rules apply to uploaded files (\fB$filepath_ID\fR, \fB$filename_ID\fR), and a file that is not used is not saved\. Use only \fBA\-Z\fR, \fBa\-z\fR, \fB0\-9\fR and \fB_\fR in parameter names to avoid this\.
+.
+.SS "CGI mode headers"
+In \fB\-cgi\fR mode the headers block in the script output is optional\. Output is treated as headers + body when it starts with \fBName: value\fR lines followed by an empty line, otherwise the whole output is the body\. Printing correct headers is the responsibility of the script:
+.
+.IP "\(bu" 4
+if a script outputs request data (form fields, \fB$HTTP_*\fR, \fB$QUERY_STRING\fR, \fB$REQUEST_URI\fR, STDIN, \.\.\.) before its own headers, a client can supply the headers block, eg: \fBLocation\fR, \fBSet\-Cookie\fR or \fBStatus\fR (response header injection)
+.
+.IP "\(bu" 4
+without a \fBContent\-Type\fR header, the content type is detected from the output, so request data that starts with an HTML tag is served as \fBtext/html\fR (XSS)
+.
+.IP "" 0
+.
+.P
+So a CGI script should always print its own headers block first, at least \fBContent\-Type\fR and an empty line, even when it doesn\'t need any other headers:
+.
+.IP "" 4
+.
+.nf
+
+# unsafe: shell2http \-cgi \-form /reflect \'echo "$v_x"\'
+shell2http \-cgi \-form /reflect \'echo "Content\-Type: text/plain"; echo; echo "$v_x"\'
+.
+.fi
+.
+.IP "" 0
+.
+.P
+The first empty line ends the headers block, everything after it is sent as the body as is\.
+.
+.SS "Live output (stream and SSE)"
+With the \fBstream=1\fR or \fBsse=1\fR \fIendpoint option\fR the output is sent to the client while the command is running:
+.
+.IP "\(bu" 4
+the response headers are sent at once, with status \fB200\fR
+.
+.IP "\(bu" 4
+\fBstream=1\fR: the output is sent as is, as \fBtext/plain; charset=utf\-8\fR; the exit code is sent at the end as the \fBX\-Shell2http\-Exit\-Code\fR HTTP trailer
+.
+.IP "\(bu" 4
+\fBsse=1\fR: the output is sent as \fBtext/event\-stream\fR, each line of stdout is a \fBdata:\fR event (default type \fBmessage\fR), a line longer than 64KB is split into several events\. With \fB\-include\-stderr\fR the stderr lines are sent as \fBstderr\fR events\. When the command has finished, an \fBexit\fR event with the exit code is sent:
+.
+.IP "" 4
+.
+.nf
+
+data: first line
+
+event: stderr
+data: some error
+
+event: exit
+data: 0
+.
+.fi
+.
+.IP "" 0
+
+.
+.IP "\(bu" 4
+the command (the shell and all processes it started) is killed when the client disconnects, on \fB\-timeout\fR or on shutdown of shell2http (Unix only, on Windows only the shell process is killed)
+.
+.IP "\(bu" 4
+a browser \fBEventSource\fR reconnects (and runs the command again) when the stream ends, close it on the \fBexit\fR event if the command is not endless
+.
+.IP "" 0
+.
+.P
+Not all options work for streaming endpoints:
+.
+.IP "\(bu" 4
+\fB\-cache\fR \- the output is not cached
+.
+.IP "\(bu" 4
+\fB\-500\fR \- not applicable, the status is sent before the command has finished
+.
+.IP "\(bu" 4
+\fB\-show\-errors\fR \- not applicable, an exec error is not appended to the output (see the exit code instead)
+.
+.IP "\(bu" 4
+\fB\-cgi\fR \- CGI variables and the request body on STDIN work as usual, but headers are not parsed from the output
+.
+.IP "\(bu" 4
+\fB\-one\-thread\fR \- an endless stream holds the lock, so all other requests wait for it
+.
+.IP "" 0
+.
+.P
+Many programs buffer their output when it is not a terminal, so it comes in big chunks with a delay (eg: \fBgrep\fR, \fBawk\fR, \fBsed\fR, \fBpython\fR)\. Use line buffering for them: \fBgrep \-\-line\-buffered\fR, \fBsed \-u\fR, \fBpython \-u\fR, \fBstdbuf \-oL some_command\fR\.
+.
+.P
+A reverse proxy may buffer the response too: shell2http sends the \fBX\-Accel\-Buffering: no\fR header for nginx, for other proxies disable buffering for streaming paths in their settings\.
+.
+.SS "WebSocket"
+With the \fBwebsocket=1\fR \fIendpoint option\fR the command is started when a client opens a WebSocket (\fBnew WebSocket("ws://host:8080/path")\fR in a browser), and works while the connection is open:
+.
+.IP "\(bu" 4
+each message from the client (text or binary) is written to STDIN of the command with \fB\en\fR appended, so \fBread line\fR 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
+.
+.IP "\(bu" 4
+each line of stdout is sent as a message (without \fB\en\fR, \fB\er\en\fR), 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 \fB\-include\-stderr\fR the stderr lines are sent too
+.
+.IP "\(bu" 4
+when the command has finished, the connection is closed with the code \fB1000\fR and the exit code as the reason (\fBevent\.reason\fR in \fBonclose\fR), \fB\-1\fR for a killed command
+.
+.IP "\(bu" 4
+the command (the shell and all processes it started) is killed when the client closes the connection, on \fB\-timeout\fR or on shutdown of shell2http, like for \fIstreaming endpoints\fR
+.
+.IP "\(bu" 4
+the path accepts only WebSocket handshakes (\fBGET\fR without a body), a plain request gets \fB400\fR
+.
+.IP "\(bu" 4
+\fB\-form\fR, \fB\-cgi\fR (variables only, there is no request body) and \fB\-basic\-auth\fR work as usual, the options not working for streaming endpoints don\'t work here either
+.
+.IP "" 0
+.
+.P
+A browser connects a WebSocket from any web page, with the cookies and saved basic auth credentials of the site, so the \fBOrigin\fR of a page is checked with the \fBallow\-origin\fR option (a page that is not allowed gets \fB403\fR):
+.
+.IP "\(bu" 4
+\fBsame\-origin\fR (default) \- the host and port of \fBOrigin\fR are the same as in the \fBHost\fR header (\fBhttp://localhost:8080\fR for \fBlocalhost:8080\fR)
+.
+.IP "\(bu" 4
+\fBsame\-site\fR \- the same registrable domain, any port and subdomain (\fBhttps://app\.example\.com\fR for \fBapi\.example\.com\fR)
+.
+.IP "\(bu" 4
+\fB*\fR \- any page, use it only for a command that is safe to run by anyone
+.
+.IP "\(bu" 4
+\fBhttps://a\.com,http://localhost:3000\fR \- only these origins (scheme, host and port as the browser sends them)
+.
+.IP "" 0
+.
+.P
+A request without \fBOrigin\fR (not from a browser: \fBwebsocat\fR, scripts) is always allowed\. Behind a reverse proxy the \fBHost\fR header must be passed to shell2http as is, or use a list of origins\.
+.
+.SS "Shutdown"
+On \fBCtrl\-C\fR (\fBSIGINT\fR) or \fBSIGTERM\fR shell2http stops accepting new requests, kills running commands and waits up to 3 seconds for running requests to finish (a second \fBCtrl\-C\fR stops it at once):
+.
+.IP "\(bu" 4
+streaming endpoints and commands with \fB\-timeout\fR run in their own process group, the shell and all processes it started are killed (on Windows only \fBCtrl\-C\fR, and only the shell process is killed)
+.
+.IP "\(bu" 4
+other commands are in the process group of shell2http: \fBCtrl\-C\fR in a terminal reaches them as usual, but on \fBSIGTERM\fR (eg: \fBkill \fR) they are not killed and shell2http waits for them up to 3 seconds
+.
+.IP "\(bu" 4
+background processes of finished commands (\fBsome_command >/dev/null 2>&1 &\fR) keep running
+.
+.IP "" 0
+.
.SH "See also"
.
.IP "\(bu" 4
diff --git a/shell2http.go b/shell2http.go
index 51dd4c5..f932594 100644
--- a/shell2http.go
+++ b/shell2http.go
@@ -14,13 +14,16 @@ import (
"mime/multipart"
"net"
"net/http"
+ "net/url"
"os"
"os/exec"
+ "os/signal"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
+ "sync"
"time"
"github.com/mattn/go-shellwords"
@@ -71,8 +74,37 @@ const (
// waitDelay - with -timeout, how long to wait for the command output to be closed
// after the command has exited or has been killed
waitDelay = time.Second
+
+ // shutdownTimeout - on SIGINT/SIGTERM, how long to wait for running requests to finish
+ shutdownTimeout = 3 * time.Second
+
+ // exitCodeHeader - response header (or trailer in the stream mode) with the exit code of the command
+ exitCodeHeader = "X-Shell2http-Exit-Code"
)
+// outputMode - how the command output is sent to the client, set by the endpoint options
+type outputMode int
+
+const (
+ outputBuffered outputMode = iota // wait for the command to finish, then send the whole output (default)
+ outputStream // stream=1: send the output as it is written
+ outputSSE // sse=1: send each line of the output as a Server-Sent Event
+ outputWebSocket // websocket=1: messages from the client to stdin, each line of the output as a message
+)
+
+// allowOrigin* - special values of the allow-origin option, any other value is a list of origins
+const (
+ allowOriginSameOrigin = "same-origin" // the Origin host is the same as the Host header (default)
+ allowOriginSameSite = "same-site" // the Origin host has the same registrable domain as the Host header
+ allowOriginAll = "*" // any origin
+)
+
+// endpointOptions - settings of one endpoint, set as a query in the path: "/path?stream=1"
+type endpointOptions struct {
+ output outputMode
+ allowOrigin string // allow-origin: the origins allowed to open a WebSocket, "" - same-origin
+}
+
// indexTmpl - template for index page
const indexTmpl = `
@@ -107,6 +139,7 @@ type command struct {
path string
cmd string
httpMethod string
+ options endpointOptions
handler http.HandlerFunc
}
@@ -122,23 +155,91 @@ func parsePathAndCommands(args []string) ([]command, error) {
uniqPaths := map[string]bool{}
for i := 0; i < len(args); i += 2 {
- path, cmd := args[i], args[i+1]
- if uniqPaths[path] {
- return nil, fmt.Errorf("a duplicate path was detected: %q", path)
- }
+ rawPath, cmd := args[i], args[i+1]
- pathParts := pathRe.FindStringSubmatch(path)
+ pathParts := pathRe.FindStringSubmatch(rawPath)
if len(pathParts) != 3 {
- return nil, fmt.Errorf("the path %q must begin with the prefix /, and with optional METHOD: prefix", path)
+ return nil, fmt.Errorf("the path %q must begin with the prefix /, and with optional METHOD: prefix", rawPath)
+ }
+
+ path, rawOptions, hasOptions := strings.Cut(pathParts[2], "?")
+ var options endpointOptions
+ if hasOptions {
+ var err error
+ if options, err = parseEndpointOptions(rawOptions); err != nil {
+ return nil, fmt.Errorf("the path %q has invalid options: %s", rawPath, err)
+ }
+ }
+
+ // the WebSocket handshake is always a GET request
+ if options.output == outputWebSocket && pathParts[1] != "" && pathParts[1] != http.MethodGet {
+ return nil, fmt.Errorf("the path %q has invalid options: websocket works only with the GET method", rawPath)
}
- cmdHandlers = append(cmdHandlers, command{path: pathParts[2], cmd: cmd, httpMethod: pathParts[1]})
- uniqPaths[path] = true
+ // the same path with different options is a duplicate too
+ pathKey := pathParts[1] + ":" + path
+ if uniqPaths[pathKey] {
+ return nil, fmt.Errorf("a duplicate path was detected: %q", rawPath)
+ }
+ uniqPaths[pathKey] = true
+
+ cmdHandlers = append(cmdHandlers, command{path: path, cmd: cmd, httpMethod: pathParts[1], options: options})
}
return cmdHandlers, nil
}
+// parseEndpointOptions - parse the endpoint options from the query part of the path ("stream=1&..."),
+// the only allowed value is "1", except allow-origin
+func parseEndpointOptions(rawQuery string) (endpointOptions, error) {
+ var options endpointOptions
+
+ query, err := url.ParseQuery(rawQuery)
+ if err != nil {
+ return options, err
+ }
+ if len(query) == 0 {
+ return options, fmt.Errorf("no options after \"?\"")
+ }
+
+ outputModes := map[string]outputMode{"stream": outputStream, "sse": outputSSE, "websocket": outputWebSocket}
+
+ for _, name := range slices.Sorted(maps.Keys(query)) {
+ mode, ok := outputModes[name]
+ if !ok && name != "allow-origin" {
+ return options, fmt.Errorf("unknown option %q, supported: stream, sse, websocket, allow-origin", name)
+ }
+
+ values := query[name]
+ if len(values) > 1 {
+ return options, fmt.Errorf("the option %q is set several times", name)
+ }
+
+ if name == "allow-origin" {
+ if err := checkAllowOrigin(values[0]); err != nil {
+ return options, fmt.Errorf("the option %q: %s", name, err)
+ }
+ options.allowOrigin = values[0]
+ continue
+ }
+
+ if values[0] != "1" {
+ return options, fmt.Errorf("the option %q must be set to 1, got %q", name, values[0])
+ }
+
+ if options.output != outputBuffered {
+ return options, fmt.Errorf("only one of the options stream, sse and websocket can be set")
+ }
+ options.output = mode
+ }
+
+ if options.allowOrigin != "" && options.output != outputWebSocket {
+ return options, fmt.Errorf("the option \"allow-origin\" can be used only with websocket=1")
+ }
+
+ return options, nil
+}
+
// getShellAndParams - get default shell and command
func getShellAndParams(cmd string, appConfig Config) (shell string, params []string, err error) {
shell, params = appConfig.defaultShell, []string{appConfig.defaultShOpt, cmd} // sh -c "cmd"
@@ -167,16 +268,10 @@ func getShellHandler(appConfig Config, shell string, params []string, cacheTTL r
reStatusCode := regexp.MustCompile(`^\d+`)
return func(rw http.ResponseWriter, req *http.Request) {
- if appConfig.setForm && appConfig.maxUploadSize > 0 && isFormData(req.Header) {
- req.Body = http.MaxBytesReader(rw, req.Body, appConfig.maxUploadSize)
- }
+ limitFormBody(rw, req, appConfig)
shellOut, exitCode, err := execShellCommand(appConfig, shell, params, req, cacheTTL)
- var formErr *formError
- if errors.As(err, &formErr) {
- // the command was not run, don't show internal details (like temp paths) to the client
- log.Printf("read request body failed: %s", err)
- http.Error(rw, http.StatusText(formErr.status), formErr.status)
+ if writeFormError(rw, err) {
return
}
if err != nil {
@@ -217,7 +312,7 @@ func getShellHandler(appConfig Config, shell string, params []string, cacheTTL r
}
}
- rw.Header().Set("X-Shell2http-Exit-Code", strconv.Itoa(exitCode))
+ rw.Header().Set(exitCodeHeader, strconv.Itoa(exitCode))
if customStatusCode > 0 {
rw.WriteHeader(customStatusCode)
@@ -229,6 +324,26 @@ func getShellHandler(appConfig Config, shell string, params []string, cacheTTL r
}
}
+// limitFormBody - limit the size of the request body parsed by -form (SH_MAX_UPLOAD_SIZE)
+func limitFormBody(rw http.ResponseWriter, req *http.Request, appConfig Config) {
+ if appConfig.setForm && appConfig.maxUploadSize > 0 && isFormData(req.Header) {
+ req.Body = http.MaxBytesReader(rw, req.Body, appConfig.maxUploadSize)
+ }
+}
+
+// writeFormError - if the command was not run because of the request body, send the error to the client
+func writeFormError(rw http.ResponseWriter, err error) bool {
+ var formErr *formError
+ if !errors.As(err, &formErr) {
+ return false
+ }
+
+ // don't show internal details (like temp paths) to the client
+ log.Printf("read request body failed: %s", err)
+ http.Error(rw, http.StatusText(formErr.status), formErr.status)
+ return true
+}
+
// execShellCommand - execute shell command, returns bytes out and error
func execShellCommand(appConfig Config, shell string, params []string, req *http.Request, cacheTTL raphanus.DB) ([]byte, int, error) {
if appConfig.cache > 0 {
@@ -241,11 +356,59 @@ func execShellCommand(appConfig Config, shell string, params []string, req *http
}
// the command is not bound to the request context: a client disconnect must not
- // abort a script halfway, only -timeout limits the execution time
- var osExecCommand *exec.Cmd
+ // abort a script halfway, only -timeout limits the execution time. Without -timeout
+ // the command is in the process group of shell2http and gets Ctrl-C from the terminal,
+ // with -timeout it is in its own process group and is killed on shutdown.
+ ctx := context.Background()
if appConfig.timeout > 0 {
- ctx, cancelFn := context.WithTimeout(context.Background(), time.Duration(appConfig.timeout)*time.Second)
+ var cancelFn context.CancelFunc
+ ctx, cancelFn = context.WithTimeout(appConfig.commandContext(), time.Duration(appConfig.timeout)*time.Second)
defer cancelFn()
+ }
+
+ shellCmd, err := newShellCommand(ctx, appConfig, shell, params, req)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ var stdoutBuf, stderrBuf bytes.Buffer
+ stderr := io.Writer(&stderrBuf)
+ if appConfig.includeStderr {
+ stderr = &stdoutBuf
+ }
+
+ exitCode, err := shellCmd.run(&stdoutBuf, stderr)
+ if stderrBuf.Len() > 0 {
+ log.Printf("stderr: %s", stderrBuf.String())
+ }
+ shellOut := stdoutBuf.Bytes()
+
+ if appConfig.cache > 0 {
+ if cacheErr := cacheTTL.SetBytes(req.RequestURI, shellOut, appConfig.cache); cacheErr != nil {
+ log.Printf("set to cache failed: %s", cacheErr)
+ }
+ }
+
+ return shellOut, exitCode, err
+}
+
+// shellCommand - a command prepared for the request, see newShellCommand
+type shellCommand struct {
+ cmd *exec.Cmd
+ finalizer func() // removes temporary files of the request
+ pipeErrCh chan error // result of writing the request body to the command stdin, nil if the body is not written
+
+ // called after the command has exited, if the request body is still being read (a stalled upload),
+ // to interrupt the reading, nil - wait for it as long as it takes (the buffered mode)
+ interruptInput func()
+}
+
+// newShellCommand - prepare the command for the request: environment, form variables and uploaded files,
+// CGI variables and the request body on stdin. If ctx can be canceled, the shell and all processes it started
+// are killed when ctx is done. On error the command must not be run.
+func newShellCommand(ctx context.Context, appConfig Config, shell string, params []string, req *http.Request) (*shellCommand, error) {
+ var osExecCommand *exec.Cmd
+ if ctx.Done() != nil {
osExecCommand = exec.CommandContext(ctx, shell, params...) // #nosec
setProcessGroup(osExecCommand)
// don't wait for processes that escaped the process group and still hold stdout/stderr
@@ -256,23 +419,16 @@ func execShellCommand(appConfig Config, shell string, params []string, req *http
proxySystemEnv(osExecCommand, appConfig)
- finalizer := func() {}
+ shellCmd := &shellCommand{cmd: osExecCommand, finalizer: func() {}}
if appConfig.setForm {
var err error
- if finalizer, err = getForm(osExecCommand, req, appConfig.formCheckRe); err != nil {
+ if shellCmd.finalizer, err = getForm(osExecCommand, req, appConfig.formCheckRe); err != nil {
// fail closed: don't run the command with some of the form variables missing
- finalizer()
- return nil, 0, err
+ shellCmd.finalizer()
+ return nil, err
}
}
- var (
- waitPipeWrite bool
- pipeErrCh = make(chan error)
- shellOut []byte
- err error
- )
-
if appConfig.setCGI {
// get request body data data to stdin of script (if not parse form vars above)
writeBody := (req.Method == "POST" || req.Method == "PUT" || req.Method == "PATCH") && (!appConfig.setForm || !isFormData(req.Header))
@@ -281,11 +437,11 @@ func execShellCommand(appConfig Config, shell string, params []string, req *http
// a chunked body has no length, read it all to set CONTENT_LENGTH (RFC 3875 4.1.2)
removeSpool, spoolErr := spoolBody(req)
if spoolErr != nil {
- finalizer()
- return nil, 0, newFormParseError(spoolErr)
+ shellCmd.finalizer()
+ return nil, newFormParseError(spoolErr)
}
- formFinalizer := finalizer
- finalizer = func() {
+ formFinalizer := shellCmd.finalizer
+ shellCmd.finalizer = func() {
removeSpool()
formFinalizer()
}
@@ -297,7 +453,8 @@ func execShellCommand(appConfig Config, shell string, params []string, req *http
if stdin, pipeErr := osExecCommand.StdinPipe(); pipeErr != nil {
log.Println("write request body data to shell failed:", pipeErr)
} else {
- waitPipeWrite = true
+ pipeErrCh := make(chan error, 1)
+ shellCmd.pipeErrCh = pipeErrCh
go func() {
if _, pipeErr := io.Copy(stdin, req.Body); pipeErr != nil {
pipeErrCh <- pipeErr
@@ -309,16 +466,14 @@ func execShellCommand(appConfig Config, shell string, params []string, req *http
}
}
- if appConfig.includeStderr {
- shellOut, err = osExecCommand.CombinedOutput()
- } else {
- var stderrBuf bytes.Buffer
- osExecCommand.Stderr = &stderrBuf
- shellOut, err = osExecCommand.Output()
- if stderrBuf.Len() > 0 {
- log.Printf("stderr: %s", stderrBuf.String())
- }
- }
+ return shellCmd, nil
+}
+
+// run - run the command with the output to stdout and stderr (may be the same writer),
+// removes temporary files of the request, returns the exit code
+func (sc *shellCommand) run(stdout, stderr io.Writer) (int, error) {
+ sc.cmd.Stdout, sc.cmd.Stderr = stdout, stderr
+ err := sc.cmd.Run()
if errors.Is(err, exec.ErrWaitDelay) {
// the command exited successfully, but some background process kept its output open
@@ -326,26 +481,31 @@ func execShellCommand(appConfig Config, shell string, params []string, req *http
err = nil
}
- if waitPipeWrite {
- if pipeErr := <-pipeErrCh; pipeErr != nil {
+ if sc.pipeErrCh != nil {
+ var pipeErr error
+ select {
+ case pipeErr = <-sc.pipeErrCh:
+ default:
+ // the request body is still being read (eg: a stalled upload)
+ if sc.interruptInput != nil {
+ sc.interruptInput()
+ }
+ pipeErr = <-sc.pipeErrCh
+ }
+ if pipeErr != nil {
log.Println("write request body data to shell failed:", pipeErr)
}
}
- finalizer()
+ sc.finalizer()
- if appConfig.cache > 0 {
- if cacheErr := cacheTTL.SetBytes(req.RequestURI, shellOut, appConfig.cache); cacheErr != nil {
- log.Printf("set to cache failed: %s", cacheErr)
- }
+ // -1 if the command was not started (eg: the shell is not found), the same as for a killed command
+ exitCode := -1
+ if sc.cmd.ProcessState != nil {
+ exitCode = sc.cmd.ProcessState.ExitCode()
}
- exitCode := 0
- if osExecCommand.ProcessState != nil {
- exitCode = osExecCommand.ProcessState.ExitCode()
- }
-
- return shellOut, exitCode, err
+ return exitCode, err
}
// setupHandlers - setup http handlers
@@ -374,7 +534,17 @@ func setupHandlers(cmdHandlers []command, appConfig Config, cacheTTL raphanus.DB
indexLiHTML = append(indexLiHTML, fmt.Sprintf(`