├── version.txt ├── AUTHORS.md ├── .github ├── workflows │ ├── gogitops.yml │ ├── release-please.yml │ ├── go-build.yml │ └── codeql-analysis.yml ├── dependabot.yml └── ISSUE_TEMPLATE │ └── bug_report.md ├── .gitignore ├── go.mod ├── main.go ├── pkg ├── portainer │ ├── terminal.go │ └── api.go └── wsterm │ └── wsterm.go ├── README.md ├── internal └── config │ └── config.go ├── CHANGELOG.md └── LICENSE /version.txt: -------------------------------------------------------------------------------- 1 | 1.7.0 2 | -------------------------------------------------------------------------------- /AUTHORS.md: -------------------------------------------------------------------------------- 1 | # Authors 2 | 3 | This project was originally forked from a great tool called Rancher SSH. 4 | 5 | # Original Rancher SSH credits 6 | 7 | ## Authors 8 | 9 | Rancher SSH was written and is maintained by Fang Li, Funplus and 10 | various contributors. 11 | -------------------------------------------------------------------------------- /.github/workflows/gogitops.yml: -------------------------------------------------------------------------------- 1 | name: GoGitOps 2 | on: 3 | pull_request: 4 | branches: 5 | - 'master' 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v1 11 | - name: GoGitOps Step 12 | id: gogitops 13 | uses: beaujr/gogitops-action@v0.2 14 | with: 15 | github-actions-token: ${{secrets.GITHUB_TOKEN}} 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.test 23 | *.prof 24 | /config.* 25 | 26 | # Compiled binaries 27 | *.exe 28 | portainerssh 29 | 30 | # GoLand stuff 31 | .idea/ -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - master 5 | name: release-please 6 | jobs: 7 | release-please: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: GoogleCloudPlatform/release-please-action@v2 11 | with: 12 | # The usual GITHUB_TOKEN doesn't work since PRs created using it doesn't trigger GitHub actions builds. 13 | token: ${{ secrets.RELEASE_PLEASE_TOKEN }} 14 | release-type: simple 15 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/devbranch-vadym/portainerssh 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/alecthomas/units v0.0.0-20210208195552-ff826a37aa15 // indirect 7 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 8 | github.com/gorilla/websocket v1.5.1 9 | github.com/kopoli/go-terminal-size v0.0.0-20170219200355-5c97524c8b54 10 | github.com/minio/pkg v1.7.5 11 | github.com/spf13/viper v1.18.2 12 | golang.org/x/crypto v0.21.0 13 | gopkg.in/alecthomas/kingpin.v2 v2.2.6 14 | ) 15 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gomod" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "daily" 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Actual behavior** 24 | What is happening instead 25 | 26 | **Environment:** 27 | - Portainer version 28 | - `portainerssh` version 29 | - Go version (for custom builds) 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | _ "embed" 5 | "os" 6 | 7 | "github.com/devbranch-vadym/portainerssh/internal/config" 8 | "github.com/devbranch-vadym/portainerssh/pkg/portainer" 9 | "github.com/devbranch-vadym/portainerssh/pkg/wsterm" 10 | ) 11 | 12 | //go:embed version.txt 13 | var version string 14 | 15 | func main() { 16 | config, params := config.ReadConfig(version) 17 | api := portainer.API{ 18 | ApiUrl: config.ApiUrl, 19 | Endpoint: config.Endpoint, 20 | User: config.User, 21 | Password: config.Password, 22 | ApiKey: config.ApiKey, 23 | } 24 | conn := api.GetContainerConn(params) 25 | 26 | wt := wsterm.NewWebTerm(conn.ShellConnection) 27 | wt.Run() 28 | 29 | exitCode, err := conn.PortainerApi.GetExecSessionExitCode(conn.InstanceId) 30 | if err != nil { 31 | panic(err) 32 | } 33 | 34 | os.Exit(exitCode) 35 | } 36 | -------------------------------------------------------------------------------- /pkg/portainer/terminal.go: -------------------------------------------------------------------------------- 1 | package portainer 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "net/http" 7 | "strconv" 8 | 9 | tsize "github.com/kopoli/go-terminal-size" 10 | ) 11 | 12 | // TerminalDimensions is a simple struct containing current user's terminal width and height. 13 | type TerminalDimensions struct { 14 | Width int 15 | Height int 16 | } 17 | 18 | func (r *API) resizeTerminal(execEndpointId string, size tsize.Size) error { 19 | jsonBodyData := map[string]interface{}{ 20 | "Height": size.Height, 21 | "Width": size.Width, 22 | "id": execEndpointId, 23 | } 24 | body, err := json.Marshal(jsonBodyData) 25 | if err != nil { 26 | return err 27 | } 28 | req, _ := http.NewRequest("POST", r.formatHttpApiUrl()+"/endpoints/"+strconv.Itoa(r.Endpoint)+"/docker/exec/"+execEndpointId+"/resize?h="+strconv.Itoa(size.Height)+"&w="+strconv.Itoa(size.Width), bytes.NewReader(body)) 29 | _, err = r.makeObjReq(req, true) 30 | 31 | return err 32 | } 33 | 34 | // TriggerResize is a simple Resize event trigger. 35 | type TriggerResize struct{} 36 | 37 | func (r *API) handleTerminalResize(execInstanceId string) (chan<- TriggerResize, <-chan error, error) { 38 | sizeListener, err := tsize.NewSizeListener() 39 | if err != nil { 40 | // Error creating SizeListener 41 | return nil, nil, err 42 | } 43 | resize := make(chan TriggerResize) 44 | errChan := make(chan error) 45 | 46 | go func() { 47 | for { 48 | select { 49 | case <-resize: 50 | size, err := tsize.GetSize() 51 | if err != nil { 52 | errChan <- err 53 | } 54 | r.resizeTerminal(execInstanceId, size) 55 | 56 | case newSize := <-sizeListener.Change: 57 | r.resizeTerminal(execInstanceId, newSize) 58 | } 59 | } 60 | }() 61 | 62 | return resize, errChan, nil 63 | } 64 | -------------------------------------------------------------------------------- /.github/workflows/go-build.yml: -------------------------------------------------------------------------------- 1 | # workflow name 2 | name: Go Build 3 | 4 | # on events 5 | on: 6 | pull_request: 7 | branches: 8 | - master 9 | release: 10 | types: 11 | - created 12 | 13 | # jobs 14 | jobs: 15 | cross-platform-build: 16 | strategy: 17 | matrix: 18 | include: 19 | - go-os: linux 20 | go-arch: amd64 21 | - go-os: linux 22 | go-arch: arm64 23 | - go-os: windows 24 | go-arch: amd64 25 | - go-os: darwin 26 | go-arch: amd64 27 | - go-os: darwin 28 | go-arch: arm64 29 | runs-on: ubuntu-latest 30 | 31 | steps: 32 | # step 1: checkout repository code 33 | - name: Checkout the repository 34 | uses: actions/checkout@v2 35 | 36 | # step 2: install Go 37 | - name: Install Go 38 | uses: actions/setup-go@v2 39 | with: 40 | go-version: ^1.16.0 41 | 42 | # step 3: run Go vet 43 | - name: Run Go vet 44 | env: 45 | GOOS: ${{ matrix.go-os }} 46 | GOARCH: ${{ matrix.go-arch }} 47 | run: go vet . 48 | 49 | # step 4: create dist 50 | - name: Prepare files to archive 51 | run: | 52 | mkdir -p dist 53 | mkdir -p out 54 | cp README.md LICENSE dist/ 55 | shell: bash 56 | 57 | # step 5: run Go build 58 | - name: Run Go build 59 | env: 60 | GOOS: ${{ matrix.go-os }} 61 | GOARCH: ${{ matrix.go-arch }} 62 | run: go build -v -o dist/ 63 | 64 | # step 6: store the build version 65 | - name: Store build version 66 | if: ${{ github.event_name == 'release' && github.event.action == 'created' }} 67 | run: | 68 | echo "BUILD_VERSION=`cat version.txt`" >> $GITHUB_ENV 69 | 70 | # step 7: create release archive 71 | - name: Create release archive 72 | if: ${{ github.event_name == 'release' && github.event.action == 'created' }} 73 | uses: ihiroky/archive-action@v1 74 | with: 75 | root_dir: dist 76 | file_path: out/portainerssh-${{ matrix.go-os }}-${{ matrix.go-arch }}-${{ env.BUILD_VERSION }}.tar.gz 77 | 78 | # step 8: upload build-artifacts 79 | - name: Upload build-artifacts 80 | if: ${{ github.event_name == 'release' && github.event.action == 'created' }} 81 | uses: skx/github-action-publish-binaries@master 82 | env: 83 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 84 | with: 85 | args: "./out/*.tar.gz" 86 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '17 22 * * 2' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'go' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 37 | # Learn more: 38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 39 | 40 | steps: 41 | - name: Checkout repository 42 | uses: actions/checkout@v2 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /pkg/wsterm/wsterm.go: -------------------------------------------------------------------------------- 1 | package wsterm 2 | 3 | import ( 4 | "github.com/gorilla/websocket" 5 | "golang.org/x/crypto/ssh/terminal" 6 | "io" 7 | "os" 8 | ) 9 | 10 | // WebTerm connects to remote shell via websocket protocol and connects it to local terminal. 11 | type WebTerm struct { 12 | SocketConn *websocket.Conn 13 | ttyState *terminal.State 14 | errChn chan error 15 | } 16 | 17 | // NewWebTerm creates a new WebTerm object and connects it to a given websocket. 18 | func NewWebTerm(socketConn *websocket.Conn) *WebTerm { 19 | return &WebTerm{SocketConn: socketConn} 20 | } 21 | 22 | func (w *WebTerm) wsWrite() { 23 | var err error 24 | var keybuf [1]byte 25 | for { 26 | _, err = os.Stdin.Read(keybuf[0:1]) 27 | if err != nil { 28 | if err != io.EOF { 29 | // EOF is not really an error so it shouldn't be sent to errors channel. 30 | // On the other hand, receiving EOF should stop writing to websocket. 31 | w.errChn <- err 32 | } 33 | return 34 | } 35 | 36 | err = w.SocketConn.WriteMessage(websocket.BinaryMessage, keybuf[0:1]) 37 | if err != nil { 38 | if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseAbnormalClosure) { 39 | w.errChn <- nil 40 | } else { 41 | w.errChn <- err 42 | } 43 | return 44 | } 45 | } 46 | } 47 | 48 | func (w *WebTerm) wsRead() { 49 | var err error 50 | var raw []byte 51 | for { 52 | _, raw, err = w.SocketConn.ReadMessage() 53 | if err != nil { 54 | if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseAbnormalClosure) { 55 | w.errChn <- nil 56 | } else { 57 | w.errChn <- err 58 | } 59 | return 60 | } 61 | os.Stdout.Write(filterZeroBytes(raw)) 62 | } 63 | } 64 | 65 | func (w *WebTerm) setRawtty(isRaw bool) { 66 | stdInFd := int(os.Stdin.Fd()) 67 | if !terminal.IsTerminal(stdInFd) { 68 | // Do not attempt to change the terminal mode if it's not a TTY. 69 | return 70 | } 71 | 72 | if isRaw { 73 | state, err := terminal.MakeRaw(stdInFd) 74 | if err != nil { 75 | panic(err) 76 | } 77 | w.ttyState = state 78 | } else { 79 | terminal.Restore(stdInFd, w.ttyState) 80 | } 81 | } 82 | 83 | // Run starts transferring data between local terminal and remote shell connection. 84 | func (w *WebTerm) Run() { 85 | w.errChn = make(chan error) 86 | w.setRawtty(true) 87 | 88 | go w.wsRead() 89 | go w.wsWrite() 90 | 91 | err := <-w.errChn 92 | w.setRawtty(false) 93 | 94 | if err != nil { 95 | panic(err) 96 | } 97 | } 98 | 99 | // filterZeroBytes removes all zero bytes from the given byte array. 100 | func filterZeroBytes(data []byte) []byte { 101 | n := 0 102 | 103 | for _, val := range data { 104 | if val != 0 { 105 | data[n] = val 106 | n++ 107 | } 108 | } 109 | 110 | return data[:n] 111 | } 112 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Portainer SSH 2 | 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/devbranch-vadym/portainerssh)](https://goreportcard.com/report/github.com/devbranch-vadym/portainerssh) 4 | [![Go Reference](https://pkg.go.dev/badge/github.com/devbranch-vadym/portainerssh.svg)](https://pkg.go.dev/github.com/devbranch-vadym/portainerssh) 5 | [![Release](https://img.shields.io/github/v/release/devbranch-vadym/portainerssh.svg?style=flat-square)](https://github.com/devbranch-vadym/portainerssh/releases/latest) 6 | 7 | Native shell client for Portainer containers, provided a powerful native terminal to manage your Docker containers. 8 | 9 | * It's dead simple. like the ssh cli, you do `portainerssh container_name` to SSH into any containers 10 | * It's flexible. `portainerssh` reads configurations from ENV, from yml or json file 11 | * It's powerful. `portainerssh` searches the whole Portainer deployment, open shell into any containers from your 12 | workstation, regardless which host it belongs to 13 | * It's smart. `portainerssh` uses fuzzy container name matching. Forget the container name? it doesn't matter, use "*" 14 | or "%" instead 15 | 16 | ## Is it really an SSH client? 17 | No. It's called so for historical purposes. It _acts_ like SSH in terms of providing you shell access to your 18 | containers. Also SSH is what people are likely googling for. 19 | 20 | 21 | ## Installation 22 | 23 | ### Via Golang 24 | 25 | ```bash 26 | go get github.com/devbranch-vadym/portainerssh 27 | ```` 28 | 29 | ### Binary builds 30 | 31 | Binary builds may be found at [releases](https://github.com/devbranch-vadym/portainerssh/releases) 32 | page. We currently provide `amd64` and `arm64` builds for GNU/Linux and Mac and `amd64` for Windows. 33 | 34 | ## Configuration 35 | 36 | The configuration could be provided by either `config.json` or `config.yml` in `./`, `/etc/portainerssh/` or `~/.portainerssh/` folders. 37 | 38 | If you want to use JSON format, create a `config.json` in the folders with content: 39 | 40 | ```json 41 | { 42 | "api_url": "https://portainerssh.server/api", 43 | "user": "your_access_key", 44 | "password": "your_access_password", 45 | "endpoint": "10", 46 | "api_key": "your_api_key" 47 | } 48 | ``` 49 | 50 | If you want to use YAML format, create a `config.yml` with content: 51 | 52 | ```yml 53 | api_url: https://your.portainer.server/api 54 | user: your_access_key 55 | password: your_access_password 56 | endpoint: 10 # Optional Portainer endpoint ID, defaults to 1. 57 | api_key: your_api_key # Optional Portainer API key, defaults to empty. Replaces username and password. 58 | ``` 59 | 60 | We accept environment variables as well: 61 | 62 | ```shell 63 | PORTAINER_API_URL=https://your.portainer.server/api 64 | PORTAINER_USER=your_access_key 65 | PORTAINER_PASSWORD=your_access_password 66 | PORTAINER_API_KEY=your_access_token 67 | ``` 68 | 69 | ## Usage 70 | 71 | ```bash 72 | portainerssh [] 73 | ```` 74 | 75 | `?` in container name matches any single character. "%" matches zero or more characters. 76 | 77 | ### Examples 78 | 79 | ``` 80 | portainerssh my-container-name 81 | portainerssh my-container-% 82 | portainerssh %-container-% 83 | portainerssh my-container-???? 84 | portainerssh -c /bin/sh my-container-name 85 | ``` 86 | 87 | ### Flags 88 | 89 | ``` 90 | -h, --help Show context-sensitive help (also try --help-long and --help-man). 91 | --version Show application version. 92 | --api_url="" Portainer server API URL, https://your.portainer.server/api . 93 | --endpoint=1 Portainer endpoint ID. Default is 1. 94 | --user="" Portainer API user/accesskey. 95 | --password="" Portainer API password/secret. 96 | --api_key="" Portainer API key. 97 | -c, --command="bash" Command to execute inside container. 98 | -u, --run_as_user="" User to execute container command as. 99 | -w, --workdir="" Working directory to execute command in. 100 | ``` 101 | 102 | ### Arguments 103 | 104 | ``` 105 | Container name, wildcards allowed 106 | ``` 107 | 108 | ### Limitations 109 | Currently, only Docker endpoints are supported. 110 | 111 | ## History 112 | `portainerssh` is based on wonderful `rancherssh` utility by Fang Li. In fact, `portainerssh` is a fork and partial 113 | rewrite of `rancherssh`, just for Portainer. 114 | -------------------------------------------------------------------------------- /internal/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "os" 5 | "strings" 6 | 7 | "github.com/spf13/viper" 8 | "gopkg.in/alecthomas/kingpin.v2" 9 | 10 | "github.com/devbranch-vadym/portainerssh/pkg/portainer" 11 | "github.com/google/shlex" 12 | ) 13 | 14 | const ( 15 | author = "Vadym Abramchuk " 16 | usage = ` 17 | Connect to container by it's name: 18 | portainerssh my-server-1 19 | Substitute single character: 20 | portainerssh "my-server-?" 21 | Connect any container matching pattern: 22 | portainerssh "%server%" 23 | 24 | Wildcards matching: 25 | "?" matches any single character. "%" matches zero or more characters. 26 | 27 | Configuration: 28 | We read configuration from config.json or config.yml in ./, /etc/portainerssh/ and ~/.portainerssh/ folders. 29 | 30 | If you want to use JSON format, create a config.json in the folders with content: 31 | { 32 | "api_url": "https://portainerssh.server/api", 33 | "user": "your_access_key", 34 | "password": "your_access_password", 35 | "endpoint": 1, 36 | "api_key": "my-api-key-here" 37 | } 38 | 39 | If you want to use YAML format, create a config.yml with content: 40 | api_url: https://your.portainer.server/api 41 | user: your_access_key 42 | password: your_access_password 43 | endpoint: 1 44 | api_key: my-api-key-here 45 | 46 | We accept environment variables as well: 47 | PORTAINER_API_URL=https://your.portainer.server/api 48 | PORTAINER_USER=your_access_key 49 | PORTAINER_PASSWORD=your_access_password 50 | ` 51 | ) 52 | 53 | // Config is a runtime configuration. 54 | type Config struct { 55 | ApiUrl string 56 | Endpoint int 57 | User string 58 | Password string 59 | ApiKey string 60 | } 61 | 62 | // ReadConfig gathers configuration values from all available sources and returns everything required to connect 63 | // to Portainer API and execute a command in container. 64 | func ReadConfig(version string) (*Config, *portainer.ContainerExecParams) { 65 | app := kingpin.New("portainerssh", usage) 66 | app.Author(author) 67 | app.Version(strings.TrimSpace(version)) 68 | app.HelpFlag.Short('h') 69 | 70 | viper.SetDefault("api_url", "") 71 | viper.SetDefault("endpoint", "1") 72 | viper.SetDefault("user", "") 73 | viper.SetDefault("password", "") 74 | viper.SetDefault("api_key", "") 75 | 76 | viper.SetConfigName("config") // name of config file (without extension) 77 | viper.AddConfigPath(".") // call multiple times to add many search paths 78 | viper.AddConfigPath("$HOME/.portainerssh") // call multiple times to add many search paths 79 | viper.AddConfigPath("/etc/portainerssh/") // path to look for the config file in 80 | viper.ReadInConfig() 81 | 82 | viper.SetEnvPrefix("portainer") 83 | viper.AutomaticEnv() 84 | 85 | var apiUrl = app.Flag("api_url", "Portainer server API URL, https://your.portainer.server/api .").Default(viper.GetString("api_url")).String() 86 | var endpoint = app.Flag("endpoint", "Portainer endpoint ID. Default is 1.").Default(viper.GetString("endpoint")).Int() 87 | var user = app.Flag("user", "Portainer API user/accesskey.").Default(viper.GetString("user")).String() 88 | var password = app.Flag("password", "Portainer API password/secret.").Default(viper.GetString("password")).String() 89 | var apiKey = app.Flag("api_key", "Portainer API key.").Default(viper.GetString("api_key")).String() 90 | 91 | var container = app.Arg("container", "Container name, wildcards allowed").Required().String() 92 | var command = app.Flag("command", "Command to execute inside container.").Default("bash").Short('c').String() 93 | var runAs = app.Flag("run_as_user", "User to execute container command as.").Default("").Short('u').String() 94 | var workdir = app.Flag("workdir", "Working directory to execute command in.").Default("").Short('w').String() 95 | 96 | app.Parse(os.Args[1:]) 97 | 98 | var hasAuthCredentials = (*user != "" && *password != "") || *apiKey != "" 99 | 100 | if *apiUrl == "" || *endpoint == 0 || !hasAuthCredentials || *container == "" { 101 | app.Usage(os.Args[1:]) 102 | os.Exit(1) 103 | } 104 | 105 | // TODO: Handle shlex.Split errors 106 | commandParts, _ := shlex.Split(*command) 107 | 108 | return &Config{ 109 | ApiUrl: *apiUrl, 110 | Endpoint: *endpoint, 111 | User: *user, 112 | Password: *password, 113 | ApiKey: *apiKey, 114 | }, &portainer.ContainerExecParams{ 115 | ContainerName: *container, 116 | Command: commandParts, 117 | User: *runAs, 118 | WorkingDir: *workdir, 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [1.7.0](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.6.1...v1.7.0) (2022-11-15) 4 | 5 | 6 | ### Features 7 | 8 | * support authenticating in Portainer API with X-API-Key, support Portainer versions >=2.12 ([d1b98be](https://www.github.com/devbranch-vadym/portainerssh/commit/d1b98bec3a3c4cda66adea73b315f2edb20e8dac)) 9 | * support setting working directory from CLI arguments ([305ea25](https://www.github.com/devbranch-vadym/portainerssh/commit/305ea256cdb09c8324683f887a7f89128338c57a)) 10 | 11 | 12 | ### Bug Fixes 13 | 14 | * filter out zero bytes from stdout ([bfa18d9](https://www.github.com/devbranch-vadym/portainerssh/commit/bfa18d96843847b38dc873c0aa7dcd5c88da6918)) 15 | 16 | ### [1.6.1](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.6.0...v1.6.1) (2022-10-28) 17 | 18 | 19 | ### Bug Fixes 20 | 21 | * endpoint ID hardcoded in WS URL ([53dbfd5](https://www.github.com/devbranch-vadym/portainerssh/commit/53dbfd50f74ca21749609fbabc1761749034b522)) 22 | 23 | ## [1.6.0](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.5.0...v1.6.0) (2021-12-23) 24 | 25 | 26 | ### Features 27 | 28 | * support returning container command exit code ([f981486](https://www.github.com/devbranch-vadym/portainerssh/commit/f981486a0763ee3fafae4785b748be50b3aed3f2)) 29 | 30 | ## [1.5.0](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.4.0...v1.5.0) (2021-09-28) 31 | 32 | 33 | ### Features 34 | 35 | * support running in non-interactive shells ([24c601c](https://www.github.com/devbranch-vadym/portainerssh/commit/24c601c67943e8fa45cbee4cefed5907a019d926)) 36 | 37 | ## [1.4.0](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.3.0...v1.4.0) (2021-09-17) 38 | 39 | 40 | ### Features 41 | 42 | * use shlex.Split to parse command as array ([f200878](https://www.github.com/devbranch-vadym/portainerssh/commit/f2008781e22e21bd1b399f0872f0960a85884f17)) 43 | 44 | ## [1.3.0](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.2.2...v1.3.0) (2021-08-01) 45 | 46 | 47 | ### Features 48 | 49 | * implement realtime terminal resize handling ([21bc1f3](https://www.github.com/devbranch-vadym/portainerssh/commit/21bc1f32f69f50ec04ba72fd07129742e42f1149)) 50 | 51 | ### [1.2.2](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.2.1...v1.2.2) (2021-07-30) 52 | 53 | 54 | ### Bug Fixes 55 | 56 | * handle unexpected EOF error when websocket is being closed by Portainer ([bd3a20c](https://www.github.com/devbranch-vadym/portainerssh/commit/bd3a20ca7ef740cbd9b97f5aa7c691aadc0da450)) 57 | 58 | ### [1.2.1](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.2.0...v1.2.1) (2021-07-30) 59 | 60 | 61 | ### Bug Fixes 62 | 63 | * trigger release build ([548f170](https://www.github.com/devbranch-vadym/portainerssh/commit/548f170ca8293a712a1aee6ee6fc426c46752860)) 64 | 65 | ## [1.2.0](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.1.0...v1.2.0) (2021-07-29) 66 | 67 | 68 | ### Features 69 | 70 | * implement running commands as a different user ([cb271eb](https://www.github.com/devbranch-vadym/portainerssh/commit/cb271ebd85f6a017f7f4cf033e753a033c7ff204)) 71 | 72 | ## [1.1.0](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.0.2...v1.1.0) (2021-07-29) 73 | 74 | 75 | ### Features 76 | 77 | * implement matching container names with wildcards ([c759db0](https://www.github.com/devbranch-vadym/portainerssh/commit/c759db0ec3e70d98d18389ca4e381c1b6e85162f)) 78 | * initial support for terminal resizing ([e236a35](https://www.github.com/devbranch-vadym/portainerssh/commit/e236a35c623fb7d036ad8e60e26adbeb13f6e9d1)) 79 | 80 | ### [1.0.2](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.0.1...v1.0.2) (2021-07-29) 81 | 82 | 83 | ### Bug Fixes 84 | 85 | * **ci:** fix release builds path ([9a4d99b](https://www.github.com/devbranch-vadym/portainerssh/commit/9a4d99bbc88b59d1b732448d3fd98865ffb045ab)) 86 | 87 | ### [1.0.1](https://www.github.com/devbranch-vadym/portainerssh/compare/v1.0.0...v1.0.1) (2021-07-28) 88 | 89 | 90 | ### Bug Fixes 91 | 92 | * force rebuild release ([e80d8b2](https://www.github.com/devbranch-vadym/portainerssh/commit/e80d8b2f4973dd5e8f8ded846731270d7492824c)) 93 | 94 | ## [1.0.0](https://www.github.com/devbranch-vadym/portainerssh/compare/v0.0.2...v1.0.0) (2021-07-28) 95 | 96 | 97 | ### ⚠ BREAKING CHANGES 98 | 99 | * Portainer has endpoints and it's a different thing 100 | 101 | ### Features 102 | 103 | * add --command flag ([ffc5444](https://www.github.com/devbranch-vadym/portainerssh/commit/ffc5444b13d80f480d87acfbfa8c8b12aa2091e7)) 104 | * introduce Portainer endpoints support ([1252a38](https://www.github.com/devbranch-vadym/portainerssh/commit/1252a3810be7686ec75e23d38b8d020c658eb79b)) 105 | 106 | 107 | ### Code Refactoring 108 | 109 | * rename existing usages of 'endpoint' with 'api url' since ([6549f13](https://www.github.com/devbranch-vadym/portainerssh/commit/6549f13b22f036094849fc71c48d5b5bb962832f)) 110 | -------------------------------------------------------------------------------- /pkg/portainer/api.go: -------------------------------------------------------------------------------- 1 | package portainer 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "os" 10 | "strconv" 11 | "strings" 12 | 13 | "github.com/gorilla/websocket" 14 | "github.com/minio/pkg/wildcard" 15 | ) 16 | 17 | // API handles remote API calls to Portainer. 18 | type API struct { 19 | ApiUrl string 20 | Endpoint int 21 | User string 22 | Password string 23 | Jwt string 24 | ApiKey string 25 | } 26 | 27 | // ContainerExecParams contains details required for connecting to a specific container. 28 | type ContainerExecParams struct { 29 | ContainerName string 30 | Command []string 31 | User string 32 | WorkingDir string 33 | } 34 | 35 | // ShellSession contains details about remote shell connected via WebSocket. 36 | type ShellSession struct { 37 | InstanceId string 38 | WsUrl string 39 | PortainerApi *API 40 | ShellConnection *websocket.Conn 41 | } 42 | 43 | func (r *API) formatHttpApiUrl() string { 44 | if r.ApiUrl[len(r.ApiUrl)-1:len(r.ApiUrl)] == "/" { 45 | return r.ApiUrl[0 : len(r.ApiUrl)-1] 46 | } 47 | return r.ApiUrl 48 | } 49 | 50 | func (r *API) formatWsApiUrl() string { 51 | return "ws" + strings.TrimPrefix(r.formatHttpApiUrl(), "http") 52 | } 53 | 54 | func (r *API) makeObjReq(req *http.Request, useAuth bool) (map[string]interface{}, error) { 55 | body, err := r.makeReq(req, useAuth) 56 | if err != nil { 57 | return nil, err 58 | } 59 | 60 | var apiResp map[string]interface{} 61 | if err = json.Unmarshal(body, &apiResp); err != nil { 62 | return nil, err 63 | } 64 | return apiResp, nil 65 | } 66 | 67 | func (r *API) makeArrReq(req *http.Request, useAuth bool) ([]map[string]interface{}, error) { 68 | body, err := r.makeReq(req, useAuth) 69 | if err != nil { 70 | return nil, err 71 | } 72 | 73 | var apiResp []map[string]interface{} 74 | if err = json.Unmarshal(body, &apiResp); err != nil { 75 | return nil, err 76 | } 77 | return apiResp, nil 78 | } 79 | 80 | func (r *API) makeReq(req *http.Request, useAuth bool) ([]byte, error) { 81 | req.Header.Add("Accept", "application/json") 82 | req.Header.Add("Content-Type", "application/json") 83 | if useAuth { 84 | if r.ApiKey != "" { 85 | req.Header.Add("X-API-Key", r.ApiKey) 86 | } else { 87 | jwt, err := r.getJwt() 88 | if err != nil { 89 | return nil, err 90 | } 91 | req.Header.Add("Authorization", "Bearer "+jwt) 92 | } 93 | } 94 | 95 | cli := http.Client{} 96 | resp, err := cli.Do(req) 97 | if err != nil { 98 | return nil, err 99 | } 100 | 101 | body, err := io.ReadAll(resp.Body) 102 | if err != nil { 103 | return nil, err 104 | } 105 | resp.Body.Close() 106 | 107 | return body, nil 108 | } 109 | 110 | func (r *API) getJwt() (string, error) { 111 | if r.Jwt == "" { 112 | if r.User == "" || r.Password == "" { 113 | fmt.Println("Both username and password should be provided for JWT auth.") 114 | os.Exit(1) 115 | } 116 | 117 | fmt.Println("Retrieving access token") 118 | jsonBodyData := map[string]interface{}{ 119 | "username": r.User, 120 | "password": r.Password, 121 | } 122 | body, err := json.Marshal(jsonBodyData) 123 | if err != nil { 124 | return "", err 125 | } 126 | req, _ := http.NewRequest("POST", r.formatHttpApiUrl()+"/auth", bytes.NewReader(body)) 127 | 128 | resp, err := r.makeObjReq(req, false) 129 | if err != nil { 130 | return "", err 131 | } 132 | 133 | r.Jwt = resp["jwt"].(string) 134 | } 135 | 136 | return r.Jwt, nil 137 | } 138 | 139 | func (r *API) getContainerId(params *ContainerExecParams) string { 140 | req, _ := http.NewRequest("GET", r.formatHttpApiUrl()+"/endpoints/"+strconv.Itoa(r.Endpoint)+"/docker/containers/json", nil) 141 | resp, err := r.makeArrReq(req, true) 142 | if err != nil { 143 | fmt.Println("Failed to communicate with Portainer API: " + err.Error()) 144 | os.Exit(1) 145 | } 146 | 147 | var data []map[string]interface{} 148 | for _, row := range resp { 149 | if wildcard.Match( 150 | strings.Replace(params.ContainerName, "%", "*", -1), 151 | strings.TrimLeft(row["Names"].([]interface{})[0].(string), "/"), 152 | ) { 153 | data = append(data, row) 154 | } 155 | } 156 | 157 | var choice = 1 158 | if len(data) == 0 { 159 | fmt.Println("Container " + params.ContainerName + " not existed in system, not running, or you don't have access permissions.") 160 | os.Exit(1) 161 | } 162 | if len(data) > 1 { 163 | fmt.Println("We found more than one containers in system:") 164 | for i, ctn := range data { 165 | fmt.Println(fmt.Sprintf("[%d] Container: %s, ID %s", i+1, ctn["Names"].([]interface{})[0].(string), ctn["Id"].(string))) 166 | } 167 | fmt.Println("--------------------------------------------") 168 | fmt.Print("Which one you want to connect: ") 169 | fmt.Scan(&choice) 170 | } 171 | ctn := data[choice-1] 172 | fmt.Println(fmt.Sprintf("Target Container: %s, ID %s", ctn["Names"].([]interface{})[0].(string), ctn["Id"].(string))) 173 | return ctn["Id"].(string) 174 | } 175 | 176 | func (r *API) spawnExecInstance(containerId string, params *ContainerExecParams) (string, error) { 177 | jsonBodyData := map[string]interface{}{ 178 | "AttachStdin": true, 179 | "AttachStdout": true, 180 | "AttachStderr": true, 181 | "Cmd": params.Command, 182 | "Tty": true, 183 | "id": containerId, 184 | } 185 | if params.User != "" { 186 | jsonBodyData["User"] = params.User 187 | } 188 | if params.WorkingDir != "" { 189 | jsonBodyData["WorkingDir"] = params.WorkingDir 190 | } 191 | body, err := json.Marshal(jsonBodyData) 192 | if err != nil { 193 | return "", err 194 | } 195 | req, _ := http.NewRequest("POST", r.formatHttpApiUrl()+"/endpoints/"+strconv.Itoa(r.Endpoint)+"/docker/containers/"+containerId+"/exec", bytes.NewReader(body)) 196 | resp, err := r.makeObjReq(req, true) 197 | 198 | if err != nil { 199 | return "", err 200 | } 201 | 202 | return resp["Id"].(string), nil 203 | } 204 | 205 | // GetExecSessionExitCode retrieves exec instance exit code. 206 | func (r *API) GetExecSessionExitCode(execInstanceId string) (int, error) { 207 | req, _ := http.NewRequest("GET", r.formatHttpApiUrl()+"/endpoints/"+strconv.Itoa(r.Endpoint)+"/docker/exec/"+execInstanceId+"/json", bytes.NewReader(nil)) 208 | resp, err := r.makeObjReq(req, true) 209 | 210 | if err != nil { 211 | return 0, err 212 | } 213 | 214 | return int(resp["ExitCode"].(float64)), nil 215 | } 216 | 217 | func (r *API) getWsUrl(execInstanceId string, endpointId int) string { 218 | // Newer versions of Portainer uses headers to pass authentication parameters. 219 | if r.ApiKey != "" { 220 | // The token parameter is not used by Portainer, but it is still required. 221 | return r.formatWsApiUrl() + "/websocket/exec?token=&endpointId=" + strconv.Itoa(endpointId) + "&id=" + execInstanceId 222 | } 223 | 224 | // Older versions uses token query parameter to pass in the jwt token. 225 | jwt, _ := r.getJwt() 226 | return r.formatWsApiUrl() + "/websocket/exec?token=" + jwt + "&endpointId=" + strconv.Itoa(endpointId) + "&id=" + execInstanceId 227 | } 228 | 229 | func (r *API) getWSConn(wsUrl string) *websocket.Conn { 230 | apiUrl := r.formatHttpApiUrl() 231 | header := http.Header{} 232 | header.Add("Origin", apiUrl) 233 | 234 | // Use API key if available, otherwise fall back to JWT. 235 | if r.ApiKey != "" { 236 | header.Add("X-API-Key", r.ApiKey) 237 | } else { 238 | jwt, err := r.getJwt() 239 | if err != nil { 240 | fmt.Println("Failed to communicate with Portainer API: " + err.Error()) 241 | os.Exit(1) 242 | } 243 | header.Add("Authorization", "Bearer "+jwt) 244 | } 245 | 246 | conn, _, err := websocket.DefaultDialer.Dial(wsUrl, header) 247 | if err != nil { 248 | fmt.Println("We couldn't connect to this container: ", err.Error()) 249 | os.Exit(1) 250 | } 251 | return conn 252 | } 253 | 254 | // GetContainerConn finds a container to connect, executes a command in it and returns spawned websocket connection. 255 | func (r *API) GetContainerConn(params *ContainerExecParams) ShellSession { 256 | fmt.Println("Searching for container " + params.ContainerName) 257 | containerId := r.getContainerId(params) 258 | execInstanceId, err := r.spawnExecInstance(containerId, params) 259 | if err != nil { 260 | fmt.Println("Failed to run exec on container: ", err.Error()) 261 | os.Exit(1) 262 | } 263 | 264 | wsurl := r.getWsUrl(execInstanceId, r.Endpoint) 265 | resize, _, _ := r.handleTerminalResize(execInstanceId) 266 | 267 | fmt.Println("Connecting to a shell ...") 268 | conn := r.getWSConn(wsurl) 269 | 270 | // Trigger terminal resize after connection is established. 271 | resize <- TriggerResize{} 272 | 273 | return ShellSession{ 274 | InstanceId: execInstanceId, 275 | WsUrl: wsurl, 276 | PortainerApi: r, 277 | ShellConnection: conn, 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 FANG LI, Funplus 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------