Compare commits

..

2 Commits

Author SHA1 Message Date
Søren L. Hansen
1729ed42c1 Remove a bunch of superfluous stuff 2022-02-28 17:02:44 -08:00
Søren L. Hansen
ac61302d18 Retract v2 2022-02-28 16:52:10 -08:00
86 changed files with 38 additions and 13820 deletions

View File

@ -1,528 +0,0 @@
{
"projectName": "gotty",
"projectOwner": "sorenisanerd",
"repoType": "github",
"repoHost": "https://github.com",
"files": [
"README.md"
],
"imageSize": 100,
"commit": true,
"commitConvention": "none",
"contributors": [
{
"login": "yudai",
"name": "Iwasaki Yudai",
"avatar_url": "https://avatars.githubusercontent.com/u/33192?v=4",
"profile": "https://yudai.arielworks.com/",
"contributions": [
"code"
]
},
{
"login": "sorenisanerd",
"name": "Soren L. Hansen",
"avatar_url": "https://avatars.githubusercontent.com/u/160090?v=4",
"profile": "http://linux2go.dk/",
"contributions": [
"bug"
]
},
{
"login": "uovobw",
"name": "Andrea Lusuardi",
"avatar_url": "https://avatars.githubusercontent.com/u/1194751?v=4",
"profile": "https://github.com/uovobw",
"contributions": [
"code"
]
},
{
"login": "moul",
"name": "Manfred Touron",
"avatar_url": "https://avatars.githubusercontent.com/u/94029?v=4",
"profile": "https://github.com/moul",
"contributions": [
"code"
]
},
{
"login": "svanellewee",
"name": "Stephan",
"avatar_url": "https://avatars.githubusercontent.com/u/1567439?v=4",
"profile": "https://github.com/svanellewee",
"contributions": [
"code"
]
},
{
"login": "QuentinPerez",
"name": "Quentin Perez",
"avatar_url": "https://avatars.githubusercontent.com/u/3081204?v=4",
"profile": "https://fr.linkedin.com/in/quentinperez",
"contributions": [
"code"
]
},
{
"login": "jizhilong",
"name": "jzl",
"avatar_url": "https://avatars.githubusercontent.com/u/816618?v=4",
"profile": "https://github.com/jizhilong",
"contributions": [
"code"
]
},
{
"login": "fazalmajid",
"name": "Fazal Majid",
"avatar_url": "https://avatars.githubusercontent.com/u/331198?v=4",
"profile": "https://majid.info/",
"contributions": [
"code"
]
},
{
"login": "Immortalin",
"name": "Immortalin",
"avatar_url": "https://avatars.githubusercontent.com/u/7126128?v=4",
"profile": "https://narrationbox.com/",
"contributions": [
"code"
]
},
{
"login": "freakhill",
"name": "freakhill",
"avatar_url": "https://avatars.githubusercontent.com/u/916582?v=4",
"profile": "https://github.com/freakhill",
"contributions": [
"code"
]
},
{
"login": "0xflotus",
"name": "0xflotus",
"avatar_url": "https://avatars.githubusercontent.com/u/26602940?v=4",
"profile": "https://github.com/0xflotus",
"contributions": [
"code"
]
},
{
"login": "skeltoac",
"name": "Andy Skelton",
"avatar_url": "https://avatars.githubusercontent.com/u/52292?v=4",
"profile": "https://andy.blog/",
"contributions": [
"code"
]
},
{
"login": "artdevjs",
"name": "Artem Medvedev",
"avatar_url": "https://avatars.githubusercontent.com/u/7567983?v=4",
"profile": "https://twitter.com/artdevjs",
"contributions": [
"code"
]
},
{
"login": "blakejennings",
"name": "Blake Jennings",
"avatar_url": "https://avatars.githubusercontent.com/u/1976331?v=4",
"profile": "https://github.com/blakejennings",
"contributions": [
"code"
]
},
{
"login": "jensenbox",
"name": "Christian Jensen",
"avatar_url": "https://avatars.githubusercontent.com/u/189265?v=4",
"profile": "https://github.com/jensenbox",
"contributions": [
"code"
]
},
{
"login": "TechWilk",
"name": "Christopher Wilkinson",
"avatar_url": "https://avatars.githubusercontent.com/u/9367803?v=4",
"profile": "https://wilk.tech/",
"contributions": [
"code"
]
},
{
"login": "RealCyGuy",
"name": "Cyrus",
"avatar_url": "https://avatars.githubusercontent.com/u/54488650?v=4",
"profile": "https://github.com/RealCyGuy",
"contributions": [
"code"
]
},
{
"login": "dehorsley",
"name": "David Horsley",
"avatar_url": "https://avatars.githubusercontent.com/u/3401668?v=4",
"profile": "https://github.com/dehorsley",
"contributions": [
"code"
]
},
{
"login": "Jason-Cooke",
"name": "Jason Cooke",
"avatar_url": "https://avatars.githubusercontent.com/u/5185660?v=4",
"profile": "https://jasoncooke.dev/",
"contributions": [
"code"
]
},
{
"login": "DenKoren",
"name": "Denis Korenevskiy",
"avatar_url": "https://avatars.githubusercontent.com/u/3419381?v=4",
"profile": "https://github.com/DenKoren",
"contributions": [
"code"
]
},
{
"login": "stucchimax",
"name": "Massimiliano Stucchi",
"avatar_url": "https://avatars.githubusercontent.com/u/1331438?v=4",
"profile": "https://www.stucchi.ch/",
"contributions": [
"code"
]
},
{
"login": "Felixoid",
"name": "Mikhail f. Shiryaev",
"avatar_url": "https://avatars.githubusercontent.com/u/3025537?v=4",
"profile": "https://www.linkedin.com/in/felixoid/",
"contributions": [
"code"
]
},
{
"login": "guywithnose",
"name": "Robert Bittle",
"avatar_url": "https://avatars.githubusercontent.com/u/1059169?v=4",
"profile": "https://github.com/guywithnose",
"contributions": [
"code"
]
},
{
"login": "sehaas",
"name": "sebastian haas",
"avatar_url": "https://avatars.githubusercontent.com/u/283482?v=4",
"profile": "https://deebas.com/",
"contributions": [
"code"
]
},
{
"login": "shoz",
"name": "shoji",
"avatar_url": "https://avatars.githubusercontent.com/u/225194?v=4",
"profile": "https://github.com/shoz",
"contributions": [
"code"
]
},
{
"login": "tsl0922",
"name": "Shuanglei Tao",
"avatar_url": "https://avatars.githubusercontent.com/u/1680515?v=4",
"profile": "https://github.com/tsl0922",
"contributions": [
"code"
]
},
{
"login": "gitter-badger",
"name": "The Gitter Badger",
"avatar_url": "https://avatars.githubusercontent.com/u/8518239?v=4",
"profile": "https://gitter.im/",
"contributions": [
"code"
]
},
{
"login": "xinsnake",
"name": "Jacob Zhou",
"avatar_url": "https://avatars.githubusercontent.com/u/1287677?v=4",
"profile": "https://github.com/xinsnake",
"contributions": [
"code"
]
},
{
"login": "zyfdegh",
"name": "zyfdegh",
"avatar_url": "https://avatars.githubusercontent.com/u/7880217?v=4",
"profile": "https://github.com/zyfdegh",
"contributions": [
"code"
]
},
{
"login": "fredster33",
"name": "fredster33",
"avatar_url": "https://avatars.githubusercontent.com/u/64927044?v=4",
"profile": "https://github.com/fredster33",
"contributions": [
"code"
]
},
{
"login": "mattn",
"name": "mattn",
"avatar_url": "https://avatars.githubusercontent.com/u/10111?v=4",
"profile": "https://mattn.kaoriya.net/",
"contributions": [
"code"
]
},
{
"login": "shingt",
"name": "Shinichi Goto",
"avatar_url": "https://avatars.githubusercontent.com/u/1391330?v=4",
"profile": "https://www.shingt.com/",
"contributions": [
"code"
]
},
{
"login": "ygit",
"name": "ygit",
"avatar_url": "https://avatars.githubusercontent.com/u/8512357?v=4",
"profile": "https://twitter.com/_yogeshsingh",
"contributions": [
"code"
]
},
{
"login": "nephaste",
"name": "Stéphane",
"avatar_url": "https://avatars.githubusercontent.com/u/3392684?v=4",
"profile": "http://forum.cachem.fr/viewforum.php?f=21",
"contributions": [
"bug"
]
},
{
"login": "prusnak",
"name": "Pavol Rusnak",
"avatar_url": "https://avatars.githubusercontent.com/u/42201?v=4",
"profile": "https://rusnak.io/",
"contributions": [
"bug"
]
},
{
"login": "devanlai",
"name": "Devan Lai",
"avatar_url": "https://avatars.githubusercontent.com/u/1348448?v=4",
"profile": "https://github.com/devanlai",
"contributions": [
"code"
]
},
{
"login": "jkandasa",
"name": "Jeeva Kandasamy",
"avatar_url": "https://avatars.githubusercontent.com/u/1004403?v=4",
"profile": "https://github.com/jkandasa",
"contributions": [
"code"
]
},
{
"login": "hardliner66",
"name": "Steve Biedermann",
"avatar_url": "https://avatars.githubusercontent.com/u/2937272?v=4",
"profile": "https://twitch.tv/iamhardliner",
"contributions": [
"code"
]
},
{
"login": "xgdgsc",
"name": "xgdgsc",
"avatar_url": "https://avatars.githubusercontent.com/u/1189869?v=4",
"profile": "https://github.com/xgdgsc",
"contributions": [
"bug"
]
},
{
"login": "flechaig",
"name": "flechaig",
"avatar_url": "https://avatars.githubusercontent.com/u/10887132?v=4",
"profile": "https://github.com/flechaig",
"contributions": [
"bug"
]
},
{
"login": "Fan-SJ",
"name": "Fan-SJ",
"avatar_url": "https://avatars.githubusercontent.com/u/49977708?v=4",
"profile": "https://github.com/Fan-SJ",
"contributions": [
"bug"
]
},
{
"login": "dmartin",
"name": "Dustin Martin",
"avatar_url": "https://avatars.githubusercontent.com/u/1657652?v=4",
"profile": "https://github.com/dmartin",
"contributions": [
"bug"
]
},
{
"login": "ahmetb",
"name": "Ahmet Alp Balkan",
"avatar_url": "https://avatars.githubusercontent.com/u/159209?v=4",
"profile": "https://ahmet.dev/",
"contributions": [
"bug"
]
},
{
"login": "CoconutMacaroon",
"name": "CoconutMacaroon",
"avatar_url": "https://avatars.githubusercontent.com/u/45187468?v=4",
"profile": "https://github.com/CoconutMacaroon",
"contributions": [
"bug"
]
},
{
"login": "DannyBen",
"name": "Danny Ben Shitrit",
"avatar_url": "https://avatars.githubusercontent.com/u/2405099?v=4",
"profile": "https://github.dannyben.com/",
"contributions": [
"bug"
]
},
{
"login": "George-NG",
"name": "George-NG",
"avatar_url": "https://avatars.githubusercontent.com/u/28577165?v=4",
"profile": "https://github.com/George-NG",
"contributions": [
"bug"
]
},
{
"login": "ghthor",
"name": "Will Owens",
"avatar_url": "https://avatars.githubusercontent.com/u/160298?v=4",
"profile": "https://github.com/ghthor",
"contributions": [
"bug"
]
},
{
"login": "jpillora",
"name": "Jaime Pillora",
"avatar_url": "https://avatars.githubusercontent.com/u/633843?v=4",
"profile": "https://jpillora.com/",
"contributions": [
"bug"
]
},
{
"login": "kaisawind",
"name": "kaisawind",
"avatar_url": "https://avatars.githubusercontent.com/u/4010613?v=4",
"profile": "https://github.com/kaisawind",
"contributions": [
"bug"
]
},
{
"login": "linyinli",
"name": "linyinli",
"avatar_url": "https://avatars.githubusercontent.com/u/42955482?v=4",
"profile": "https://github.com/linyinli",
"contributions": [
"bug"
]
},
{
"login": "LucaMarconato",
"name": "LucaMarconato",
"avatar_url": "https://avatars.githubusercontent.com/u/2664412?v=4",
"profile": "https://github.com/LucaMarconato",
"contributions": [
"bug"
]
},
{
"login": "masterkain",
"name": "Kain",
"avatar_url": "https://avatars.githubusercontent.com/u/12844?v=4",
"profile": "https://audiobox.fm/",
"contributions": [
"bug"
]
},
{
"login": "Nexuist",
"name": "Andi Andreas",
"avatar_url": "https://avatars.githubusercontent.com/u/1498061?v=4",
"profile": "http://duro.me/",
"contributions": [
"bug"
]
},
{
"login": "qigj",
"name": "qigj",
"avatar_url": "https://avatars.githubusercontent.com/u/56585735?v=4",
"profile": "https://github.com/qigj",
"contributions": [
"bug"
]
},
{
"login": "shuaiyy",
"name": "shuaiyy",
"avatar_url": "https://avatars.githubusercontent.com/u/19821321?v=4",
"profile": "https://github.com/shuaiyy",
"contributions": [
"bug"
]
},
{
"login": "v20z",
"name": "v20z",
"avatar_url": "https://avatars.githubusercontent.com/u/2884824?v=4",
"profile": "https://github.com/v20z",
"contributions": [
"bug"
]
},
{
"login": "Yann-Qiu",
"name": "Yanfeng Qiu",
"avatar_url": "https://avatars.githubusercontent.com/u/56961747?v=4",
"profile": "https://github.com/Yann-Qiu",
"contributions": [
"bug"
]
}
],
"contributorsPerLine": 7
}

View File

@ -1,49 +0,0 @@
name: "Unit and Build Tests"
on:
push:
pull_request:
branches: [ master ]
jobs:
bundle-up-to-date:
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-go@v3
with:
go-version: 1.19
- uses: actions/setup-node@v3
with:
node-version: 16
- run: "make clean"
- run: "make assets"
- name: "Make sure gotty.js bundle is up-to-date"
run: "diffsize=$(git diff bindata/static/js/gotty.js | wc -l); test $diffsize == 0"
cross-compile-test:
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: "Build & test"
run: "make tools test cross_compile"
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: binaries
path: builds/pkg/*/gotty

View File

@ -1,42 +0,0 @@
---
name: "pre-release"
on: [push]
env:
IMAGE_NAME: ${{ github.repository }}
jobs:
pre-release-docker:
name: "Pre Release Docker"
runs-on: "ubuntu-latest"
steps:
-
name: Docker meta
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=sha,format=long
type=sha
type=semver,pattern=v{{major}}.{{minor}}.{{patch}}
type=semver,pattern=v{{major}}.{{minor}}
type=semver,pattern=v{{major}}
type=ref,event=tag
type=ref,event=branch
- uses: docker/setup-qemu-action@v2
- uses: docker/setup-buildx-action@v2
- uses: docker/login-action@v2
with:
username: "${{ secrets.DOCKER_HUB_USER }}"
password: "${{ secrets.DOCKER_HUB_TOKEN }}"
- name: "Build and push docker image"
uses: docker/build-push-action@v4
with:
platforms: linux/amd64,linux/arm/v7,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

View File

@ -1,30 +0,0 @@
name: "Quick build test"
on:
push:
pull_request:
branches: [ master ]
jobs:
quick-build-test:
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: "Build"
run: "touch bindata/* bindata/*/* ; make"
- name: Upload linux/amd64 artifact
uses: actions/upload-artifact@v3
with:
name: gotty-linux-amd64
path: gotty

View File

@ -1,40 +0,0 @@
---
name: "tagged-release"
on:
push:
tags:
- "v*"
jobs:
tagged-release:
name: "Tagged Release"
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: "Build & test"
run: "make tools test release-artifacts"
- name: Upload build artifacts
uses: actions/upload-artifact@v3
with:
name: binaries
path: builds/pkg/*/gotty
- uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
prerelease: false
draft: true
files: |
LICENSE
builds/dist/*

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
gotty
bindata
builds
js/dist
js/node_modules/*

View File

@ -1,5 +0,0 @@
{
"recommendations": [
"amodio.tsl-problem-matcher"
]
}

27
.vscode/launch.json vendored
View File

@ -1,27 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch GoTTY",
"type": "go",
"buildFlags": "-tags=dev",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}",
"args": ["-a", "127.0.0.1", "-w", "${env:SHELL}"]
},
{
"name": "Launch Chrome",
"type": "chrome",
"url": "http://127.0.0.1:8080",
"webRoot": "${workspaceFolder}/js",
"outFiles": [
"${workspaceFolder}/**/*.js",
"!**/node_modules/**"
],
},
]
}

16
.vscode/tasks.json vendored
View File

@ -1,16 +0,0 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "webpack watch",
"type": "shell",
"command": "cd ${workspaceFolder}/js;DEV=1 npx webpack --watch --mode=development",
"problemMatcher": [
"$ts-webpack-watch"
],
"isBackground": true
}
]
}

View File

@ -1,44 +0,0 @@
# How to contribute
GoTTY is MIT licensed and accepts contributions via GitHub pull requests. We also accepts feature requests on GitHub issues.
## Reporting a bug
Reporting a bug is always welcome and one of the best ways to contribute. A good bug report helps the developers to improve the product much easier. We therefore would like to ask you to fill out the quesions on the issue template as much as possible. That helps us to figure out what's happening and discover the root cause.
## Requesting a new feature
When you find that GoTTY cannot fullfill your requirements because of lack of ability, you may want to open a new feature request. In that case, please file a new issue with your usecase and requirements.
## Opening a pull request
### Code Style
Please run `go fmt` on your Go code and make sure that your commits are organized for each logical change and your commit messages are in proper format (see below).
[Go's official code style guide](https://github.com/golang/go/wiki/CodeReviewComments) is also helpful.
### Format of the commit message
When you write a commit message, we recommend include following information to make review easier and keep the history cleaerer.
* What is the change
* The reason for the change
The following is an example:
```
Add something new to existing package
Since the existing function lacks that mechanism for some purpose,
this commit adds a new structure to provide it.
```
When your pull request is to add a new feature, we recommend add an actual usecase so that we can discuss the best way to achive your requirement. Opening a proposal issue in advance is another good way to start discussion of new features.
## Contact
If you have a trivial question about GoTTY for a bug or new feature, you can contact @sorenisanerd on Twitter (unfortunately, I cannot provide support on GoTTY though).

View File

@ -1,20 +0,0 @@
FROM node:16 as js-build
WORKDIR /gotty
COPY js /gotty/js
COPY Makefile /gotty/
RUN make bindata/static/js/gotty.js.map
FROM golang:1.20 as go-build
WORKDIR /gotty
COPY . /gotty
COPY --from=js-build /gotty/js/node_modules /gotty/js/node_modules
COPY --from=js-build /gotty/bindata/static/js /gotty/bindata/static/js
RUN CGO_ENABLED=0 make
FROM alpine:latest
RUN apk update && \
apk upgrade && \
apk --no-cache add ca-certificates bash
WORKDIR /root
COPY --from=go-build /gotty/gotty /usr/bin/
CMD ["gotty", "-w", "bash"]

View File

@ -1,7 +1,7 @@
The MIT License (MIT)
Copyright (c) 2015-2017 Iwasaki Yudai
Copyright (c) 2021-2022 Søren L. Hansen
Copyright (c) 2021 Søren L. Hansen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,92 +0,0 @@
OUTPUT_DIR = ./builds
GIT_COMMIT = `git rev-parse HEAD | cut -c1-7`
VERSION = $(shell git describe --tags)
BUILD_OPTIONS = -ldflags "-X main.Version=$(VERSION)"
ifeq ($(DEV), 1)
BUILD_OPTIONS += -tags dev
WEBPACK_MODE = development
else
WEBPACK_MODE = production
endif
export CGO_ENABLED=0
gotty: main.go assets server/*.go webtty/*.go backend/*.go Makefile
go build ${BUILD_OPTIONS}
docker:
docker build . -t gotty-bash:$(VERSION)
.PHONY: all docker assets
assets: bindata/static/js/gotty.js.map \
bindata/static/js/gotty.js \
bindata/static/index.html \
bindata/static/icon.svg \
bindata/static/favicon.ico \
bindata/static/css/index.css \
bindata/static/css/xterm.css \
bindata/static/css/xterm_customize.css \
bindata/static/manifest.json \
bindata/static/icon_192.png
all: gotty
bindata/static bindata/static/css bindata/static/js:
mkdir -p $@
bindata/static/%: resources/% | bindata/static/css
cp "$<" "$@"
bindata/static/css/%.css: resources/%.css | bindata/static
cp "$<" "$@"
bindata/static/css/xterm.css: js/node_modules/xterm/css/xterm.css | bindata/static
cp "$<" "$@"
js/node_modules/xterm/dist/xterm.css:
cd js && \
npm install
bindata/static/js/gotty.js.map bindata/static/js/gotty.js: js/src/* | js/node_modules/webpack
cd js && \
npx webpack --mode=$(WEBPACK_MODE)
js/node_modules/webpack:
cd js && \
npm install
README-options:
./gotty --help | sed '1,/GLOBAL OPTIONS/ d' > options.txt.tmp
sed -f README.md.sed -i README.md
rm options.txt.tmp
tools:
go install github.com/mitchellh/gox@latest
go install github.com/tcnksm/ghr@latest
test:
if [ `go fmt $(go list ./... | grep -v /vendor/) | wc -l` -gt 0 ]; then echo "go fmt error"; exit 1; fi
go test ./...
cross_compile:
GOARM=5 gox -os="darwin linux freebsd netbsd openbsd solaris" -arch="386 amd64 arm arm64" -osarch="!darwin/386" -osarch="!darwin/arm" $(BUILD_OPTIONS) -output "${OUTPUT_DIR}/pkg/{{.OS}}_{{.Arch}}/{{.Dir}}"
targz:
mkdir -p ${OUTPUT_DIR}/dist
cd ${OUTPUT_DIR}/pkg/; for osarch in *; do (cd $$osarch; tar zcvf ../../dist/gotty_${VERSION}_$$osarch.tar.gz ./*); done;
shasums:
cd ${OUTPUT_DIR}/dist; sha256sum * > ./SHA256SUMS
release-artifacts: gotty cross_compile targz shasums
release:
ghr -draft ${VERSION} ${OUTPUT_DIR}/dist # -c ${GIT_COMMIT} --delete --prerelease -u sorenisanerd -r gotty ${VERSION}
clean:
rm -fr gotty builds js/dist bindata/static js/node_modules
addcontributors:
gh issue list -s all -L 1000 --json author -t "$$(echo '{{ range . }}{{ .author.login }}\n{{ end }}')" | sort | uniq | xargs -Ifoo all-contributors add foo bug --commitTemplate '<%= (newContributor ? "Add" : "Update") %> @<%= username %> as a contributor'
gh pr list -s all -L 1000 --json author -t "$$(echo '{{ range . }}{{ .author.login }}\n{{ end }}')" | sort | uniq | xargs -Ifoo all-contributors add foo code --commitTemplate '<%= (newContributor ? "Add" : "Update") %> @<%= username %> as a contributor'

102
NEWS.md
View File

@ -1,102 +0,0 @@
## 1.5.0 (2022-09-01)
* Add @ahmetb as a contributor ([276767a](https://github.com/sorenisanerd/gotty/commit/276767a))
* Add @CoconutMacaroon as a contributor ([74c1318](https://github.com/sorenisanerd/gotty/commit/74c1318))
* Add @DannyBen as a contributor ([fcfa161](https://github.com/sorenisanerd/gotty/commit/fcfa161))
* Add @dmartin as a contributor ([6b2ae89](https://github.com/sorenisanerd/gotty/commit/6b2ae89))
* Add @Fan-SJ as a contributor ([c2428c8](https://github.com/sorenisanerd/gotty/commit/c2428c8))
* Add @flechaig as a contributor ([2c4004d](https://github.com/sorenisanerd/gotty/commit/2c4004d))
* Add @George-NG as a contributor ([270ae45](https://github.com/sorenisanerd/gotty/commit/270ae45))
* Add @ghthor as a contributor ([1a6bccd](https://github.com/sorenisanerd/gotty/commit/1a6bccd))
* Add @jpillora as a contributor ([f52fbd7](https://github.com/sorenisanerd/gotty/commit/f52fbd7))
* Add @kaisawind as a contributor ([accff3a](https://github.com/sorenisanerd/gotty/commit/accff3a))
* Add @linyinli as a contributor ([8014af3](https://github.com/sorenisanerd/gotty/commit/8014af3))
* Add @LucaMarconato as a contributor ([3bd9836](https://github.com/sorenisanerd/gotty/commit/3bd9836))
* Add @masterkain as a contributor ([369e2f7](https://github.com/sorenisanerd/gotty/commit/369e2f7))
* Add @Nexuist as a contributor ([ca691bc](https://github.com/sorenisanerd/gotty/commit/ca691bc))
* Add @qigj as a contributor ([5a052e7](https://github.com/sorenisanerd/gotty/commit/5a052e7))
* Add @shuaiyy as a contributor ([95e1bbd](https://github.com/sorenisanerd/gotty/commit/95e1bbd))
* Add @v20z as a contributor ([d594bef](https://github.com/sorenisanerd/gotty/commit/d594bef))
* Add @xgdgsc as a contributor ([c197990](https://github.com/sorenisanerd/gotty/commit/c197990))
* Add @Yann-Qiu as a contributor ([7b994ec](https://github.com/sorenisanerd/gotty/commit/7b994ec))
* Update @flechaig as a contributor ([9877e9c](https://github.com/sorenisanerd/gotty/commit/9877e9c))
* Update @flechaig as a contributor ([e03ea9c](https://github.com/sorenisanerd/gotty/commit/e03ea9c))
* Update @prusnak as a contributor ([3c45888](https://github.com/sorenisanerd/gotty/commit/3c45888))
* Update @prusnak as a contributor ([8d7f5fc](https://github.com/sorenisanerd/gotty/commit/8d7f5fc))
* Update @sorenisanerd as a contributor ([34f516b](https://github.com/sorenisanerd/gotty/commit/34f516b))
* Update @sorenisanerd as a contributor ([89a04d1](https://github.com/sorenisanerd/gotty/commit/89a04d1))
* Update @xgdgsc as a contributor ([b3c5d03](https://github.com/sorenisanerd/gotty/commit/b3c5d03))
* Update @xgdgsc as a contributor ([09f7e95](https://github.com/sorenisanerd/gotty/commit/09f7e95))
* Add make target to add contributors ([1bbfd5e](https://github.com/sorenisanerd/gotty/commit/1bbfd5e))
* Add missing import "strings" ([d0e3ffb](https://github.com/sorenisanerd/gotty/commit/d0e3ffb))
* add slash ([7706bf2](https://github.com/sorenisanerd/gotty/commit/7706bf2))
* Always disable CGO ([7a96f37](https://github.com/sorenisanerd/gotty/commit/7a96f37)), closes [#39](https://github.com/sorenisanerd/gotty/issues/39)
* Bump terser from 5.12.1 to 5.14.2 in /js ([3ae13e0](https://github.com/sorenisanerd/gotty/commit/3ae13e0))
* Create a release when a new tag is pushed ([d8fe975](https://github.com/sorenisanerd/gotty/commit/d8fe975))
* Ensure --quiet flag is honored ([7d431a7](https://github.com/sorenisanerd/gotty/commit/7d431a7)), closes [#45](https://github.com/sorenisanerd/gotty/issues/45)
* Refresh dependencies, drop node-sass ([94e5873](https://github.com/sorenisanerd/gotty/commit/94e5873))
* Run tests on pull requests ([316d5ff](https://github.com/sorenisanerd/gotty/commit/316d5ff))
## 1.4.0 (2022-05-30)
* Add @hardliner66 as a contributor ([1ca998e](https://github.com/sorenisanerd/gotty/commit/1ca998e))
* Add @jkandasa as a contributor ([cd23910](https://github.com/sorenisanerd/gotty/commit/cd23910))
* Add backend tests ([603c650](https://github.com/sorenisanerd/gotty/commit/603c650))
* Add generated data to git ([a9fbc07](https://github.com/sorenisanerd/gotty/commit/a9fbc07))
* add quiet flag to disable logging ([4109b11](https://github.com/sorenisanerd/gotty/commit/4109b11))
* Add references to @yudai ([bffd821](https://github.com/sorenisanerd/gotty/commit/bffd821)), closes [#8](https://github.com/sorenisanerd/gotty/issues/8)
* Add rule to build gotty.js.map ([82c3acf](https://github.com/sorenisanerd/gotty/commit/82c3acf))
* Apply font size and family in xterm ([f157dbe](https://github.com/sorenisanerd/gotty/commit/f157dbe)), closes [#21](https://github.com/sorenisanerd/gotty/issues/21)
* Avoid HTTP 401 error on manifest.json due to CORS ([817b5c8](https://github.com/sorenisanerd/gotty/commit/817b5c8))
* Bump browserslist from 4.16.4 to 4.16.6 in /js ([8deba62](https://github.com/sorenisanerd/gotty/commit/8deba62))
* Disable arg passing by default ([5c8eb10](https://github.com/sorenisanerd/gotty/commit/5c8eb10)), closes [#17](https://github.com/sorenisanerd/gotty/issues/17)
* Do not include ALL of bootstrap ([b63ea16](https://github.com/sorenisanerd/gotty/commit/b63ea16))
* Ensure defaults for booleans is set correctly ([28f8e61](https://github.com/sorenisanerd/gotty/commit/28f8e61)), closes [#16](https://github.com/sorenisanerd/gotty/issues/16)
* Fix existing tests ([d674aa1](https://github.com/sorenisanerd/gotty/commit/d674aa1)), closes [#13](https://github.com/sorenisanerd/gotty/issues/13)
* Fix warnings from Markdown linter ([aa86a34](https://github.com/sorenisanerd/gotty/commit/aa86a34))
* go fmt ([dcb153c](https://github.com/sorenisanerd/gotty/commit/dcb153c))
* Improve webtty test coverage ([f61763f](https://github.com/sorenisanerd/gotty/commit/f61763f))
* Make client request base64 encoding ([dd3603c](https://github.com/sorenisanerd/gotty/commit/dd3603c))
* Make sure we read the full message ([1eed97f](https://github.com/sorenisanerd/gotty/commit/1eed97f))
* Publish artifacts on push to master ([6c62ab7](https://github.com/sorenisanerd/gotty/commit/6c62ab7))
* Remove hterm ([163fd05](https://github.com/sorenisanerd/gotty/commit/163fd05))
* Run tests on push ([55674f1](https://github.com/sorenisanerd/gotty/commit/55674f1))
* Run tests on push to all branches ([679a324](https://github.com/sorenisanerd/gotty/commit/679a324))
* update go version in Dockerfile ([fd2fb99](https://github.com/sorenisanerd/gotty/commit/fd2fb99))
* Update js dependencies ([26fc412](https://github.com/sorenisanerd/gotty/commit/26fc412))
* Update xterm.js and other js libs ([81afdc7](https://github.com/sorenisanerd/gotty/commit/81afdc7)), closes [#18](https://github.com/sorenisanerd/gotty/issues/18)
* Use bootstrap components for up- and downloads ([7f05f2f](https://github.com/sorenisanerd/gotty/commit/7f05f2f))
* Use Go's built-in embed mechanism ([f66f0d0](https://github.com/sorenisanerd/gotty/commit/f66f0d0)), closes [#7](https://github.com/sorenisanerd/gotty/issues/7)
* feat(zmodem): Allow file uploads/downloads ([782991c](https://github.com/sorenisanerd/gotty/commit/782991c))
## v1.3.0
* Links in the tty are now clickable.
* Use WebGL for rendering by default.
* Ensure authentication (TLS or Basic auth) remain enabled even if some of the options are only given in config files Thanks, @devanlai!
* Fix typo in README.md Thanks, @prusnak!
* Add arm64/Linux build. Thanks for the suggestion, @nephaste!
## v1.2.0
* Pass BUILD\_OPTIONS to gox, too, so release artifacts have version info included.
* Update xterm.js 2.7.0 => 4.11.0
* Lots of clean up.
## v1.1.0
* Today I learned about Go's handling of versions, so re-releasing 2.1.0 as 1.1.0.
* Added path option. Thanks, @apatil!
## v2.1.0 (whoops)
* Use Go modules and update cli module import path. Thanks, @svanellewee!
* Fix typos. Thanks, @0xflotus, @RealCyGuy, @ygit, @Jason-Cooke and @fredster33!
* Fix printing of ipv6 addresses. Thanks, @Felixoid!
* Add Progressive Web App support. Thanks, @sehaas!
* Add instructions for GNU screen. Thanks, @Immortalin!
* Add Solaris support. Thanks, @fazalmajid!
* New maintainer: @sorenisanerd

277
README.md
View File

@ -1,277 +0,0 @@
# ![](https://raw.githubusercontent.com/sorenisanerd/gotty/master/resources/favicon.ico) GoTTY - Share your terminal as a web application
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-57-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
[![GitHub release](http://img.shields.io/github/release/sorenisanerd/gotty.svg?style=flat-square)][release]
[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)][license]
[![Maintainer streaming](https://twitch-status.soren.tools/sorencodes)][twitch]
[release]: https://github.com/sorenisanerd/gotty/releases
[license]: https://github.com/sorenisanerd/gotty/blob/master/LICENSE
[twitch]: https://twitch.tv/sorencodes
GoTTY is a simple command line tool that turns your CLI tools into web applications.
[Original work](https://github.com/yudai/gotty) by [Iwasaki Yudai](https://github.com/yudai). There would be no GoTTY without him. ❤️
![Screenshot](https://raw.githubusercontent.com/sorenisanerd/gotty/master/screenshot.gif)
# Installation
## From release page
You can download the latest stable binary file from the [Releases](https://github.com/sorenisanerd/gotty/releases) page. Note that the release marked `Pre-release` is built for testing purpose, which can include unstable or breaking changes. Download a release marked [Latest release](https://github.com/sorenisanerd/gotty/releases/latest) for a stable build.
(Files named with `darwin_amd64` are for Mac OS X users)
## Homebrew Installation
You can install GoTTY with [Homebrew](http://brew.sh/) as well.
```sh
$ brew install sorenisanerd/gotty/gotty
```
## `go get` Installation (Development)
If you have a Go language environment, you can install GoTTY with the `go get` command. However, this command builds a binary file from the latest master branch, which can include unstable or breaking changes. GoTTY requires go1.9 or later.
```sh
$ go get github.com/sorenisanerd/gotty
```
# Usage
```
Usage: gotty [options] <command> [<arguments...>]
```
Run `gotty` with your preferred command as its arguments (e.g. `gotty top`).
By default, GoTTY starts a web server at port 8080. Open the URL on your web browser and you can see the running command as if it were running on your terminal.
## Options
```sh
--address value, -a value IP address to listen (default: "0.0.0.0") [$GOTTY_ADDRESS]
--port value, -p value Port number to liten (default: "8080") [$GOTTY_PORT]
--path value, -m value Base path (default: "/") [$GOTTY_PATH]
--permit-write, -w Permit clients to write to the TTY (BE CAREFUL) (default: false) [$GOTTY_PERMIT_WRITE]
--credential value, -c value Credential for Basic Authentication (ex: user:pass, default disabled) [$GOTTY_CREDENTIAL]
--random-url, -r Add a random string to the URL (default: false) [$GOTTY_RANDOM_URL]
--random-url-length value Random URL length (default: 8) [$GOTTY_RANDOM_URL_LENGTH]
--tls, -t Enable TLS/SSL (default: false) [$GOTTY_TLS]
--tls-crt value TLS/SSL certificate file path (default: "~/.gotty.crt") [$GOTTY_TLS_CRT]
--tls-key value TLS/SSL key file path (default: "~/.gotty.key") [$GOTTY_TLS_KEY]
--tls-ca-crt value TLS/SSL CA certificate file for client certifications (default: "~/.gotty.ca.crt") [$GOTTY_TLS_CA_CRT]
--index value Custom index.html file [$GOTTY_INDEX]
--title-format value Title format of browser window (default: "{{ .command }}@{{ .hostname }}") [$GOTTY_TITLE_FORMAT]
--reconnect Enable reconnection (default: false) [$GOTTY_RECONNECT]
--reconnect-time value Time to reconnect (default: 10) [$GOTTY_RECONNECT_TIME]
--max-connection value Maximum connection to gotty (default: 0) [$GOTTY_MAX_CONNECTION]
--once Accept only one client and exit on disconnection (default: false) [$GOTTY_ONCE]
--timeout value Timeout seconds for waiting a client(0 to disable) (default: 0) [$GOTTY_TIMEOUT]
--permit-arguments Permit clients to send command line arguments in URL (e.g. http://example.com:8080/?arg=AAA&arg=BBB) (default: false) [$GOTTY_PERMIT_ARGUMENTS]
--width value Static width of the screen, 0(default) means dynamically resize (default: 0) [$GOTTY_WIDTH]
--height value Static height of the screen, 0(default) means dynamically resize (default: 0) [$GOTTY_HEIGHT]
--ws-origin value A regular expression that matches origin URLs to be accepted by WebSocket. No cross origin requests are acceptable by default [$GOTTY_WS_ORIGIN]
--ws-query-args value Querystring arguments to append to the websocket instantiation [$GOTTY_WS_QUERY_ARGS]
--enable-webgl Enable WebGL renderer (default: true) [$GOTTY_ENABLE_WEBGL]
--close-signal value Signal sent to the command process when gotty close it (default: SIGHUP) (default: 1) [$GOTTY_CLOSE_SIGNAL]
--close-timeout value Time in seconds to force kill process after client is disconnected (default: -1) (default: -1) [$GOTTY_CLOSE_TIMEOUT]
--config value Config file path (default: "~/.gotty") [$GOTTY_CONFIG]
--help, -h show help (default: false)
--version, -v print the version (default: false)
```
### Config File
You can customize default options and your terminal by providing a config file to the `gotty` command. GoTTY loads a profile file at `~/.gotty` by default when it exists.
```
// Listen at port 9000 by default
port = "9000"
// Enable TSL/SSL by default
enable_tls = true
```
See the [`.gotty`](https://github.com/sorenisanerd/gotty/blob/master/.gotty) file in this repository for the list of configuration options.
### Security Options
By default, GoTTY doesn't allow clients to send any keystrokes or commands except terminal window resizing. When you want to permit clients to write input to the TTY, add the `-w` option. However, accepting input from remote clients is dangerous for most commands. When you need interaction with the TTY for some reasons, consider starting GoTTY with tmux or GNU Screen and run your command on it (see "Sharing with Multiple Clients" section for detail).
To restrict client access, you can use the `-c` option to enable the basic authentication. With this option, clients need to input the specified username and password to connect to the GoTTY server. Note that the credentials will be transmitted between the server and clients in plain text. For more strict authentication, consider the SSL/TLS client certificate authentication described below.
The `-r` option is a little bit more casual way to restrict access. With this option, GoTTY generates a random URL so that only people who know the URL can get access to the server.
All traffic between the server and clients are NOT encrypted by default. When you send secret information through GoTTY, we strongly recommend you use the `-t` option which enables TLS/SSL on the session. By default, GoTTY loads the crt and key files placed at `~/.gotty.crt` and `~/.gotty.key`. You can overwrite these file paths with the `--tls-crt` and `--tls-key` options. When you need to generate a self-signed certification file, you can use the `openssl` command.
```sh
openssl req -x509 -nodes -days 9999 -newkey rsa:2048 -keyout ~/.gotty.key -out ~/.gotty.crt
```
(NOTE: For Safari uses, see [how to enable self-signed certificates for WebSockets](http://blog.marcon.me/post/24874118286/secure-websockets-safari) when use self-signed certificates)
For additional security, you can use the SSL/TLS client certificate authentication by providing a CA certificate file to the `--tls-ca-crt` option (this option requires the `-t` or `--tls` to be set). This option requires all clients to send valid client certificates that are signed by the specified certification authority.
## Sharing with Multiple Clients
GoTTY starts a new process with the given command when a new client connects to the server. This means users cannot share a single terminal with others by default. However, you can use terminal multiplexers for sharing a single process with multiple clients.
### Screen
After installing GNU screen, start a new session with `screen -S name-for-session` and connect to it with gotty in another terminal window/tab through `screen -x name-for-session`. All commands and activities being done in the first terminal tab/window will now be broadcasted by gotty.
### Tmux
For example, you can start a new tmux session named `gotty` with `top` command by the command below.
```sh
$ gotty tmux new -A -s gotty top
```
This command doesn't allow clients to send keystrokes, however, you can attach the session from your local terminal and run operations like switching the mode of the `top` command. To connect to the tmux session from your terminal, you can use following command.
```sh
$ tmux new -A -s gotty
```
By using terminal multiplexers, you can have the control of your terminal and allow clients to just see your screen.
### Quick Sharing on tmux
To share your current session with others by a shortcut key, you can add a line like below to your `.tmux.conf`.
```
# Start GoTTY in a new window with C-t
bind-key C-t new-window "gotty tmux attach -t `tmux display -p '#S'`"
```
## Playing with Docker
When you want to create a jailed environment for each client, you can use Docker containers like following:
```sh
$ gotty -w docker run -it --rm busybox
```
## Development
You can build a binary by simply running `make`. go1.16 is required.
To build the frontend part (JS files and other static files), you need `npm`.
## Architecture
GoTTY uses [xterm.js](https://xtermjs.org/) to run a JavaScript based terminal on web browsers. GoTTY itself provides a websocket server that simply relays output from the TTY to clients and receives input from clients and forwards it to the TTY. This xterm + websocket idea is inspired by [Wetty](https://github.com/krishnasrinivas/wetty).
## Alternatives
### Command line client
* [gotty-client](https://github.com/moul/gotty-client): If you want to connect to GoTTY server from your terminal
### Terminal/SSH on Web Browsers
* [Secure Shell (Chrome App)](https://chrome.google.com/webstore/detail/secure-shell/pnhechapfaindjhompbnflcldabbghjo): If you are a chrome user and need a "real" SSH client on your web browser, perhaps the Secure Shell app is what you want
* [Wetty](https://github.com/krishnasrinivas/wetty): Node based web terminal (SSH/login)
* [ttyd](https://tsl0922.github.io/ttyd): C port of GoTTY with CJK and IME support
### Terminal Sharing
* [tmate](http://tmate.io/): Forked-Tmux based Terminal-Terminal sharing
* [termshare](https://termsha.re): Terminal-Terminal sharing through a HTTP server
* [tmux](https://tmux.github.io/): Tmux itself also supports TTY sharing through SSH)
# License
The MIT License
# Contributors
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://yudai.arielworks.com/"><img src="https://avatars.githubusercontent.com/u/33192?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Iwasaki Yudai</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=yudai" title="Code">💻</a></td>
<td align="center"><a href="http://linux2go.dk/"><img src="https://avatars.githubusercontent.com/u/160090?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Soren L. Hansen</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Asorenisanerd" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/uovobw"><img src="https://avatars.githubusercontent.com/u/1194751?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Andrea Lusuardi</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=uovobw" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/moul"><img src="https://avatars.githubusercontent.com/u/94029?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Manfred Touron</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=moul" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/svanellewee"><img src="https://avatars.githubusercontent.com/u/1567439?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stephan</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=svanellewee" title="Code">💻</a></td>
<td align="center"><a href="https://fr.linkedin.com/in/quentinperez"><img src="https://avatars.githubusercontent.com/u/3081204?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Quentin Perez</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=QuentinPerez" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/jizhilong"><img src="https://avatars.githubusercontent.com/u/816618?v=4?s=100" width="100px;" alt=""/><br /><sub><b>jzl</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=jizhilong" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://majid.info/"><img src="https://avatars.githubusercontent.com/u/331198?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Fazal Majid</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=fazalmajid" title="Code">💻</a></td>
<td align="center"><a href="https://narrationbox.com/"><img src="https://avatars.githubusercontent.com/u/7126128?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Immortalin</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=Immortalin" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/freakhill"><img src="https://avatars.githubusercontent.com/u/916582?v=4?s=100" width="100px;" alt=""/><br /><sub><b>freakhill</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=freakhill" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/0xflotus"><img src="https://avatars.githubusercontent.com/u/26602940?v=4?s=100" width="100px;" alt=""/><br /><sub><b>0xflotus</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=0xflotus" title="Code">💻</a></td>
<td align="center"><a href="https://andy.blog/"><img src="https://avatars.githubusercontent.com/u/52292?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Andy Skelton</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=skeltoac" title="Code">💻</a></td>
<td align="center"><a href="https://twitter.com/artdevjs"><img src="https://avatars.githubusercontent.com/u/7567983?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Artem Medvedev</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=artdevjs" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/blakejennings"><img src="https://avatars.githubusercontent.com/u/1976331?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Blake Jennings</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=blakejennings" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/jensenbox"><img src="https://avatars.githubusercontent.com/u/189265?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christian Jensen</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=jensenbox" title="Code">💻</a></td>
<td align="center"><a href="https://wilk.tech/"><img src="https://avatars.githubusercontent.com/u/9367803?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christopher Wilkinson</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=TechWilk" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/RealCyGuy"><img src="https://avatars.githubusercontent.com/u/54488650?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Cyrus</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=RealCyGuy" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/dehorsley"><img src="https://avatars.githubusercontent.com/u/3401668?v=4?s=100" width="100px;" alt=""/><br /><sub><b>David Horsley</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=dehorsley" title="Code">💻</a></td>
<td align="center"><a href="https://jasoncooke.dev/"><img src="https://avatars.githubusercontent.com/u/5185660?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jason Cooke</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=Jason-Cooke" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/DenKoren"><img src="https://avatars.githubusercontent.com/u/3419381?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Denis Korenevskiy</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=DenKoren" title="Code">💻</a></td>
<td align="center"><a href="https://www.stucchi.ch/"><img src="https://avatars.githubusercontent.com/u/1331438?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Massimiliano Stucchi</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=stucchimax" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://www.linkedin.com/in/felixoid/"><img src="https://avatars.githubusercontent.com/u/3025537?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mikhail f. Shiryaev</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=Felixoid" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/guywithnose"><img src="https://avatars.githubusercontent.com/u/1059169?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Robert Bittle</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=guywithnose" title="Code">💻</a></td>
<td align="center"><a href="https://deebas.com/"><img src="https://avatars.githubusercontent.com/u/283482?v=4?s=100" width="100px;" alt=""/><br /><sub><b>sebastian haas</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=sehaas" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/shoz"><img src="https://avatars.githubusercontent.com/u/225194?v=4?s=100" width="100px;" alt=""/><br /><sub><b>shoji</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=shoz" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/tsl0922"><img src="https://avatars.githubusercontent.com/u/1680515?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Shuanglei Tao</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=tsl0922" title="Code">💻</a></td>
<td align="center"><a href="https://gitter.im/"><img src="https://avatars.githubusercontent.com/u/8518239?v=4?s=100" width="100px;" alt=""/><br /><sub><b>The Gitter Badger</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=gitter-badger" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/xinsnake"><img src="https://avatars.githubusercontent.com/u/1287677?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jacob Zhou</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=xinsnake" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/zyfdegh"><img src="https://avatars.githubusercontent.com/u/7880217?v=4?s=100" width="100px;" alt=""/><br /><sub><b>zyfdegh</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=zyfdegh" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/fredster33"><img src="https://avatars.githubusercontent.com/u/64927044?v=4?s=100" width="100px;" alt=""/><br /><sub><b>fredster33</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=fredster33" title="Code">💻</a></td>
<td align="center"><a href="https://mattn.kaoriya.net/"><img src="https://avatars.githubusercontent.com/u/10111?v=4?s=100" width="100px;" alt=""/><br /><sub><b>mattn</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=mattn" title="Code">💻</a></td>
<td align="center"><a href="https://www.shingt.com/"><img src="https://avatars.githubusercontent.com/u/1391330?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Shinichi Goto</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=shingt" title="Code">💻</a></td>
<td align="center"><a href="https://twitter.com/_yogeshsingh"><img src="https://avatars.githubusercontent.com/u/8512357?v=4?s=100" width="100px;" alt=""/><br /><sub><b>ygit</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=ygit" title="Code">💻</a></td>
<td align="center"><a href="http://forum.cachem.fr/viewforum.php?f=21"><img src="https://avatars.githubusercontent.com/u/3392684?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stéphane</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Anephaste" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://rusnak.io/"><img src="https://avatars.githubusercontent.com/u/42201?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Pavol Rusnak</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aprusnak" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/devanlai"><img src="https://avatars.githubusercontent.com/u/1348448?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Devan Lai</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=devanlai" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/jkandasa"><img src="https://avatars.githubusercontent.com/u/1004403?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jeeva Kandasamy</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=jkandasa" title="Code">💻</a></td>
<td align="center"><a href="https://twitch.tv/iamhardliner"><img src="https://avatars.githubusercontent.com/u/2937272?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Steve Biedermann</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=hardliner66" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/xgdgsc"><img src="https://avatars.githubusercontent.com/u/1189869?v=4?s=100" width="100px;" alt=""/><br /><sub><b>xgdgsc</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Axgdgsc" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/flechaig"><img src="https://avatars.githubusercontent.com/u/10887132?v=4?s=100" width="100px;" alt=""/><br /><sub><b>flechaig</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aflechaig" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/Fan-SJ"><img src="https://avatars.githubusercontent.com/u/49977708?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Fan-SJ</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3AFan-SJ" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/dmartin"><img src="https://avatars.githubusercontent.com/u/1657652?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dustin Martin</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Admartin" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://ahmet.dev/"><img src="https://avatars.githubusercontent.com/u/159209?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ahmet Alp Balkan</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aahmetb" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/CoconutMacaroon"><img src="https://avatars.githubusercontent.com/u/45187468?v=4?s=100" width="100px;" alt=""/><br /><sub><b>CoconutMacaroon</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3ACoconutMacaroon" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.dannyben.com/"><img src="https://avatars.githubusercontent.com/u/2405099?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Danny Ben Shitrit</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3ADannyBen" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/George-NG"><img src="https://avatars.githubusercontent.com/u/28577165?v=4?s=100" width="100px;" alt=""/><br /><sub><b>George-NG</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3AGeorge-NG" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/ghthor"><img src="https://avatars.githubusercontent.com/u/160298?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Will Owens</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aghthor" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://jpillora.com/"><img src="https://avatars.githubusercontent.com/u/633843?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jaime Pillora</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Ajpillora" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/kaisawind"><img src="https://avatars.githubusercontent.com/u/4010613?v=4?s=100" width="100px;" alt=""/><br /><sub><b>kaisawind</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Akaisawind" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/linyinli"><img src="https://avatars.githubusercontent.com/u/42955482?v=4?s=100" width="100px;" alt=""/><br /><sub><b>linyinli</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Alinyinli" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/LucaMarconato"><img src="https://avatars.githubusercontent.com/u/2664412?v=4?s=100" width="100px;" alt=""/><br /><sub><b>LucaMarconato</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3ALucaMarconato" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://audiobox.fm/"><img src="https://avatars.githubusercontent.com/u/12844?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kain</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Amasterkain" title="Bug reports">🐛</a></td>
<td align="center"><a href="http://duro.me/"><img src="https://avatars.githubusercontent.com/u/1498061?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Andi Andreas</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3ANexuist" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/qigj"><img src="https://avatars.githubusercontent.com/u/56585735?v=4?s=100" width="100px;" alt=""/><br /><sub><b>qigj</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aqigj" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/shuaiyy"><img src="https://avatars.githubusercontent.com/u/19821321?v=4?s=100" width="100px;" alt=""/><br /><sub><b>shuaiyy</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Ashuaiyy" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/v20z"><img src="https://avatars.githubusercontent.com/u/2884824?v=4?s=100" width="100px;" alt=""/><br /><sub><b>v20z</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Av20z" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/Yann-Qiu"><img src="https://avatars.githubusercontent.com/u/56961747?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Yanfeng Qiu</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3AYann-Qiu" title="Bug reports">🐛</a></td>
</tr>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

View File

@ -1,6 +0,0 @@
/^## Options/,/^### Config File/ {
/^\(`\|#\)/!d # Delete any line not beginning with ` or #
/```sh/ { # Shove options.txt.tmp in after ```sh
r options.txt.tmp
}
}

View File

@ -1 +0,0 @@
package backend

View File

@ -1,3 +0,0 @@
// Package localcommand provides an implementation of webtty.Slave
// that launches a local command with a PTY.
package localcommand

View File

@ -1,48 +0,0 @@
package localcommand
import (
"syscall"
"time"
"github.com/sorenisanerd/gotty/server"
)
type Options struct {
CloseSignal int `hcl:"close_signal" flagName:"close-signal" flagSName:"" flagDescribe:"Signal sent to the command process when gotty close it (default: SIGHUP)" default:"1"`
CloseTimeout int `hcl:"close_timeout" flagName:"close-timeout" flagSName:"" flagDescribe:"Time in seconds to force kill process after client is disconnected (default: -1)" default:"-1"`
}
type Factory struct {
command string
argv []string
options *Options
opts []Option
}
func NewFactory(command string, argv []string, options *Options) (*Factory, error) {
opts := []Option{WithCloseSignal(syscall.Signal(options.CloseSignal))}
if options.CloseTimeout >= 0 {
opts = append(opts, WithCloseTimeout(time.Duration(options.CloseTimeout)*time.Second))
}
return &Factory{
command: command,
argv: argv,
options: options,
opts: opts,
}, nil
}
func (factory *Factory) Name() string {
return "local command"
}
func (factory *Factory) New(params map[string][]string, headers map[string][]string) (server.Slave, error) {
argv := make([]string, len(factory.argv))
copy(argv, factory.argv)
if params["arg"] != nil && len(params["arg"]) > 0 {
argv = append(argv, params["arg"]...)
}
return New(factory.command, argv, headers, factory.opts...)
}

View File

@ -1,135 +0,0 @@
package localcommand
import (
"os"
"os/exec"
"strings"
"syscall"
"time"
"github.com/creack/pty"
"github.com/pkg/errors"
)
const (
DefaultCloseSignal = syscall.SIGINT
DefaultCloseTimeout = 10 * time.Second
)
type LocalCommand struct {
command string
argv []string
closeSignal syscall.Signal
closeTimeout time.Duration
cmd *exec.Cmd
pty *os.File
ptyClosed chan struct{}
}
func New(command string, argv []string, headers map[string][]string, options ...Option) (*LocalCommand, error) {
cmd := exec.Command(command, argv...)
cmd.Env = append(os.Environ(), "TERM=xterm-256color")
// Combine headers into key=value pairs to set as env vars
// Prefix the headers with "http_" so we don't overwrite any other env vars
// which potentially has the same name and to bring these closer to what
// a (F)CGI server would proxy to a backend service
// Replace hyphen with underscore and make them all upper case
for key, values := range headers {
h := "HTTP_" + strings.Replace(strings.ToUpper(key), "-", "_", -1) + "=" + strings.Join(values, ",")
// log.Printf("Adding header: %s", h)
cmd.Env = append(cmd.Env, h)
}
pty, err := pty.Start(cmd)
if err != nil {
// todo close cmd?
return nil, errors.Wrapf(err, "failed to start command `%s`", command)
}
ptyClosed := make(chan struct{})
lcmd := &LocalCommand{
command: command,
argv: argv,
closeSignal: DefaultCloseSignal,
closeTimeout: DefaultCloseTimeout,
cmd: cmd,
pty: pty,
ptyClosed: ptyClosed,
}
for _, option := range options {
option(lcmd)
}
// When the process is closed by the user,
// close pty so that Read() on the pty breaks with an EOF.
go func() {
defer func() {
lcmd.pty.Close()
close(lcmd.ptyClosed)
}()
lcmd.cmd.Wait()
}()
return lcmd, nil
}
func (lcmd *LocalCommand) Read(p []byte) (n int, err error) {
return lcmd.pty.Read(p)
}
func (lcmd *LocalCommand) Write(p []byte) (n int, err error) {
return lcmd.pty.Write(p)
}
func (lcmd *LocalCommand) Close() error {
if lcmd.cmd != nil && lcmd.cmd.Process != nil {
lcmd.cmd.Process.Signal(lcmd.closeSignal)
}
for {
select {
case <-lcmd.ptyClosed:
return nil
case <-lcmd.closeTimeoutC():
lcmd.cmd.Process.Signal(syscall.SIGKILL)
}
}
}
func (lcmd *LocalCommand) WindowTitleVariables() map[string]interface{} {
return map[string]interface{}{
"command": lcmd.command,
"argv": lcmd.argv,
"pid": lcmd.cmd.Process.Pid,
}
}
func (lcmd *LocalCommand) ResizeTerminal(width int, height int) error {
window := pty.Winsize{
Rows: uint16(height),
Cols: uint16(width),
X: 0,
Y: 0,
}
err := pty.Setsize(lcmd.pty, &window)
if err != nil {
return err
} else {
return nil
}
}
func (lcmd *LocalCommand) closeTimeoutC() <-chan time.Time {
if lcmd.closeTimeout >= 0 {
return time.After(lcmd.closeTimeout)
}
return make(chan time.Time)
}

View File

@ -1,88 +0,0 @@
package localcommand
import (
"bytes"
"reflect"
"testing"
"time"
)
func TestNewFactory(t *testing.T) {
factory, err := NewFactory("/bin/false", []string{}, &Options{CloseSignal: 123, CloseTimeout: 321})
if err != nil {
t.Errorf("NewFactory() returned error")
return
}
if factory.command != "/bin/false" {
t.Errorf("factory.command = %v, expected %v", factory.command, "/bin/false")
}
if !reflect.DeepEqual(factory.argv, []string{}) {
t.Errorf("factory.argv = %v, expected %v", factory.argv, []string{})
}
if !reflect.DeepEqual(factory.options, &Options{CloseSignal: 123, CloseTimeout: 321}) {
t.Errorf("factory.options = %v, expected %v", factory.options, &Options{})
}
slave, _ := factory.New(nil, nil)
lcmd := slave.(*LocalCommand)
if lcmd.closeSignal != 123 {
t.Errorf("lcmd.closeSignal = %v, expected %v", lcmd.closeSignal, 123)
}
if lcmd.closeTimeout != time.Second*321 {
t.Errorf("lcmd.closeTimeout = %v, expected %v", lcmd.closeTimeout, time.Second*321)
}
}
func TestFactoryNew(t *testing.T) {
factory, err := NewFactory("/bin/cat", []string{}, &Options{})
if err != nil {
t.Errorf("NewFactory() returned error")
return
}
slave, err := factory.New(nil, nil)
if err != nil {
t.Errorf("factory.New() returned error")
return
}
writeBuf := []byte("foobar\n")
n, err := slave.Write(writeBuf)
if err != nil {
t.Errorf("write() failed: %v", err)
return
}
if n != 7 {
t.Errorf("Unexpected write length. n = %d, expected n = %d", n, 7)
return
}
// Local echo is on, so we get the output twice:
// Once because we're "typing" it, and once more
// repeated back to us by `cat`. Also, \r\n
// because we're a terminal.
expectedBuf := []byte("foobar\r\nfoobar\r\n")
readBuf := make([]byte, 1024)
var totalRead int
for totalRead < 16 {
n, err = slave.Read(readBuf[totalRead:])
if err != nil {
t.Errorf("read() failed: %v", err)
return
}
totalRead += n
}
if totalRead != 16 {
t.Errorf("Unexpected read length. totalRead = %d, expected totalRead = %d", totalRead, 16)
return
}
if !bytes.Equal(readBuf[:totalRead], expectedBuf) {
t.Errorf("unexpected output from slave: got %v, expected %v", readBuf[:totalRead], expectedBuf)
}
err = slave.Close()
if err != nil {
t.Errorf("close() failed: %v", err)
return
}
}

View File

@ -1,20 +0,0 @@
package localcommand
import (
"syscall"
"time"
)
type Option func(*LocalCommand)
func WithCloseSignal(signal syscall.Signal) Option {
return func(lcmd *LocalCommand) {
lcmd.closeSignal = signal
}
}
func WithCloseTimeout(timeout time.Duration) Option {
return func(lcmd *LocalCommand) {
lcmd.closeTimeout = timeout
}
}

View File

@ -1,8 +0,0 @@
//go:build !dev
package bindata
import "embed"
//go:embed static/*
var Fs embed.FS

View File

@ -1,28 +0,0 @@
//go:build dev
package bindata
import (
"io"
"io/fs"
"os"
)
type GottyFS struct {
fs.FS
}
var Fs GottyFS
func (gfs *GottyFS) ReadFile(name string) ([]byte, error) {
fp, err := gfs.Open(name)
if err != nil {
return nil, err
}
return io.ReadAll(fp)
}
func init() {
Fs = GottyFS{os.DirFS("bindata")}
}

View File

@ -1,13 +0,0 @@
html, body, #terminal {
background: black;
height: 100%;
width: 100%;
padding: 0%;
margin: 0%;
}
.progress .progress-bar {
transition: unset;
transition-duration: 0.1s;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

View File

@ -1,209 +0,0 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
cursor: text;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: #000;
color: #FFF;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: #000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer,
.xterm .xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility,
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
pointer-events: none;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
/* Dim should not apply to background, so the opacity of the foreground color is applied
* explicitly in the generated class and reset to 1 here */
opacity: 1 !important;
}
.xterm-underline-1 { text-decoration: underline; }
.xterm-underline-2 { text-decoration: double underline; }
.xterm-underline-3 { text-decoration: wavy underline; }
.xterm-underline-4 { text-decoration: dotted underline; }
.xterm-underline-5 { text-decoration: dashed underline; }
.xterm-overline {
text-decoration: overline;
}
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
.xterm-strikethrough {
text-decoration: line-through;
}
.xterm-screen .xterm-decoration-container .xterm-decoration {
z-index: 6;
position: absolute;
}
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
z-index: 7;
}
.xterm-decoration-overview-ruler {
z-index: 8;
position: absolute;
top: 0;
right: 0;
pointer-events: none;
}
.xterm-decoration-top {
z-index: 2;
position: relative;
}

View File

@ -1,19 +0,0 @@
.terminal {
font-family: "DejaVu Sans Mono", "Everson Mono", FreeMono, Menlo, Terminal, monospace, "Apple Symbols";
}
.xterm-overlay {
font-family: "DejaVu Sans Mono", "Everson Mono", FreeMono, Menlo, Terminal, monospace, "Apple Symbols";
border-radius: 15px;
font-size: xx-large;
color: black;
background: white;
opacity: 0.75;
padding: 0.2em 0.5em 0.2em 0.5em;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
user-select: none;
transition: opacity 180ms ease-in;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -1,66 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 708.4149 708.41411"
height="708.41412"
width="708.41492"
xml:space="preserve"
id="svg2"
version="1.1"><metadata
id="metadata8"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
id="defs6"><clipPath
id="clipPath18"
clipPathUnits="userSpaceOnUse"><path
id="path16"
d="M 0,2000 H 2000 V 0 H 0 Z" /></clipPath></defs><g
transform="matrix(1.3333333,0,0,-1.3333333,-979.12558,1687.5405)"
id="g10"><g
id="g12"><g
clip-path="url(#clipPath18)"
id="g14"><g
transform="translate(772.1414,1265.6554)"
id="g20"><path
id="path22"
style="fill:#de3c28;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c -20.875,0 -37.797,-16.922 -37.797,-37.797 v -126.348 -25.917 -212.342 L 345.882,0 Z" /></g><g
transform="translate(956.8504,734.3448)"
id="g24"><path
id="path26"
style="fill:#af1419;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 h 260.209 c 26.839,0 48.596,21.757 48.596,48.596 v 275.281 z" /></g><g
transform="translate(1265.6552,1075.5929)"
id="g28"><path
id="path30"
style="fill:#db0918;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v 25.918 126.348 c 0,20.875 -16.922,37.796 -37.796,37.796 h -109.836 l -383.679,-402.404 v -80.31 c 0,-26.839 21.757,-48.596 48.596,-48.596 h 173.91 L 0,-17.371 Z" /></g><g
transform="translate(1169.2147,909.6954)"
id="g32"><path
id="path34"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 h -138.227 c -9.129,0 -16.528,7.4 -16.528,16.529 0,9.128 7.399,16.529 16.528,16.529 H 0 c 9.129,0 16.528,-7.401 16.528,-16.529 C 16.528,7.4 9.129,0 0,0" /></g><g
transform="translate(898.8318,1033.5314)"
id="g36"><path
id="path38"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c 2.86,-0.72 5.65,-1.45 8.37,-2.2 -0.63,-8.56 -7.76,-15.3 -16.479,-15.3 -9.13,0 -16.531,7.4 -16.531,16.53 v 8.54 c 1.861,-0.83 3.72,-1.549 5.601,-2.15 C -15.199,4.18 -8.85,2.37 0,0" /></g><g
transform="translate(907.2527,1150.7814)"
id="g40"><path
id="path42"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v -65.81 c -4.45,1.59 -9.98,2.38 -16.601,2.38 -6.21,0 -11.7,-0.88 -16.46,-2.64 V 0 c 0,9.13 7.401,16.53 16.531,16.53 C -7.4,16.53 0,9.13 0,0" /></g><g
transform="translate(874.1922,868.8272)"
id="g44"><path
id="path46"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v 65.811 c 4.45,-1.59 9.98,-2.38 16.601,-2.38 6.21,0 11.699,0.88 16.46,2.639 V 0 C 33.061,-9.13 25.66,-16.529 16.53,-16.529 7.4,-16.529 0,-9.13 0,0" /></g><g
transform="translate(966.6326,994.1915)"
id="g48"><path
id="path50"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c -3.53,7.28 -8.45,13.3 -14.75,18.06 -6.301,4.76 -13.95,8.8 -22.94,12.14 -6.661,2.47 -13.911,4.78 -21.741,6.94 -2.719,0.75 -5.509,1.48 -8.37,2.2 -8.849,2.37 -15.199,4.18 -19.039,5.42 -1.881,0.6 -3.74,1.32 -5.6,2.15 -1.951,0.87 -3.88,1.87 -5.8,2.99 -3.76,2.19 -6.71,4.81 -8.861,7.85 -2.139,3.05 -3.219,6.67 -3.219,10.86 0,6.75 3.16,12.54 9.46,17.34 2.49,1.9 5.299,3.43 8.42,4.57 4.759,1.76 10.25,2.64 16.46,2.64 6.62,0 12.15,-0.79 16.6,-2.38 3.01,-1.05 5.52,-2.48 7.54,-4.26 5.01,-4.42 9.3,-10.59 12.88,-18.49 2.77,-5.52 5.34,-9.49 7.71,-11.92 2.37,-2.43 5.84,-3.64 10.399,-3.64 5.011,0 9.191,2.02 12.54,6.07 3.351,4.04 5.031,8.59 5.031,13.63 0,5.52 -1.34,11.19 -4.021,17 -2.689,5.8 -6.939,11.35 -12.75,16.63 -5.809,5.28 -13.119,9.52 -21.929,12.71 -5.23,1.89 -11.031,3.22 -17.4,3.99 -4.37,0.53 -9.011,0.79 -13.921,0.79 -6.779,0 -13.159,-0.48 -19.139,-1.45 -7.361,-1.19 -14.121,-3.11 -20.29,-5.76 -11.18,-4.81 -19.72,-11.69 -25.621,-20.63 -5.899,-8.95 -8.849,-19.18 -8.849,-30.7 0,-12.09 2.79,-22.2 8.38,-30.34 5.59,-8.14 13.15,-14.56 22.67,-19.28 9.52,-4.71 21.349,-8.83 35.48,-12.35 10.55,-2.57 18.98,-4.99 25.279,-7.28 6.301,-2.28 11.441,-5.59 15.42,-9.92 3.981,-4.33 5.971,-9.97 5.971,-16.92 0,-8.76 -3.69,-16.06 -11.061,-21.92 -7.379,-5.85 -16.969,-8.78 -28.769,-8.78 -8.59,0 -15.521,1.45 -20.79,4.36 -5.28,2.9 -9.37,6.59 -12.28,11.06 -2.901,4.47 -5.611,10.04 -8.111,16.71 -2.059,5.61 -4.54,9.85 -7.449,12.7 -2.9,2.86 -6.46,4.29 -10.66,4.29 -5.181,0 -9.45,-1.84 -12.811,-5.5 -3.349,-3.66 -5.029,-8.07 -5.029,-13.21 0,-8.85 2.8,-17.96 8.39,-27.34 5.58,-9.38 12.849,-16.87 21.79,-22.49 12.61,-7.8 28.61,-11.7 48.019,-11.7 16.181,0 30.181,2.85 41.981,8.56 11.809,5.71 20.769,13.61 26.9,23.7 6.119,10.09 9.18,21.47 9.18,34.129 C 5.3,-16.21 3.54,-7.28 0,0" /></g></g></g></g></svg>

Before

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

View File

@ -1,22 +0,0 @@
<!doctype html>
<html>
<head>
<title>{{ .title }}</title>
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<link rel="icon" href="favicon.ico">
<link rel="icon" href="icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./css/index.css" />
<link rel="stylesheet" href="./css/xterm.css" />
<link rel="stylesheet" href="./css/xterm_customize.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="terminal"></div>
<script src="./auth_token.js"></script>
<script src="./config.js"></script>
<script src="./js/gotty.js"></script>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -1,7 +0,0 @@
/*!
* Bootstrap v5.3.2 (https://getbootstrap.com/)
* Copyright 2011-2023 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/
/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */

File diff suppressed because one or more lines are too long

View File

@ -1,649 +0,0 @@
@popperjs/core
MIT
The MIT License (MIT)
Copyright (c) 2019 Federico Zivolo
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
bootstrap
MIT
The MIT License (MIT)
Copyright (c) 2011-2023 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
crc-32
Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (C) 2014-present SheetJS LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
css-loader
MIT
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
jsx-runtime
MIT
The MIT License (MIT)
Copyright (c) 2015-present Jason Miller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
preact
MIT
The MIT License (MIT)
Copyright (c) 2015-present Jason Miller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
style-loader
MIT
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
xterm
MIT
Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
xterm-addon-fit
MIT
Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
xterm-addon-web-links
MIT
Copyright (c) 2017, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
xterm-addon-webgl
MIT
Copyright (c) 2018, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
zmodem.js
Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,15 +0,0 @@
{
"short_name": "{{ .title }}",
"name": "{{ .title }}",
"start_url": "./",
"icons": [
{
"src": "./icon_192.png",
"type": "image/png",
"sizes": "192x192"
}
],
"display": "minimal-ui",
"theme_color": "#000000",
"background_color": "#000000"
}

3623
favicon.ai

File diff suppressed because one or more lines are too long

23
go.mod
View File

@ -1,22 +1,5 @@
module github.com/sorenisanerd/gotty
module github.com/sorenisanerd/gotty/v2
go 1.20
go 1.13
require (
github.com/NYTimes/gziphandler v1.1.1
github.com/creack/pty v1.1.11
github.com/fatih/structs v1.1.0
github.com/gorilla/websocket v1.4.2
github.com/pkg/errors v0.9.1
github.com/urfave/cli/v2 v2.3.0
github.com/yudai/hcl v0.0.0-20151013225006-5fa2393b3552
)
require (
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/russross/blackfriday/v2 v2.0.1 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
golang.org/x/sys v0.1.0 // indirect
)
retract [v2.0.0, v2.1.1]

36
go.sum
View File

@ -1,36 +0,0 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I=
github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=
github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/yudai/hcl v0.0.0-20151013225006-5fa2393b3552 h1:tjsK9T2IA3d2FFNxzDP7AJf+EXhyuPd7PB4Z2HrtAoc=
github.com/yudai/hcl v0.0.0-20151013225006-5fa2393b3552/go.mod h1:hg0ZaCmQL3rze1cH8Fh2g0a9q8vQs0uN8ESpePEwSEw=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

4524
js/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +0,0 @@
{
"name": "gotty",
"version": "1.4.0",
"private": true,
"devDependencies": {
"@types/bootstrap": "^5.2.10",
"compression-webpack-plugin": "^9.2.0",
"license-loader": "^0.5.0",
"license-webpack-plugin": "^4.0.2",
"purgecss": "^4.1.3",
"sass": "^1.70.0",
"sass-loader": "^12.6.0",
"terser-webpack-plugin": "^5.3.10",
"ts-loader": "^8.4.0",
"typescript": "^4.9.5",
"webpack": "^5.90.1",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.15.1"
},
"dependencies": {
"@popperjs/core": "^2.11.8",
"bootstrap": "^5.3.2",
"css-loader": "^5.2.7",
"debounce": "^1.2.1",
"preact": "^10.19.4",
"react-bootstrap": "^2.10.1",
"style-loader": "^2.0.0",
"xterm": "^5.3.0",
"xterm-addon-fit": "^0.8.0",
"xterm-addon-web-links": "^0.9.0",
"xterm-addon-webgl": "^0.16.0",
"zmodem.js": "^0.1.10"
}
}

View File

@ -1,63 +0,0 @@
import { createRef, Component, ComponentChildren } from "preact";
import { Modal } from "bootstrap";
import './bootstrap.scss';
interface ModalProps {
children: ComponentChildren;
buttons?: ComponentChildren;
title: string;
dismissHandler?: (hideModal?: () => void) => void;
}
export class MyModal extends Component<ModalProps, {}> {
ref = createRef<HTMLDivElement>();
constructor() {
super();
}
componentDidMount() {
Modal.getOrCreateInstance(this.ref.current!).show();
this.ref.current?.addEventListener('hide.bs.modal', () => { this.props.dismissHandler && this.props.dismissHandler(); });
}
componentWillUnmount() {
this.hide()
}
hide(): void {
Modal.getOrCreateInstance(this.ref.current!).hide();
}
render() {
return <div class="modal fade" ref={this.ref} tabIndex={-1} aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{this.props.title}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
{this.props.children}
</div>
<div class="modal-footer">
{this.props.buttons}
</div>
</div>
</div>
</div>;
}
}
interface ButtonProps {
priority: "primary" | "secondary" | "danger"
clickHandler?: () => void
children: ComponentChildren
disabled?: boolean;
}
export function Button(props:ButtonProps) {
let classes: string = "btn btn-" + props.priority
return <button type="button" disabled={props.disabled} class={classes} onClick={ () => { props.clickHandler ? props.clickHandler() : null; }}>{ props.children}</button>
}

26
js/src/bootstrap.scss vendored
View File

@ -1,26 +0,0 @@
@import "mixins/banner";
@include bsBanner("");
// scss-docs-start import-stack
// Configuration
@import "functions";
@import "variables";
@import "variables-dark";
@import "maps";
@import "mixins";
@import "utilities";
// Layout & components
@import "root";
@import "reboot";
@import "type";
@import "images";
@import "containers";
@import "grid";
@import "buttons";
@import "transitions";
@import "progress";
@import "close";
@import "modal";
@import "spinners";

View File

@ -1,31 +0,0 @@
import { ConnectionFactory } from "./websocket";
import { Terminal, WebTTY, protocols } from "./webtty";
import { OurXterm } from "./xterm";
// @TODO remove these
declare var gotty_auth_token: string;
declare var gotty_term: string;
declare var gotty_ws_query_args: string;
const elem = document.getElementById("terminal")
if (elem !== null) {
var term: Terminal;
term = new OurXterm(elem);
const httpsEnabled = window.location.protocol == "https:";
const queryArgs = (gotty_ws_query_args === "") ? "" : "?" + gotty_ws_query_args;
const url = (httpsEnabled ? 'wss://' : 'ws://') + window.location.host + window.location.pathname + 'ws' + queryArgs;
const args = window.location.search;
const factory = new ConnectionFactory(url, protocols);
const wt = new WebTTY(term, factory, args, gotty_auth_token);
const closer = wt.open();
// According to https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event
// this event is unreliable and in some cases (Firefox is mentioned), having an
// "unload" event handler can have unwanted side effects. Consider commenting it out.
window.addEventListener("unload", () => {
closer();
term.close();
});
};

View File

@ -1,59 +0,0 @@
export class ConnectionFactory {
url: string;
protocols: string[];
constructor(url: string, protocols: string[]) {
this.url = url;
this.protocols = protocols;
};
create(): Connection {
return new Connection(this.url, this.protocols);
};
}
export class Connection {
bare: WebSocket;
constructor(url: string, protocols: string[]) {
this.bare = new WebSocket(url, protocols);
}
open() {
// nothing todo for websocket
};
close() {
this.bare.close();
};
send(data: string) {
this.bare.send(data);
};
isOpen(): boolean {
if (this.bare.readyState == WebSocket.CONNECTING ||
this.bare.readyState == WebSocket.OPEN) {
return true
}
return false
}
onOpen(callback: () => void) {
this.bare.onopen = (event) => {
callback();
}
};
onReceive(callback: (data: string) => void) {
this.bare.onmessage = (event) => {
callback(event.data);
}
};
onClose(callback: () => void) {
this.bare.onclose = (event) => {
callback();
};
};
}

View File

@ -1,270 +0,0 @@
export const protocols = ["webtty"];
export const msgInputUnknown = '0';
export const msgInput = '1';
export const msgPing = '2';
export const msgResizeTerminal = '3';
export const msgSetEncoding = '4';
export const msgUnknownOutput = '0';
export const msgOutput = '1';
export const msgPong = '2';
export const msgSetWindowTitle = '3';
export const msgSetPreferences = '4';
export const msgSetReconnect = '5';
export const msgSetBufferSize = '6';
export interface Terminal {
/*
* Get dimensions of the terminal
*/
info(): { columns: number, rows: number };
/*
* Process output from the server side
*/
output(data: Uint8Array): void;
/*
* Display a message overlay on the terminal
*/
showMessage(message: string, timeout: number): void;
// Don't think we need this anymore
// getMessage(): HTMLElement;
/*
* Remove message shown by shoMessage. You only need to call
* this if you want to dismiss it sooner than the timeout.
*/
removeMessage(): void;
/*
* Set window title
*/
setWindowTitle(title: string): void;
/*
* Set preferences. TODO: Add typings
*/
setPreferences(value: object): void;
/*
* Sets an input (e.g. user types something) handler
*/
onInput(callback: (input: string) => void): void;
/*
* Sets a resize handler
*/
onResize(callback: (colmuns: number, rows: number) => void): void;
reset(): void;
deactivate(): void;
close(): void;
}
export interface Connection {
open(): void;
close(): void;
/*
* This takes fucking strings??
*/
send(s: string): void;
isOpen(): boolean;
onOpen(callback: () => void): void;
onReceive(callback: (data: string) => void): void;
onClose(callback: () => void): void;
}
export interface ConnectionFactory {
create(): Connection;
}
export class WebTTY {
/*
* A terminal instance that implements the Terminal interface.
* This made a lot of sense when we had both HTerm and xterm, but
* now I wonder if the abstraction makes sense. Keeping it for now,
* though.
*/
term: Terminal;
/*
* ConnectionFactory and connection instance. We pass the factory
* in instead of just a connection so that we can reconnect.
*/
connectionFactory: ConnectionFactory;
connection: Connection;
/*
* Arguments passed in by the user. We forward them to the backend
* where they are appended to the command line.
*/
args: string;
/*
* An authentication token. The client gets this from `/auth_token.js`.
*/
authToken: string;
/*
* If connection is dropped, reconnect after `reconnect` seconds.
* -1 means do not reconnect.
*/
reconnect: number;
/*
* The server's buffer size. If a single message exceeds this size, it will
* be truncated on the server, so we track it here so that we can split messages
* into chunks small enough that we don't hurt the server's feelings.
*/
bufSize: number;
constructor(term: Terminal, connectionFactory: ConnectionFactory, args: string, authToken: string) {
this.term = term;
this.connectionFactory = connectionFactory;
this.args = args;
this.authToken = authToken;
this.reconnect = -1;
this.bufSize = 1024;
};
open() {
let connection = this.connectionFactory.create();
let pingTimer: NodeJS.Timeout;
let reconnectTimeout: NodeJS.Timeout;
this.connection = connection;
const setup = () => {
connection.onOpen(() => {
const termInfo = this.term.info();
this.initializeConnection(this.args, this.authToken);
this.term.onResize((columns: number, rows: number) => {
this.sendResizeTerminal(columns, rows);
});
this.sendResizeTerminal(termInfo.columns, termInfo.rows);
this.sendSetEncoding("base64");
this.term.onInput(
(input: string | Uint8Array) => {
this.sendInput(input);
}
);
pingTimer = setInterval(() => {
this.sendPing()
}, 30 * 1000);
});
connection.onReceive((data) => {
const payload = data.slice(1);
switch (data[0]) {
case msgOutput:
this.term.output(Uint8Array.from(atob(payload), c => c.charCodeAt(0)));
break;
case msgPong:
break;
case msgSetWindowTitle:
this.term.setWindowTitle(payload);
break;
case msgSetPreferences:
const preferences = JSON.parse(payload);
this.term.setPreferences(preferences);
break;
case msgSetReconnect:
const autoReconnect = JSON.parse(payload);
console.log("Enabling reconnect: " + autoReconnect + " seconds")
this.reconnect = autoReconnect;
break;
case msgSetBufferSize:
const bufSize = JSON.parse(payload);
this.bufSize = bufSize;
break;
}
});
connection.onClose(() => {
clearInterval(pingTimer);
this.term.deactivate();
this.term.showMessage("Connection Closed", 0);
if (this.reconnect > 0) {
reconnectTimeout = setTimeout(() => {
connection = this.connectionFactory.create();
this.term.reset();
setup();
}, this.reconnect * 1000);
}
});
connection.open();
}
setup();
return () => {
clearTimeout(reconnectTimeout);
connection.close();
}
};
private initializeConnection(args, authToken) {
this.connection.send(JSON.stringify(
{
Arguments: args,
AuthToken: authToken,
}
));
}
/*
* sendInput sends data to the server. It accepts strings or Uint8Arrays.
* strings will be encoded as UTF-8. Uint8Arrays are passed along as-is.
*/
private sendInput(input: string | Uint8Array) {
let effectiveBufferSize = this.bufSize - 1;
let dataString: string;
if (typeof input === "string") {
dataString = input;
} else {
dataString = String.fromCharCode(...input)
}
// Account for base64 encoding
let maxChunkSize = Math.floor(effectiveBufferSize / 4) * 3;
for (let i = 0; i < Math.ceil(dataString.length / maxChunkSize); i++) {
let inputChunk = dataString.substring(i * maxChunkSize, Math.min((i + 1) * maxChunkSize, dataString.length))
this.connection.send(msgInput + btoa(inputChunk));
}
}
private sendPing(): void {
this.connection.send(msgPing);
}
private sendResizeTerminal(colmuns: number, rows: number) {
this.connection.send(
msgResizeTerminal + JSON.stringify(
{
columns: colmuns,
rows: rows
}
)
);
}
private sendSetEncoding(encoding: "base64" | "null") {
this.connection.send(msgSetEncoding + encoding)
}
};

View File

@ -1,166 +0,0 @@
import { IDisposable, Terminal } from "xterm";
import { FitAddon } from 'xterm-addon-fit';
import { WebLinksAddon } from 'xterm-addon-web-links';
import { WebglAddon } from 'xterm-addon-webgl';
import { ZModemAddon } from "./zmodem";
export class OurXterm {
// The HTMLElement that contains our terminal
elem: HTMLElement;
// The xtermjs.XTerm
term: Terminal;
resizeListener: () => void;
message: HTMLElement;
messageTimeout: number;
messageTimer: NodeJS.Timeout;
onResizeHandler: IDisposable;
onDataHandler: IDisposable;
fitAddOn: FitAddon;
zmodemAddon: ZModemAddon;
toServer: (data: string | Uint8Array) => void;
encoder: TextEncoder
constructor(elem: HTMLElement) {
this.elem = elem;
this.term = new Terminal();
this.fitAddOn = new FitAddon();
this.zmodemAddon = new ZModemAddon({
toTerminal: (x: Uint8Array) => this.term.write(x),
toServer: (x: Uint8Array) => this.sendInput(x)
});
this.term.loadAddon(new WebLinksAddon());
this.term.loadAddon(this.fitAddOn);
this.term.loadAddon(this.zmodemAddon);
this.message = elem.ownerDocument.createElement("div");
this.message.className = "xterm-overlay";
this.messageTimeout = 2000;
this.resizeListener = () => {
this.fitAddOn.fit();
this.term.scrollToBottom();
this.showMessage(String(this.term.cols) + "x" + String(this.term.rows), this.messageTimeout);
};
this.term.open(elem);
this.term.focus();
this.resizeListener();
window.addEventListener("resize", () => { this.resizeListener(); });
};
info(): { columns: number, rows: number } {
return { columns: this.term.cols, rows: this.term.rows };
};
// This gets called from the Websocket's onReceive handler
output(data: Uint8Array) {
this.zmodemAddon.consume(data);
};
getMessage(): HTMLElement {
return this.message;
}
showMessage(message: string, timeout: number) {
this.message.innerHTML = message;
this.showMessageElem(timeout);
}
showMessageElem(timeout: number) {
this.elem.appendChild(this.message);
if (this.messageTimer) {
clearTimeout(this.messageTimer);
}
if (timeout > 0) {
this.messageTimer = setTimeout(() => {
try {
this.elem.removeChild(this.message);
} catch (error) {
console.error(error);
}
}, timeout);
}
};
removeMessage(): void {
if (this.message.parentNode == this.elem) {
this.elem.removeChild(this.message);
}
}
setWindowTitle(title: string) {
document.title = title;
};
setPreferences(value: object) {
Object.keys(value).forEach((key) => {
if (key == "EnableWebGL" && key) {
this.term.loadAddon(new WebglAddon());
} else if (key == "font-size") {
this.term.options.fontSize = value[key]
} else if (key == "font-family") {
this.term.options.fontFamily = value[key]
}
});
};
sendInput(data: Uint8Array) {
return this.toServer(data)
}
onInput(callback: (input: string) => void) {
this.encoder = new TextEncoder()
this.toServer = callback;
// I *think* we're ok like this, but if not, we can dispose
// of the previous handler and put the new one in place.
if (this.onDataHandler !== undefined) {
return
}
this.onDataHandler = this.term.onData((input) => {
this.toServer(this.encoder.encode(input));
});
};
onResize(callback: (colmuns: number, rows: number) => void) {
this.onResizeHandler = this.term.onResize(() => {
callback(this.term.cols, this.term.rows);
});
};
deactivate(): void {
this.onDataHandler.dispose();
this.onResizeHandler.dispose();
this.term.blur();
}
reset(): void {
this.removeMessage();
this.term.clear();
}
close(): void {
window.removeEventListener("resize", this.resizeListener);
this.term.dispose();
}
disableStdin(): void {
this.term.options.disableStdin = true;
}
enableStdin(): void {
this.term.options.disableStdin = false;
}
focus(): void {
this.term.focus();
}
}

View File

@ -1,245 +0,0 @@
import { Component, ComponentChildren, createRef, render } from "preact";
import { ITerminalAddon, Terminal } from "xterm";
import { Browser, Detection, Offer, Sentry, Session } from 'zmodem.js/src/zmodem_browser';
import { Button, MyModal } from "./MyModal";
export class ZModemAddon implements ITerminalAddon {
term: Terminal;
elem: HTMLDivElement;
sentry: Sentry;
toTerminal: (data: Uint8Array) => void;
toServer: (data: Uint8Array) => void;
constructor(props: {
toTerminal: (data: Uint8Array) => void,
toServer: (data: Uint8Array) => void
}) {
this.createElement();
this.toTerminal = props.toTerminal;
this.toServer = props.toServer;
this.init();
}
private createElement() {
this.elem = document.createElement("div");
document.body.prepend(this.elem);
}
consume(data: Uint8Array) {
this.sentry.consume(data)
}
activate(terminal: Terminal): void {
this.term = terminal
}
dispose() {
}
private init() {
render(<></>, this.elem);
this.sentry = new Sentry({
'to_terminal': (d: Uint8Array) => this.toTerminal(d),
'on_detect': (detection: Detection) => this.onDetect(detection),
'sender': (x: Uint8Array) => { this.toServer(x) },
'on_retract': () => this.reset(),
});
}
private reset() {
this.init();
this.term.options.disableStdin = false;
this.term.focus();
}
private onDetect(detection: Detection) {
var zsession = detection.confirm();
this.term.options.disableStdin = true;
zsession.on('session_end', () => { this.reset() });
if (zsession.type === "send") {
this.send(zsession);
}
else {
zsession.on("offer", (xfer: any) => this.onOffer(xfer));
zsession.start();
}
}
private send(zsession: Session) {
render(<SendFileModal session={zsession} />, this.elem)
}
private onOffer(xfer: Offer) {
render(<ReceiveFileModal xfer={xfer} onFinish={() => this.reset()} />, this.elem)
}
}
// Renders a bootstrap progress bar
function Progress(props: { min: number, max: number, now: number, children?: ComponentChildren }) {
let { min, max, now } = props;
let percentage = "0";
if ((typeof min === "number") &&
(typeof max === "number") &&
(typeof now === "number") &&
(min != max)) {
percentage = (100 * (now - min) / (max - min)).toFixed(0);
}
return <div class="progress">
<div class="progress-bar" role="progressbar" style={"width: " + percentage + "%"} aria-valuenow={now} aria-valuemin={min} aria-valuemax={max}>{props.children}</div>
</div>
}
interface ReceiveFileModalProps {
xfer: Offer;
onFinish?: () => void;
}
interface ReceiveFileModalState {
state: "notstarted" | "started" | "skipped" | "done"
}
export class ReceiveFileModal extends Component<ReceiveFileModalProps, ReceiveFileModalState> {
constructor(props) {
super(props)
this.setState({ state: "notstarted" })
}
accept() {
this.setState({ state: "started" });
let timerID = setInterval(
() => this.forceUpdate(),
100
);
this.props.xfer.accept().then((payloads: any) => {
// All done, so stop updating the progress bar
// and perform a final render.
clearInterval(timerID);
this.forceUpdate();
if (this.state.state != "skipped") {
Browser.save_to_disk(
payloads,
this.props.xfer.get_details().name
);
}
this.setState({ state: "done" })
})
}
finish() {
console.log('finished');
if (this.props.onFinish) this.props.onFinish();
}
progress() {
if (this.state.state !== "notstarted") {
return <Progress min={0} max={this.props.xfer.get_details().size} now={this.props.xfer.get_offset()} />
}
}
skip() {
this.props.xfer.skip()
this.setState({ state: "skipped" })
}
buttons() {
switch (this.state.state) {
case "notstarted":
return <>
<Button priority="primary" clickHandler={() => { this.accept(); }}>Accept</Button>
<Button priority="secondary" clickHandler={() => { this.skip(); }}>Decline</Button>
</>
case "started":
return <>
<Button priority="danger" clickHandler={() => { this.skip(); }}>Cancel</Button>
</>
case "skipped":
return <>
<Button priority="danger" disabled={true}>Skipping...</Button>
</>
}
}
render() {
if (this.state.state != "done")
return <MyModal title="Incoming file"
buttons={this.buttons()}>
Accept <code>{this.props.xfer.get_details().name}</code> ({this.props.xfer.get_details().size.toLocaleString(undefined, { maximumFractionDigits: 0 })} bytes)?
{this.progress()}
</MyModal>
}
}
export class SendFileModal extends Component<SendFileModalProps, SendFileModalState> {
filePickerRef = createRef<HTMLInputElement>();
constructor(props: SendFileModalProps) {
super(props)
this.setState({ state: "notstarted" })
}
buttons() {
switch (this.state.state) {
case "started":
return <>
<Button priority="primary" clickHandler={() => { this.send(); }} disabled={true}>
Sending...
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</Button>
</>
case "notstarted":
return <>
<Button priority="primary" clickHandler={() => { this.send(); }}>Send</Button>
</>
default:
return
}
}
send() {
Browser.send_files(this.props.session,
this.filePickerRef.current!.files, {
on_offer_response: (f, xfer) => { this.setState({ state: "started" }) },
}).then(() => {
this.setState({ state: "done" })
this.props.session.close()
if (this.props.onFinish !== undefined) {
this.props.onFinish();
}
})
.catch(e => console.log(e));
}
render() {
if (this.state.state != "done")
return <MyModal title="Send file(s)"
buttons={this.buttons()}>
<div class="mb-3">
<label for="formFileMultiple" class="form-label">
Remote requested file transfer
</label>
<input ref={this.filePickerRef} class="form-control form-control-sm" type="file" id="formFileMultiple" multiple />
</div>
</MyModal>
}
}
interface SendFileModalProps {
onFinish?: () => void;
session: Session;
}
interface SendFileModalState {
state: "notstarted" | "started" | "done"
currentFile: any
}

View File

@ -1,24 +0,0 @@
{
"compilerOptions": {
"outDir": "./dist/",
"jsx": "react-jsx",
"jsxImportSource": "preact",
"strictNullChecks": true,
"noUnusedLocals" : true,
"noImplicitThis": true,
"alwaysStrict": true,
"declaration": true,
"sourceMap": true,
"target": "esnext",
"module": "commonJS",
"baseUrl": ".",
"types": ["preact", "node"],
"paths": {
"*": ["./typings/*"]
}
},
"exclude": [
"node_modules",
"dist"
]
}

View File

@ -1,57 +0,0 @@
const path = require('path');
const TerserPlugin = require("terser-webpack-plugin");
const LicenseWebpackPlugin = require('license-webpack-plugin').LicenseWebpackPlugin;
var devtool;
if (process.env.DEV === '1') {
devtool = 'inline-source-map';
} else {
devtool = 'source-map';
}
module.exports = {
entry: "./src/main.ts",
entry: {
"gotty": "./src/main.ts",
},
output: {
path: path.resolve(__dirname, '../bindata/static/js/'),
},
devtool: devtool,
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
plugins: [
new LicenseWebpackPlugin()
],
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.scss$/i,
use: ["style-loader", "css-loader", {
loader: "sass-loader",
options: {
sassOptions: {
includePaths: ["node_modules/bootstrap/scss"]
}
}
}
],
},
],
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
};

158
main.go
View File

@ -1,162 +1,6 @@
package main
import (
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"strings"
"syscall"
cli "github.com/urfave/cli/v2"
"github.com/sorenisanerd/gotty/backend/localcommand"
"github.com/sorenisanerd/gotty/pkg/homedir"
"github.com/sorenisanerd/gotty/server"
"github.com/sorenisanerd/gotty/utils"
)
func main() {
app := cli.NewApp()
app.Name = "gotty"
app.Version = Version
app.Usage = "Share your terminal as a web application"
app.HideHelpCommand = true
appOptions := &server.Options{}
if err := utils.ApplyDefaultValues(appOptions); err != nil {
exit(err, 1)
}
backendOptions := &localcommand.Options{}
if err := utils.ApplyDefaultValues(backendOptions); err != nil {
exit(err, 1)
}
cliFlags, flagMappings, err := utils.GenerateFlags(appOptions, backendOptions)
if err != nil {
exit(err, 3)
}
app.Flags = append(
cliFlags,
&cli.StringFlag{
Name: "config",
Value: "~/.gotty",
Usage: "Config file path",
EnvVars: []string{"GOTTY_CONFIG"},
},
)
app.Action = func(c *cli.Context) error {
if c.NArg() == 0 {
msg := "Error: No command given."
cli.ShowAppHelp(c)
exit(fmt.Errorf(msg), 1)
}
configFile := c.String("config")
_, err := os.Stat(homedir.Expand(configFile))
if configFile != "~/.gotty" || !os.IsNotExist(err) {
if err := utils.ApplyConfigFile(configFile, appOptions, backendOptions); err != nil {
exit(err, 2)
}
}
utils.ApplyFlags(cliFlags, flagMappings, c, appOptions, backendOptions)
if appOptions.Quiet {
log.SetFlags(0)
log.SetOutput(io.Discard)
}
if c.IsSet("credential") {
appOptions.EnableBasicAuth = true
}
if c.IsSet("tls-ca-crt") {
appOptions.EnableTLSClientAuth = true
}
err = appOptions.Validate()
if err != nil {
exit(err, 6)
}
args := c.Args()
factory, err := localcommand.NewFactory(args.First(), args.Tail(), backendOptions)
if err != nil {
exit(err, 3)
}
hostname, _ := os.Hostname()
appOptions.TitleVariables = map[string]interface{}{
"command": args.First(),
"argv": args.Tail(),
"hostname": hostname,
}
srv, err := server.New(factory, appOptions)
if err != nil {
exit(err, 3)
}
ctx, cancel := context.WithCancel(context.Background())
gCtx, gCancel := context.WithCancel(context.Background())
log.Printf("GoTTY is starting with command: %s", strings.Join(args.Slice(), " "))
errs := make(chan error, 1)
go func() {
errs <- srv.Run(ctx, server.WithGracefullContext(gCtx))
}()
err = waitSignals(errs, cancel, gCancel)
if err != nil && err != context.Canceled {
fmt.Printf("Error: %s\n", err)
exit(err, 8)
}
return nil
}
app.Run(os.Args)
}
func exit(err error, code int) {
if err != nil {
fmt.Println(err)
}
os.Exit(code)
}
func waitSignals(errs chan error, cancel context.CancelFunc, gracefullCancel context.CancelFunc) error {
sigChan := make(chan os.Signal, 1)
signal.Notify(
sigChan,
syscall.SIGINT,
syscall.SIGTERM,
)
select {
case err := <-errs:
return err
case s := <-sigChan:
switch s {
case syscall.SIGINT:
gracefullCancel()
fmt.Println("C-C to force close")
select {
case err := <-errs:
return err
case <-sigChan:
fmt.Println("Force closing...")
cancel()
return <-errs
}
default:
cancel()
return <-errs
}
}
fmt.Println("Deprecated. Use v1")
}

View File

@ -1,13 +0,0 @@
package homedir
import (
"os"
)
func Expand(path string) string {
if path[0:2] == "~/" {
return os.Getenv("HOME") + path[1:]
} else {
return path
}
}

View File

@ -1,18 +0,0 @@
package randomstring
import (
"crypto/rand"
"math/big"
"strconv"
)
func Generate(length int) string {
const base = 36
size := big.NewInt(base)
n := make([]byte, length)
for i, _ := range n {
c, _ := rand.Int(rand.Reader, size)
n[i] = strconv.FormatInt(c.Int64(), base)[0]
}
return string(n)
}

View File

@ -1,8 +0,0 @@
* Check that the build works, duh.
* Check that "gotty bash" works and that it does not accept input.
* Check that "gotty -w bash" works and that it DOES accept input.
* Check that "gotty -w bash" works and that it DOES accept input.
* Check that cross-compilation works.
* Ensure NEWS is up-to-date
* Ensure contributor list is up-to-date
* Ensure usage is correct in Makefile

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -1,66 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 708.4149 708.41411"
height="708.41412"
width="708.41492"
xml:space="preserve"
id="svg2"
version="1.1"><metadata
id="metadata8"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
id="defs6"><clipPath
id="clipPath18"
clipPathUnits="userSpaceOnUse"><path
id="path16"
d="M 0,2000 H 2000 V 0 H 0 Z" /></clipPath></defs><g
transform="matrix(1.3333333,0,0,-1.3333333,-979.12558,1687.5405)"
id="g10"><g
id="g12"><g
clip-path="url(#clipPath18)"
id="g14"><g
transform="translate(772.1414,1265.6554)"
id="g20"><path
id="path22"
style="fill:#de3c28;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c -20.875,0 -37.797,-16.922 -37.797,-37.797 v -126.348 -25.917 -212.342 L 345.882,0 Z" /></g><g
transform="translate(956.8504,734.3448)"
id="g24"><path
id="path26"
style="fill:#af1419;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 h 260.209 c 26.839,0 48.596,21.757 48.596,48.596 v 275.281 z" /></g><g
transform="translate(1265.6552,1075.5929)"
id="g28"><path
id="path30"
style="fill:#db0918;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v 25.918 126.348 c 0,20.875 -16.922,37.796 -37.796,37.796 h -109.836 l -383.679,-402.404 v -80.31 c 0,-26.839 21.757,-48.596 48.596,-48.596 h 173.91 L 0,-17.371 Z" /></g><g
transform="translate(1169.2147,909.6954)"
id="g32"><path
id="path34"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 h -138.227 c -9.129,0 -16.528,7.4 -16.528,16.529 0,9.128 7.399,16.529 16.528,16.529 H 0 c 9.129,0 16.528,-7.401 16.528,-16.529 C 16.528,7.4 9.129,0 0,0" /></g><g
transform="translate(898.8318,1033.5314)"
id="g36"><path
id="path38"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c 2.86,-0.72 5.65,-1.45 8.37,-2.2 -0.63,-8.56 -7.76,-15.3 -16.479,-15.3 -9.13,0 -16.531,7.4 -16.531,16.53 v 8.54 c 1.861,-0.83 3.72,-1.549 5.601,-2.15 C -15.199,4.18 -8.85,2.37 0,0" /></g><g
transform="translate(907.2527,1150.7814)"
id="g40"><path
id="path42"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v -65.81 c -4.45,1.59 -9.98,2.38 -16.601,2.38 -6.21,0 -11.7,-0.88 -16.46,-2.64 V 0 c 0,9.13 7.401,16.53 16.531,16.53 C -7.4,16.53 0,9.13 0,0" /></g><g
transform="translate(874.1922,868.8272)"
id="g44"><path
id="path46"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v 65.811 c 4.45,-1.59 9.98,-2.38 16.601,-2.38 6.21,0 11.699,0.88 16.46,2.639 V 0 C 33.061,-9.13 25.66,-16.529 16.53,-16.529 7.4,-16.529 0,-9.13 0,0" /></g><g
transform="translate(966.6326,994.1915)"
id="g48"><path
id="path50"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c -3.53,7.28 -8.45,13.3 -14.75,18.06 -6.301,4.76 -13.95,8.8 -22.94,12.14 -6.661,2.47 -13.911,4.78 -21.741,6.94 -2.719,0.75 -5.509,1.48 -8.37,2.2 -8.849,2.37 -15.199,4.18 -19.039,5.42 -1.881,0.6 -3.74,1.32 -5.6,2.15 -1.951,0.87 -3.88,1.87 -5.8,2.99 -3.76,2.19 -6.71,4.81 -8.861,7.85 -2.139,3.05 -3.219,6.67 -3.219,10.86 0,6.75 3.16,12.54 9.46,17.34 2.49,1.9 5.299,3.43 8.42,4.57 4.759,1.76 10.25,2.64 16.46,2.64 6.62,0 12.15,-0.79 16.6,-2.38 3.01,-1.05 5.52,-2.48 7.54,-4.26 5.01,-4.42 9.3,-10.59 12.88,-18.49 2.77,-5.52 5.34,-9.49 7.71,-11.92 2.37,-2.43 5.84,-3.64 10.399,-3.64 5.011,0 9.191,2.02 12.54,6.07 3.351,4.04 5.031,8.59 5.031,13.63 0,5.52 -1.34,11.19 -4.021,17 -2.689,5.8 -6.939,11.35 -12.75,16.63 -5.809,5.28 -13.119,9.52 -21.929,12.71 -5.23,1.89 -11.031,3.22 -17.4,3.99 -4.37,0.53 -9.011,0.79 -13.921,0.79 -6.779,0 -13.159,-0.48 -19.139,-1.45 -7.361,-1.19 -14.121,-3.11 -20.29,-5.76 -11.18,-4.81 -19.72,-11.69 -25.621,-20.63 -5.899,-8.95 -8.849,-19.18 -8.849,-30.7 0,-12.09 2.79,-22.2 8.38,-30.34 5.59,-8.14 13.15,-14.56 22.67,-19.28 9.52,-4.71 21.349,-8.83 35.48,-12.35 10.55,-2.57 18.98,-4.99 25.279,-7.28 6.301,-2.28 11.441,-5.59 15.42,-9.92 3.981,-4.33 5.971,-9.97 5.971,-16.92 0,-8.76 -3.69,-16.06 -11.061,-21.92 -7.379,-5.85 -16.969,-8.78 -28.769,-8.78 -8.59,0 -15.521,1.45 -20.79,4.36 -5.28,2.9 -9.37,6.59 -12.28,11.06 -2.901,4.47 -5.611,10.04 -8.111,16.71 -2.059,5.61 -4.54,9.85 -7.449,12.7 -2.9,2.86 -6.46,4.29 -10.66,4.29 -5.181,0 -9.45,-1.84 -12.811,-5.5 -3.349,-3.66 -5.029,-8.07 -5.029,-13.21 0,-8.85 2.8,-17.96 8.39,-27.34 5.58,-9.38 12.849,-16.87 21.79,-22.49 12.61,-7.8 28.61,-11.7 48.019,-11.7 16.181,0 30.181,2.85 41.981,8.56 11.809,5.71 20.769,13.61 26.9,23.7 6.119,10.09 9.18,21.47 9.18,34.129 C 5.3,-16.21 3.54,-7.28 0,0" /></g></g></g></g></svg>

Before

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

View File

@ -1,13 +0,0 @@
html, body, #terminal {
background: black;
height: 100%;
width: 100%;
padding: 0%;
margin: 0%;
}
.progress .progress-bar {
transition: unset;
transition-duration: 0.1s;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

View File

@ -1,22 +0,0 @@
<!doctype html>
<html>
<head>
<title>{{ .title }}</title>
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<link rel="icon" href="favicon.ico">
<link rel="icon" href="icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./css/index.css" />
<link rel="stylesheet" href="./css/xterm.css" />
<link rel="stylesheet" href="./css/xterm_customize.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="terminal"></div>
<script src="./auth_token.js"></script>
<script src="./config.js"></script>
<script src="./js/gotty.js"></script>
</body>
</html>

View File

@ -1,15 +0,0 @@
{
"short_name": "{{ .title }}",
"name": "{{ .title }}",
"start_url": "./",
"icons": [
{
"src": "./icon_192.png",
"type": "image/png",
"sizes": "192x192"
}
],
"display": "minimal-ui",
"theme_color": "#000000",
"background_color": "#000000"
}

View File

@ -1,19 +0,0 @@
.terminal {
font-family: "DejaVu Sans Mono", "Everson Mono", FreeMono, Menlo, Terminal, monospace, "Apple Symbols";
}
.xterm-overlay {
font-family: "DejaVu Sans Mono", "Everson Mono", FreeMono, Menlo, Terminal, monospace, "Apple Symbols";
border-radius: 15px;
font-size: xx-large;
color: black;
background: white;
opacity: 0.75;
padding: 0.2em 0.5em 0.2em 0.5em;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
user-select: none;
transition: opacity 180ms ease-in;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

View File

@ -1,70 +0,0 @@
package server
import (
"sync"
"time"
)
type counter struct {
duration time.Duration
zeroTimer *time.Timer
wg sync.WaitGroup
connections int
mutex sync.Mutex
}
func newCounter(duration time.Duration) *counter {
zeroTimer := time.NewTimer(duration)
// when duration is 0, drain the expire event here
// so that user will never get the event.
if duration == 0 {
<-zeroTimer.C
}
return &counter{
duration: duration,
zeroTimer: zeroTimer,
}
}
func (counter *counter) add(n int) int {
counter.mutex.Lock()
defer counter.mutex.Unlock()
if counter.duration > 0 {
counter.zeroTimer.Stop()
}
counter.wg.Add(n)
counter.connections += n
return counter.connections
}
func (counter *counter) done() int {
counter.mutex.Lock()
defer counter.mutex.Unlock()
counter.connections--
counter.wg.Done()
if counter.connections == 0 && counter.duration > 0 {
counter.zeroTimer.Reset(counter.duration)
}
return counter.connections
}
func (counter *counter) count() int {
counter.mutex.Lock()
defer counter.mutex.Unlock()
return counter.connections
}
func (counter *counter) wait() {
counter.wg.Wait()
}
func (counter *counter) timer() *time.Timer {
return counter.zeroTimer
}

View File

@ -1,266 +0,0 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"strings"
"sync/atomic"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/sorenisanerd/gotty/webtty"
)
func (server *Server) generateHandleWS(ctx context.Context, cancel context.CancelFunc, counter *counter) http.HandlerFunc {
once := new(int64)
go func() {
select {
case <-counter.timer().C:
cancel()
case <-ctx.Done():
}
}()
return func(w http.ResponseWriter, r *http.Request) {
if server.options.Once {
success := atomic.CompareAndSwapInt64(once, 0, 1)
if !success {
http.Error(w, "Server is shutting down", http.StatusServiceUnavailable)
return
}
}
num := counter.add(1)
closeReason := "unknown reason"
defer func() {
num := counter.done()
log.Printf(
"Connection closed by %s: %s, connections: %d/%d",
closeReason, r.RemoteAddr, num, server.options.MaxConnection,
)
if server.options.Once {
cancel()
}
}()
if int64(server.options.MaxConnection) != 0 {
if num > server.options.MaxConnection {
closeReason = "exceeding max number of connections"
return
}
}
log.Printf("New client connected: %s, connections: %d/%d", r.RemoteAddr, num, server.options.MaxConnection)
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
conn, err := server.upgrader.Upgrade(w, r, nil)
if err != nil {
closeReason = err.Error()
return
}
defer conn.Close()
if server.options.PassHeaders {
err = server.processWSConn(ctx, conn, r.Header)
} else {
err = server.processWSConn(ctx, conn, nil)
}
switch err {
case ctx.Err():
closeReason = "cancelation"
case webtty.ErrSlaveClosed:
closeReason = server.factory.Name()
case webtty.ErrMasterClosed:
closeReason = "client"
default:
closeReason = fmt.Sprintf("an error: %s", err)
}
}
}
func (server *Server) processWSConn(ctx context.Context, conn *websocket.Conn, headers map[string][]string) error {
typ, initLine, err := conn.ReadMessage()
if err != nil {
return errors.Wrapf(err, "failed to authenticate websocket connection")
}
if typ != websocket.TextMessage {
return errors.New("failed to authenticate websocket connection: invalid message type")
}
var init InitMessage
err = json.Unmarshal(initLine, &init)
if err != nil {
return errors.Wrapf(err, "failed to authenticate websocket connection")
}
if init.AuthToken != server.options.Credential {
return errors.New("failed to authenticate websocket connection")
}
queryPath := "?"
if server.options.PermitArguments && init.Arguments != "" {
queryPath = init.Arguments
}
query, err := url.Parse(queryPath)
if err != nil {
return errors.Wrapf(err, "failed to parse arguments")
}
params := query.Query()
var slave Slave
slave, err = server.factory.New(params, headers)
if err != nil {
return errors.Wrapf(err, "failed to create backend")
}
defer slave.Close()
titleVars := server.titleVariables(
[]string{"server", "master", "slave"},
map[string]map[string]interface{}{
"server": server.options.TitleVariables,
"master": map[string]interface{}{
"remote_addr": conn.RemoteAddr(),
},
"slave": slave.WindowTitleVariables(),
},
)
titleBuf := new(bytes.Buffer)
err = server.titleTemplate.Execute(titleBuf, titleVars)
if err != nil {
return errors.Wrapf(err, "failed to fill window title template")
}
opts := []webtty.Option{
webtty.WithWindowTitle(titleBuf.Bytes()),
}
if server.options.PermitWrite {
opts = append(opts, webtty.WithPermitWrite())
}
if server.options.EnableReconnect {
opts = append(opts, webtty.WithReconnect(server.options.ReconnectTime))
}
if server.options.Width > 0 {
opts = append(opts, webtty.WithFixedColumns(server.options.Width))
}
if server.options.Height > 0 {
opts = append(opts, webtty.WithFixedRows(server.options.Height))
}
tty, err := webtty.New(&wsWrapper{conn}, slave, opts...)
if err != nil {
return errors.Wrapf(err, "failed to create webtty")
}
err = tty.Run(ctx)
return err
}
func (server *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
indexVars, err := server.indexVariables(r)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
indexBuf := new(bytes.Buffer)
err = server.indexTemplate.Execute(indexBuf, indexVars)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
w.Write(indexBuf.Bytes())
}
func (server *Server) handleManifest(w http.ResponseWriter, r *http.Request) {
indexVars, err := server.indexVariables(r)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
indexBuf := new(bytes.Buffer)
err = server.manifestTemplate.Execute(indexBuf, indexVars)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
w.Write(indexBuf.Bytes())
}
func (server *Server) indexVariables(r *http.Request) (map[string]interface{}, error) {
titleVars := server.titleVariables(
[]string{"server", "master"},
map[string]map[string]interface{}{
"server": server.options.TitleVariables,
"master": map[string]interface{}{
"remote_addr": r.RemoteAddr,
},
},
)
titleBuf := new(bytes.Buffer)
err := server.titleTemplate.Execute(titleBuf, titleVars)
if err != nil {
return nil, err
}
indexVars := map[string]interface{}{
"title": titleBuf.String(),
}
return indexVars, err
}
func (server *Server) handleAuthToken(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
// @TODO hashing?
w.Write([]byte("var gotty_auth_token = '" + server.options.Credential + "';"))
}
func (server *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
lines := []string{
"var gotty_term = 'xterm';",
"var gotty_ws_query_args = '" + server.options.WSQueryArgs + "';",
}
w.Write([]byte(strings.Join(lines, "\n")))
}
// titleVariables merges maps in a specified order.
// varUnits are name-keyed maps, whose names will be iterated using order.
func (server *Server) titleVariables(order []string, varUnits map[string]map[string]interface{}) map[string]interface{} {
titleVars := map[string]interface{}{}
for _, name := range order {
vars, ok := varUnits[name]
if !ok {
panic("title variable name error")
}
for key, val := range vars {
titleVars[key] = val
}
}
// safe net for conflicted keys
for _, name := range order {
titleVars[name] = varUnits[name]
}
return titleVars
}

View File

@ -1,6 +0,0 @@
package server
type InitMessage struct {
Arguments string `json:"Arguments,omitempty"`
AuthToken string `json:"AuthToken,omitempty"`
}

View File

@ -1,28 +0,0 @@
package server
import (
"net"
)
func listAddresses() (addresses []string) {
ifaces, err := net.Interfaces()
if err != nil {
return []string{}
}
addresses = make([]string, 0, len(ifaces))
for _, iface := range ifaces {
ifAddrs, _ := iface.Addrs()
for _, ifAddr := range ifAddrs {
switch v := ifAddr.(type) {
case *net.IPNet:
addresses = append(addresses, v.IP.String())
case *net.IPAddr:
addresses = append(addresses, v.IP.String())
}
}
}
return addresses
}

View File

@ -1,23 +0,0 @@
package server
import (
"bufio"
"net"
"net/http"
)
type logResponseWriter struct {
http.ResponseWriter
status int
}
func (w *logResponseWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *logResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hj, _ := w.ResponseWriter.(http.Hijacker)
w.status = http.StatusSwitchingProtocols
return hj.Hijack()
}

View File

@ -1,51 +0,0 @@
package server
import (
"encoding/base64"
"log"
"net/http"
"strings"
)
func (server *Server) wrapLogger(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rw := &logResponseWriter{w, 200}
handler.ServeHTTP(rw, r)
log.Printf("%s %d %s %s", r.RemoteAddr, rw.status, r.Method, r.URL.Path)
})
}
func (server *Server) wrapHeaders(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// todo add version
w.Header().Set("Server", "GoTTY")
handler.ServeHTTP(w, r)
})
}
func (server *Server) wrapBasicAuth(handler http.Handler, credential string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(token) != 2 || strings.ToLower(token[0]) != "basic" {
w.Header().Set("WWW-Authenticate", `Basic realm="GoTTY"`)
http.Error(w, "Bad Request", http.StatusUnauthorized)
return
}
payload, err := base64.StdEncoding.DecodeString(token[1])
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
if credential != string(payload) {
w.Header().Set("WWW-Authenticate", `Basic realm="GoTTY"`)
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
log.Printf("Basic Authentication Succeeded: %s", r.RemoteAddr)
handler.ServeHTTP(w, r)
})
}

View File

@ -1,45 +0,0 @@
package server
import (
"github.com/pkg/errors"
)
type Options struct {
Address string `hcl:"address" flagName:"address" flagSName:"a" flagDescribe:"IP address to listen" default:"0.0.0.0"`
Port string `hcl:"port" flagName:"port" flagSName:"p" flagDescribe:"Port number to liten" default:"8080"`
Path string `hcl:"path" flagName:"path" flagSName:"m" flagDescribe:"Base path" default:"/"`
PermitWrite bool `hcl:"permit_write" flagName:"permit-write" flagSName:"w" flagDescribe:"Permit clients to write to the TTY (BE CAREFUL)" default:"false"`
EnableBasicAuth bool `hcl:"enable_basic_auth" default:"false"`
Credential string `hcl:"credential" flagName:"credential" flagSName:"c" flagDescribe:"Credential for Basic Authentication (ex: user:pass, default disabled)" default:""`
EnableRandomUrl bool `hcl:"enable_random_url" flagName:"random-url" flagSName:"r" flagDescribe:"Add a random string to the URL" default:"false"`
RandomUrlLength int `hcl:"random_url_length" flagName:"random-url-length" flagDescribe:"Random URL length" default:"8"`
EnableTLS bool `hcl:"enable_tls" flagName:"tls" flagSName:"t" flagDescribe:"Enable TLS/SSL" default:"false"`
TLSCrtFile string `hcl:"tls_crt_file" flagName:"tls-crt" flagDescribe:"TLS/SSL certificate file path" default:"~/.gotty.crt"`
TLSKeyFile string `hcl:"tls_key_file" flagName:"tls-key" flagDescribe:"TLS/SSL key file path" default:"~/.gotty.key"`
EnableTLSClientAuth bool `hcl:"enable_tls_client_auth" default:"false"`
TLSCACrtFile string `hcl:"tls_ca_crt_file" flagName:"tls-ca-crt" flagDescribe:"TLS/SSL CA certificate file for client certifications" default:"~/.gotty.ca.crt"`
IndexFile string `hcl:"index_file" flagName:"index" flagDescribe:"Custom index.html file" default:""`
TitleFormat string `hcl:"title_format" flagName:"title-format" flagSName:"" flagDescribe:"Title format of browser window" default:"{{ .command }}@{{ .hostname }}"`
EnableReconnect bool `hcl:"enable_reconnect" flagName:"reconnect" flagDescribe:"Enable reconnection" default:"false"`
ReconnectTime int `hcl:"reconnect_time" flagName:"reconnect-time" flagDescribe:"Time to reconnect" default:"10"`
MaxConnection int `hcl:"max_connection" flagName:"max-connection" flagDescribe:"Maximum connection to gotty" default:"0"`
Once bool `hcl:"once" flagName:"once" flagDescribe:"Accept only one client and exit on disconnection" default:"false"`
Timeout int `hcl:"timeout" flagName:"timeout" flagDescribe:"Timeout seconds for waiting a client(0 to disable)" default:"0"`
PermitArguments bool `hcl:"permit_arguments" flagName:"permit-arguments" flagDescribe:"Permit clients to send command line arguments in URL (e.g. http://example.com:8080/?arg=AAA&arg=BBB)" default:"false"`
PassHeaders bool `hcl:"pass_headers" flagName:"pass-headers" flagDescribe:"Pass HTTP request headers as environment variables (e.g. Cookie becomes HTTP_COOKIE)" default:"false"`
Width int `hcl:"width" flagName:"width" flagDescribe:"Static width of the screen, 0(default) means dynamically resize" default:"0"`
Height int `hcl:"height" flagName:"height" flagDescribe:"Static height of the screen, 0(default) means dynamically resize" default:"0"`
WSOrigin string `hcl:"ws_origin" flagName:"ws-origin" flagDescribe:"A regular expression that matches origin URLs to be accepted by WebSocket. No cross origin requests are acceptable by default" default:""`
WSQueryArgs string `hcl:"ws_query_args" flagName:"ws-query-args" flagDescribe:"Querystring arguments to append to the websocket instantiation" default:""`
EnableWebGL bool `hcl:"enable_webgl" flagName:"enable-webgl" flagDescribe:"Enable WebGL renderer" default:"true"`
Quiet bool `hcl:"quiet" flagName:"quiet" flagDescribe:"Don't log" default:"false"`
TitleVariables map[string]interface{}
}
func (options *Options) Validate() error {
if options.EnableTLSClientAuth && !options.EnableTLS {
return errors.New("TLS client authentication is enabled, but TLS is not enabled")
}
return nil
}

View File

@ -1,21 +0,0 @@
package server
import (
"context"
)
// RunOptions holds a set of configurations for Server.Run().
type RunOptions struct {
gracefullCtx context.Context
}
// RunOption is an option of Server.Run().
type RunOption func(*RunOptions)
// WithGracefullContext accepts a context to shutdown a Server
// with care for existing client connections.
func WithGracefullContext(ctx context.Context) RunOption {
return func(options *RunOptions) {
options.gracefullCtx = ctx
}
}

View File

@ -1,269 +0,0 @@
package server
import (
"context"
"crypto/tls"
"crypto/x509"
"html/template"
"io/fs"
"log"
"net"
"net/http"
"os"
"regexp"
"strings"
noesctmpl "text/template"
"time"
"github.com/NYTimes/gziphandler"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/sorenisanerd/gotty/bindata"
"github.com/sorenisanerd/gotty/pkg/homedir"
"github.com/sorenisanerd/gotty/pkg/randomstring"
"github.com/sorenisanerd/gotty/webtty"
)
// Server provides a webtty HTTP endpoint.
type Server struct {
factory Factory
options *Options
upgrader *websocket.Upgrader
indexTemplate *template.Template
titleTemplate *noesctmpl.Template
manifestTemplate *template.Template
}
// New creates a new instance of Server.
// Server will use the New() of the factory provided to handle each request.
func New(factory Factory, options *Options) (*Server, error) {
indexData, err := bindata.Fs.ReadFile("static/index.html")
if err != nil {
panic("index not found") // must be in bindata
}
if options.IndexFile != "" {
path := homedir.Expand(options.IndexFile)
indexData, err = os.ReadFile(path)
if err != nil {
return nil, errors.Wrapf(err, "failed to read custom index file at `%s`", path)
}
}
indexTemplate, err := template.New("index").Parse(string(indexData))
if err != nil {
panic("index template parse failed") // must be valid
}
manifestData, err := bindata.Fs.ReadFile("static/manifest.json")
if err != nil {
panic("manifest not found") // must be in bindata
}
manifestTemplate, err := template.New("manifest").Parse(string(manifestData))
if err != nil {
panic("manifest template parse failed") // must be valid
}
titleTemplate, err := noesctmpl.New("title").Parse(options.TitleFormat)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse window title format `%s`", options.TitleFormat)
}
var originChekcer func(r *http.Request) bool
if options.WSOrigin != "" {
matcher, err := regexp.Compile(options.WSOrigin)
if err != nil {
return nil, errors.Wrapf(err, "failed to compile regular expression of Websocket Origin: %s", options.WSOrigin)
}
originChekcer = func(r *http.Request) bool {
return matcher.MatchString(r.Header.Get("Origin"))
}
}
return &Server{
factory: factory,
options: options,
upgrader: &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
Subprotocols: webtty.Protocols,
CheckOrigin: originChekcer,
},
indexTemplate: indexTemplate,
titleTemplate: titleTemplate,
manifestTemplate: manifestTemplate,
}, nil
}
// Run starts the main process of the Server.
// The cancelation of ctx will shutdown the server immediately with aborting
// existing connections. Use WithGracefullContext() to support gracefull shutdown.
func (server *Server) Run(ctx context.Context, options ...RunOption) error {
cctx, cancel := context.WithCancel(ctx)
opts := &RunOptions{gracefullCtx: context.Background()}
for _, opt := range options {
opt(opts)
}
counter := newCounter(time.Duration(server.options.Timeout) * time.Second)
path := server.options.Path
if server.options.EnableRandomUrl {
path = "/" + randomstring.Generate(server.options.RandomUrlLength) + "/"
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
if !strings.HasSuffix(path, "/") {
path = path + "/"
}
handlers := server.setupHandlers(cctx, cancel, path, counter)
srv, err := server.setupHTTPServer(handlers)
if err != nil {
return errors.Wrapf(err, "failed to setup an HTTP server")
}
if server.options.PermitWrite {
log.Printf("Permitting clients to write input to the PTY.")
}
if server.options.Once {
log.Printf("Once option is provided, accepting only one client")
}
if server.options.Port == "0" {
log.Printf("Port number configured to `0`, choosing a random port")
}
hostPort := net.JoinHostPort(server.options.Address, server.options.Port)
listener, err := net.Listen("tcp", hostPort)
if err != nil {
return errors.Wrapf(err, "failed to listen at `%s`", hostPort)
}
scheme := "http"
if server.options.EnableTLS {
scheme = "https"
}
host, port, _ := net.SplitHostPort(listener.Addr().String())
log.Printf("HTTP server is listening at: %s", scheme+"://"+net.JoinHostPort(host, port)+path)
if server.options.Address == "0.0.0.0" {
for _, address := range listAddresses() {
log.Printf("Alternative URL: %s", scheme+"://"+net.JoinHostPort(address, port)+path)
}
}
srvErr := make(chan error, 1)
go func() {
if server.options.EnableTLS {
crtFile := homedir.Expand(server.options.TLSCrtFile)
keyFile := homedir.Expand(server.options.TLSKeyFile)
log.Printf("TLS crt file: " + crtFile)
log.Printf("TLS key file: " + keyFile)
err = srv.ServeTLS(listener, crtFile, keyFile)
} else {
err = srv.Serve(listener)
}
if err != nil {
srvErr <- err
}
}()
go func() {
select {
case <-opts.gracefullCtx.Done():
srv.Shutdown(context.Background())
case <-cctx.Done():
}
}()
select {
case err = <-srvErr:
if err == http.ErrServerClosed { // by gracefull ctx
err = nil
} else {
cancel()
}
case <-cctx.Done():
srv.Close()
err = cctx.Err()
}
conn := counter.count()
if conn > 0 {
log.Printf("Waiting for %d connections to be closed", conn)
}
counter.wait()
return err
}
func (server *Server) setupHandlers(ctx context.Context, cancel context.CancelFunc, pathPrefix string, counter *counter) http.Handler {
fs, err := fs.Sub(bindata.Fs, "static")
if err != nil {
log.Fatalf("failed to open static/ subdirectory of embedded filesystem: %v", err)
}
staticFileHandler := http.FileServer(http.FS(fs))
var siteMux = http.NewServeMux()
siteMux.HandleFunc(pathPrefix, server.handleIndex)
siteMux.Handle(pathPrefix+"js/", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"favicon.ico", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"icon.svg", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"css/", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"icon_192.png", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.HandleFunc(pathPrefix+"manifest.json", server.handleManifest)
siteMux.HandleFunc(pathPrefix+"auth_token.js", server.handleAuthToken)
siteMux.HandleFunc(pathPrefix+"config.js", server.handleConfig)
siteHandler := http.Handler(siteMux)
if server.options.EnableBasicAuth {
log.Printf("Using Basic Authentication")
siteHandler = server.wrapBasicAuth(siteHandler, server.options.Credential)
}
withGz := gziphandler.GzipHandler(server.wrapHeaders(siteHandler))
siteHandler = server.wrapLogger(withGz)
wsMux := http.NewServeMux()
wsMux.Handle("/", siteHandler)
wsMux.HandleFunc(pathPrefix+"ws", server.generateHandleWS(ctx, cancel, counter))
siteHandler = http.Handler(wsMux)
return siteHandler
}
func (server *Server) setupHTTPServer(handler http.Handler) (*http.Server, error) {
srv := &http.Server{
Handler: handler,
}
if server.options.EnableTLSClientAuth {
tlsConfig, err := server.tlsConfig()
if err != nil {
return nil, errors.Wrapf(err, "failed to setup TLS configuration")
}
srv.TLSConfig = tlsConfig
}
return srv, nil
}
func (server *Server) tlsConfig() (*tls.Config, error) {
caFile := homedir.Expand(server.options.TLSCACrtFile)
caCert, err := os.ReadFile(caFile)
if err != nil {
return nil, errors.New("could not open CA crt file " + caFile)
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCert) {
return nil, errors.New("could not parse CA crt file data in " + caFile)
}
tlsConfig := &tls.Config{
ClientCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
}
return tlsConfig, nil
}

View File

@ -1,17 +0,0 @@
package server
import (
"github.com/sorenisanerd/gotty/webtty"
)
// Slave is webtty.Slave with some additional methods.
type Slave interface {
webtty.Slave
Close() error
}
type Factory interface {
Name() string
New(params map[string][]string, headers map[string][]string) (Slave, error)
}

View File

@ -1,41 +0,0 @@
package server
import (
"io"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
type wsWrapper struct {
*websocket.Conn
}
func (wsw *wsWrapper) Write(p []byte) (n int, err error) {
writer, err := wsw.Conn.NextWriter(websocket.TextMessage)
if err != nil {
return 0, err
}
defer writer.Close()
return writer.Write(p)
}
func (wsw *wsWrapper) Read(p []byte) (n int, err error) {
for {
msgType, reader, err := wsw.Conn.NextReader()
if err != nil {
return 0, err
}
if msgType != websocket.TextMessage {
continue
}
b, err := io.ReadAll(reader)
if len(b) > len(p) {
return 0, errors.Wrapf(err, "Client message exceeded buffer size")
}
n = copy(p, b)
return n, err
}
}

View File

@ -1,41 +0,0 @@
package utils
import (
"fmt"
"github.com/fatih/structs"
"reflect"
"strconv"
)
func ApplyDefaultValues(struct_ interface{}) (err error) {
o := structs.New(struct_)
for _, field := range o.Fields() {
defaultValue := field.Tag("default")
if defaultValue == "" {
continue
}
var val interface{}
switch field.Kind() {
case reflect.String:
val = defaultValue
case reflect.Bool:
if defaultValue == "true" {
val = true
} else if defaultValue == "false" {
val = false
} else {
return fmt.Errorf("invalid bool expression: %v, use true/false", defaultValue)
}
case reflect.Int:
val, err = strconv.Atoi(defaultValue)
if err != nil {
return err
}
default:
val = field.Value()
}
field.Set(val)
}
return nil
}

View File

@ -1,128 +0,0 @@
package utils
import (
"log"
"os"
"reflect"
"strings"
"github.com/fatih/structs"
"github.com/urfave/cli/v2"
"github.com/yudai/hcl"
"github.com/sorenisanerd/gotty/pkg/homedir"
)
func GenerateFlags(options ...interface{}) (flags []cli.Flag, mappings map[string]string, err error) {
mappings = make(map[string]string)
for _, struct_ := range options {
o := structs.New(struct_)
for _, field := range o.Fields() {
flagName := field.Tag("flagName")
if flagName == "" {
continue
}
envName := "GOTTY_" + strings.ToUpper(strings.Join(strings.Split(flagName, "-"), "_"))
mappings[flagName] = field.Name()
flagShortName := field.Tag("flagSName")
var aliases []string
if flagShortName != "" {
aliases = []string{flagShortName}
}
flagDescription := field.Tag("flagDescribe")
switch field.Kind() {
case reflect.String:
flags = append(flags, &cli.StringFlag{
Name: flagName,
Value: field.Value().(string),
Usage: flagDescription,
EnvVars: []string{envName},
Aliases: aliases,
})
case reflect.Bool:
flags = append(flags, &cli.BoolFlag{
Name: flagName,
Usage: flagDescription,
EnvVars: []string{envName},
Aliases: aliases,
DefaultText: field.Tag("default"),
})
case reflect.Int:
flags = append(flags, &cli.IntFlag{
Name: flagName,
Value: field.Value().(int),
Usage: flagDescription,
EnvVars: []string{envName},
Aliases: aliases,
})
}
}
}
return
}
func ApplyFlags(
flags []cli.Flag,
mappingHint map[string]string,
c *cli.Context,
options ...interface{},
) {
objects := make([]*structs.Struct, len(options))
for i, struct_ := range options {
objects[i] = structs.New(struct_)
}
for flagName, fieldName := range mappingHint {
if !c.IsSet(flagName) {
continue
}
var field *structs.Field
var ok bool
for _, o := range objects {
field, ok = o.FieldOk(fieldName)
if ok {
break
}
}
if field == nil {
continue
}
var val interface{}
switch field.Kind() {
case reflect.String:
val = c.String(flagName)
case reflect.Bool:
val = c.Bool(flagName)
case reflect.Int:
val = c.Int(flagName)
}
field.Set(val)
}
}
func ApplyConfigFile(filePath string, options ...interface{}) error {
filePath = homedir.Expand(filePath)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return err
}
fileString := []byte{}
log.Printf("Loading config file at: %s", filePath)
fileString, err := os.ReadFile(filePath)
if err != nil {
return err
}
for _, object := range options {
if err := hcl.Decode(object, string(fileString)); err != nil {
return err
}
}
return nil
}

View File

@ -1,3 +0,0 @@
package main
var Version = "unknown_version"

View File

@ -1,19 +0,0 @@
package webtty
type Decoder interface {
Decode(dst, src []byte) (int, error)
}
type Encoder interface {
Encode(dst, src []byte) (int, error)
}
type NullCodec struct{}
func (NullCodec) Encode(dst, src []byte) (int, error) {
return copy(dst, src), nil
}
func (NullCodec) Decode(dst, src []byte) (int, error) {
return copy(dst, src), nil
}

View File

@ -1,3 +0,0 @@
// Package webtty provides a protocl and an implementation to
// controll terminals thorough networks.
package webtty

View File

@ -1,13 +0,0 @@
package webtty
import (
"errors"
)
var (
// ErrSlaveClosed indicates the function has exited by the slave
ErrSlaveClosed = errors.New("slave closed")
// ErrSlaveClosed is returned when the slave connection is closed.
ErrMasterClosed = errors.New("master closed")
)

View File

@ -1,8 +0,0 @@
package webtty
import (
"io"
)
// Master represents a PTY master, usually it's a websocket connection.
type Master io.ReadWriter

View File

@ -1,35 +0,0 @@
package webtty
// Protocols defines the name of this protocol,
// which is supposed to be used to the subprotocol of Websockt streams.
var Protocols = []string{"webtty"}
const (
// Unknown message type, maybe sent by a bug
UnknownInput = '0'
// User input typically from a keyboard
Input = '1'
// Ping to the server
Ping = '2'
// Notify that the browser size has been changed
ResizeTerminal = '3'
// Change encoding
SetEncoding = '4'
)
const (
// Unknown message type, maybe set by a bug
UnknownOutput = '0'
// Normal output to the terminal
Output = '1'
// Pong to the browser
Pong = '2'
// Set window title of the terminal
SetWindowTitle = '3'
// Set terminal preference
SetPreferences = '4'
// Make terminal to reconnect
SetReconnect = '5'
// Set the input buffer size
SetBufferSize = '6'
)

View File

@ -1,62 +0,0 @@
package webtty
import (
"encoding/json"
"github.com/pkg/errors"
)
// Option is an option for WebTTY.
type Option func(*WebTTY) error
// WithPermitWrite sets a WebTTY to accept input from slaves.
func WithPermitWrite() Option {
return func(wt *WebTTY) error {
wt.permitWrite = true
return nil
}
}
// WithFixedColumns sets a fixed width to TTY master.
func WithFixedColumns(columns int) Option {
return func(wt *WebTTY) error {
wt.columns = columns
return nil
}
}
// WithFixedRows sets a fixed height to TTY master.
func WithFixedRows(rows int) Option {
return func(wt *WebTTY) error {
wt.rows = rows
return nil
}
}
// WithWindowTitle sets the default window title of the session
func WithWindowTitle(windowTitle []byte) Option {
return func(wt *WebTTY) error {
wt.windowTitle = windowTitle
return nil
}
}
// WithReconnect enables reconnection on the master side.
func WithReconnect(timeInSeconds int) Option {
return func(wt *WebTTY) error {
wt.reconnect = timeInSeconds
return nil
}
}
// WithMasterPreferences sets an optional configuration of master.
func WithMasterPreferences(preferences interface{}) Option {
return func(wt *WebTTY) error {
prefs, err := json.Marshal(preferences)
if err != nil {
return errors.Wrapf(err, "failed to marshal preferences as JSON")
}
wt.masterPrefs = prefs
return nil
}
}

View File

@ -1,17 +0,0 @@
package webtty
import (
"io"
)
// Slave represents a PTY slave, typically it's a local command.
type Slave interface {
io.ReadWriter
// WindowTitleVariables returns any values that can be used to fill out
// the title of a terminal.
WindowTitleVariables() map[string]interface{}
// ResizeTerminal sets a new size of the terminal.
ResizeTerminal(columns int, rows int) error
}

View File

@ -1,246 +0,0 @@
package webtty
import (
"context"
"encoding/base64"
"encoding/json"
"sync"
"github.com/pkg/errors"
)
// WebTTY bridges a PTY slave and its PTY master.
// To support text-based streams and side channel commands such as
// terminal resizing, WebTTY uses an original protocol.
type WebTTY struct {
// PTY Master, which probably a connection to browser
masterConn Master
// PTY Slave
slave Slave
windowTitle []byte
permitWrite bool
columns int
rows int
reconnect int // in seconds
masterPrefs []byte
decoder Decoder
bufferSize int
writeMutex sync.Mutex
}
// New creates a new instance of WebTTY.
// masterConn is a connection to the PTY master,
// typically it's a websocket connection to a client.
// slave is a PTY slave such as a local command with a PTY.
func New(masterConn Master, slave Slave, options ...Option) (*WebTTY, error) {
wt := &WebTTY{
masterConn: masterConn,
slave: slave,
permitWrite: false,
columns: 0,
rows: 0,
bufferSize: 1024,
decoder: &NullCodec{},
}
for _, option := range options {
option(wt)
}
return wt, nil
}
// Run starts the main process of the WebTTY.
// This method blocks until the context is canceled.
// Note that the master and slave are left intact even
// after the context is canceled. Closing them is caller's
// responsibility.
// If the connection to one end gets closed, returns ErrSlaveClosed or ErrMasterClosed.
func (wt *WebTTY) Run(ctx context.Context) error {
err := wt.sendInitializeMessage()
if err != nil {
return errors.Wrapf(err, "failed to send initializing message")
}
errs := make(chan error, 2)
go func() {
errs <- func() error {
buffer := make([]byte, wt.bufferSize)
for {
//base64 length
effectiveBufferSize := wt.bufferSize - 1
//max raw data length
maxChunkSize := int(effectiveBufferSize/4) * 3
n, err := wt.slave.Read(buffer[:maxChunkSize])
if err != nil {
return ErrSlaveClosed
}
err = wt.handleSlaveReadEvent(buffer[:n])
if err != nil {
return err
}
}
}()
}()
go func() {
errs <- func() error {
buffer := make([]byte, wt.bufferSize)
for {
n, err := wt.masterConn.Read(buffer)
if err != nil {
return ErrMasterClosed
}
err = wt.handleMasterReadEvent(buffer[:n])
if err != nil {
return err
}
}
}()
}()
select {
case <-ctx.Done():
err = ctx.Err()
case err = <-errs:
}
return err
}
func (wt *WebTTY) sendInitializeMessage() error {
err := wt.masterWrite(append([]byte{SetWindowTitle}, wt.windowTitle...))
if err != nil {
return errors.Wrapf(err, "failed to send window title")
}
bufSizeMsg, _ := json.Marshal(wt.bufferSize)
err = wt.masterWrite(append([]byte{SetBufferSize}, bufSizeMsg...))
if err != nil {
return errors.Wrapf(err, "failed to send buffer size")
}
if wt.reconnect > 0 {
reconnect, _ := json.Marshal(wt.reconnect)
err := wt.masterWrite(append([]byte{SetReconnect}, reconnect...))
if err != nil {
return errors.Wrapf(err, "failed to set reconnect")
}
}
if wt.masterPrefs != nil {
err := wt.masterWrite(append([]byte{SetPreferences}, wt.masterPrefs...))
if err != nil {
return errors.Wrapf(err, "failed to set preferences")
}
}
return nil
}
func (wt *WebTTY) handleSlaveReadEvent(data []byte) error {
safeMessage := base64.StdEncoding.EncodeToString(data)
err := wt.masterWrite(append([]byte{Output}, []byte(safeMessage)...))
if err != nil {
return errors.Wrapf(err, "failed to send message to master")
}
return nil
}
func (wt *WebTTY) masterWrite(data []byte) error {
wt.writeMutex.Lock()
defer wt.writeMutex.Unlock()
_, err := wt.masterConn.Write(data)
if err != nil {
return errors.Wrapf(err, "failed to write to master")
}
return nil
}
func (wt *WebTTY) handleMasterReadEvent(data []byte) error {
if len(data) == 0 {
return errors.New("unexpected zero length read from master")
}
switch data[0] {
case Input:
if !wt.permitWrite {
return nil
}
if len(data) <= 1 {
return nil
}
var decodedBuffer = make([]byte, len(data))
n, err := wt.decoder.Decode(decodedBuffer, data[1:])
if err != nil {
return errors.Wrapf(err, "failed to decode received data")
}
_, err = wt.slave.Write(decodedBuffer[:n])
if err != nil {
return errors.Wrapf(err, "failed to write received data to slave")
}
case Ping:
err := wt.masterWrite([]byte{Pong})
if err != nil {
return errors.Wrapf(err, "failed to return Pong message to master")
}
case SetEncoding:
switch string(data[1:]) {
case "base64":
wt.decoder = base64.StdEncoding
case "null":
wt.decoder = NullCodec{}
}
case ResizeTerminal:
if wt.columns != 0 && wt.rows != 0 {
break
}
if len(data) <= 1 {
return errors.New("received malformed remote command for terminal resize: empty payload")
}
var args argResizeTerminal
err := json.Unmarshal(data[1:], &args)
if err != nil {
return errors.Wrapf(err, "received malformed data for terminal resize")
}
rows := wt.rows
if rows == 0 {
rows = int(args.Rows)
}
columns := wt.columns
if columns == 0 {
columns = int(args.Columns)
}
wt.slave.ResizeTerminal(columns, rows)
default:
return errors.Errorf("unknown message type `%c`", data[0])
}
return nil
}
type argResizeTerminal struct {
Columns float64
Rows float64
}

View File

@ -1,284 +0,0 @@
package webtty
import (
"bytes"
"context"
"encoding/base64"
"io"
"sync"
"testing"
)
func TestInitialization(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
mMaster, _, _, cancel := prepareSUT(t, &wg)
defer cancel()
// Check that the initialization happens as expected
checkNextMsgType(t, mMaster.gottyToMasterReader, SetWindowTitle)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetBufferSize)
}
func TestInitializationWithPreferences(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
mMaster, _, _, cancel := prepareSUT(t, &wg, WithMasterPreferences(map[string]string{"foo": "bar"}))
defer cancel()
// Check that the initialization happens as expected
checkNextMsgType(t, mMaster.gottyToMasterReader, SetWindowTitle)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetBufferSize)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetPreferences)
}
func TestInitializationWithReconnect(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
mMaster, _, _, cancel := prepareSUT(t, &wg, WithReconnect(10))
defer cancel()
// Check that the initialization happens as expected
checkNextMsgType(t, mMaster.gottyToMasterReader, SetWindowTitle)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetBufferSize)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetReconnect)
}
func TestWriteFromSlaveCommand(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
mMaster, mSlave, _, cancel := prepareSUT(t, &wg)
defer cancel()
// Check that the initialization happens as expected
checkNextMsgType(t, mMaster.gottyToMasterReader, SetWindowTitle)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetBufferSize)
// Simulate the slave (the process being run by GoTTY)
// echoing "foobar"
message := []byte("foobar")
mSlave.slaveToGottyWriter.Write(message)
// And then make sure it makes it way to the client
// through the websocket as an output message
buf := make([]byte, 1024)
n, err := mMaster.gottyToMasterReader.Read(buf)
if err != nil {
t.Fatalf("Unexpected error from Read(): %s", err)
}
if buf[0] != Output {
t.Fatalf("Unexpected message type `%c`", buf[0])
}
// Decode it and make sure it's intact
decoded := make([]byte, 1024)
n, err = base64.StdEncoding.Decode(decoded, buf[1:n])
if err != nil {
t.Fatalf("Unexpected error from Decode(): %s", err)
}
if !bytes.Equal(decoded[:n], message) {
t.Fatalf("Unexpected message received: `%s`", decoded[:n])
}
cancel()
wg.Wait()
}
func TestWriteFromFrontend(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
mMaster, mSlave, _, cancel := prepareSUT(t, &wg, WithPermitWrite())
defer cancel()
// Absorb initialization messages
checkNextMsgType(t, mMaster.gottyToMasterReader, SetWindowTitle)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetBufferSize)
// simulate input from frontend...
message := []byte("1hello\n") // line buffered canonical mode
mMaster.masterToGottyWriter.Write(message)
// ...and make sure it makes it through to the slave intact
readBuf := make([]byte, 1024)
n, err := mSlave.gottyToSlaveReader.Read(readBuf)
if err != nil {
t.Fatalf("Unexpected error from Write(): %s", err)
}
if !bytes.Equal(readBuf[:n], message[1:]) {
t.Fatalf("Unexpected message received: `%s`", readBuf[:n])
}
}
func TestPing(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
mMaster, _, _, cancel := prepareSUT(t, &wg)
defer cancel()
// Absorb initialization messages
checkNextMsgType(t, mMaster.gottyToMasterReader, SetWindowTitle)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetBufferSize)
// ping
message := []byte("2\n") // line buffered canonical mode
n, err := mMaster.masterToGottyWriter.Write(message)
if err != nil {
t.Fatalf("Unexpected error from Write(): %s", err)
}
if n != len(message) {
t.Fatalf("Write() accepted `%d` for message `%s`", n, message)
}
readBuf := make([]byte, 1024)
n, err = mMaster.gottyToMasterReader.Read(readBuf)
if err != nil {
t.Fatalf("Unexpected error from Read(): %s", err)
}
if !bytes.Equal(readBuf[:n], []byte{'2'}) {
t.Fatalf("Unexpected message received: `%s`", readBuf[:n])
}
cancel()
wg.Wait()
}
func TestResizeTerminal(t *testing.T) {
var wg sync.WaitGroup
defer wg.Wait()
mMaster, mSlave, _, cancel := prepareSUT(t, &wg)
defer cancel()
// Absorb initialization messages
checkNextMsgType(t, mMaster.gottyToMasterReader, SetWindowTitle)
checkNextMsgType(t, mMaster.gottyToMasterReader, SetBufferSize)
message := []byte(`3{"Columns": 1234, "Rows": 2345}` + "\n") // line buffered canonical mode
mSlave.wg.Add(1)
n, err := mMaster.masterToGottyWriter.Write(message)
if err != nil {
t.Fatalf("Unexpected error from Write(): %s", err)
}
if n != len(message) {
t.Fatalf("Write() accepted `%d` for message `%s`", n, message)
}
mSlave.wg.Wait()
if mSlave.columns != 1234 {
t.Fatalf("Columns not set correctly. Expected %v, got %v", 1234, mSlave.columns)
}
if mSlave.rows != 2345 {
t.Fatalf("Rows not set correctly. Expected %v, got %v", 2345, mSlave.columns)
}
cancel()
wg.Wait()
}
type mockMaster struct {
gottyToMasterReader *io.PipeReader
gottyToMasterWriter *io.PipeWriter
masterToGottyReader *io.PipeReader
masterToGottyWriter *io.PipeWriter
}
type mockSlave struct {
gottyToSlaveReader *io.PipeReader
gottyToSlaveWriter *io.PipeWriter
slaveToGottyReader *io.PipeReader
slaveToGottyWriter *io.PipeWriter
wg sync.WaitGroup
columns, rows int
}
func prepareSUT(t *testing.T, wg *sync.WaitGroup, options ...Option) (*mockMaster, *mockSlave, *WebTTY, context.CancelFunc) {
mMaster := newMockMaster()
mSlave := newMockSlave()
dt, err := New(mMaster, mSlave, options...)
if err != nil {
t.Fatalf("Unexpected error from New(): %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
wg.Add(1)
go func() {
wg.Done()
dt.Run(ctx)
}()
return mMaster, mSlave, dt, cancel
}
func checkNextMsgType(t *testing.T, reader io.Reader, expected byte) {
msgType, _ := nextMsg(t, reader)
if msgType != expected {
t.Fatalf("Unexpected message type `%c`", msgType)
}
}
func nextMsg(t *testing.T, reader io.Reader) (byte, []byte) {
buf := make([]byte, 1024)
_, err := reader.Read(buf)
if err != nil {
t.Fatalf("unexpected error %v", err)
}
return buf[0], buf[1:]
}
func newMockMaster() *mockMaster {
rv := &mockMaster{}
rv.gottyToMasterReader, rv.gottyToMasterWriter = io.Pipe()
rv.masterToGottyReader, rv.masterToGottyWriter = io.Pipe()
return rv
}
func (mm *mockMaster) close() {
mm.masterToGottyWriter.Close()
mm.gottyToMasterReader.Close()
}
func (mm *mockMaster) Read(buf []byte) (int, error) {
return mm.masterToGottyReader.Read(buf)
}
func (mm *mockMaster) Write(buf []byte) (int, error) {
return mm.gottyToMasterWriter.Write(buf)
}
func newMockSlave() *mockSlave {
rv := &mockSlave{}
rv.gottyToSlaveReader, rv.gottyToSlaveWriter = io.Pipe()
rv.slaveToGottyReader, rv.slaveToGottyWriter = io.Pipe()
return rv
}
func (ms *mockSlave) close() {
ms.slaveToGottyWriter.Close()
ms.gottyToSlaveReader.Close()
}
func (ms *mockSlave) Read(buf []byte) (int, error) {
return ms.slaveToGottyReader.Read(buf)
}
func (ms *mockSlave) Write(buf []byte) (int, error) {
return ms.gottyToSlaveWriter.Write(buf)
}
func (ms *mockSlave) WindowTitleVariables() map[string]interface{} {
return nil
}
func (ms *mockSlave) ResizeTerminal(columns int, rows int) error {
ms.columns = columns
ms.rows = rows
ms.wg.Done()
return nil
}

32
wercker.yml Normal file
View File

@ -0,0 +1,32 @@
box: golang:1.9.0
build:
steps:
- setup-go-workspace
- script:
name: tools
code: make tools
- script:
name: test
code: make test
- script:
name: cross compile
code: make cross_compile OUTPUT_DIR=$WERCKER_OUTPUT_DIR
- script:
name: store Makefile
code: cp Makefile $WERCKER_OUTPUT_DIR/
deploy:
steps:
- script:
name: tools
code: make tools
- script:
name: targz
code: make targz OUTPUT_DIR=.
- script:
name: shasums
code: make shasums OUTPUT_DIR=.
- script:
name: release
code: make release OUTPUT_DIR=. GIT_COMMIT=$WERCKER_GIT_COMMIT