Compare commits
15 Commits
33e6ad08d7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b484981017 | |||
| 102c975388 | |||
| ad034ef681 | |||
| aceecfd14c | |||
| a2a688fc4e | |||
| 1de7155771 | |||
| c951c41a9b | |||
| 79d77497a0 | |||
| cb08bb7673 | |||
| 20b90c1727 | |||
| 5d9f7aee92 | |||
| a1e920f6b5 | |||
| dd96c8fe75 | |||
| b5045409cb | |||
| ba5f702e36 |
@ -30,7 +30,7 @@ jobs:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnl_please:latest
|
||||
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:latest
|
||||
platforms: linux/amd64,linux/arm64
|
||||
if: github.ref == 'refs/heads/main'
|
||||
|
||||
@ -40,6 +40,6 @@ jobs:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnl_please:staging
|
||||
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:staging
|
||||
platforms: linux/amd64,linux/arm64
|
||||
if: github.ref == 'refs/heads/staging'
|
||||
106
README.md
106
README.md
@ -1,93 +1,35 @@
|
||||
# tunnel_pls
|
||||
# Tunnel Please
|
||||
|
||||
A lightweight SSH-based tunnel server written in Go that enables secure TCP and HTTP forwarding with an interactive terminal interface for managing connections and custom subdomains.
|
||||
|
||||
## Features
|
||||
|
||||
## Getting started
|
||||
- SSH interactive session with real-time command handling
|
||||
- Custom subdomain management for HTTP tunnels
|
||||
- Active connection control with drop functionality
|
||||
- Dual protocol support: HTTP and TCP tunnels
|
||||
- Real-time connection monitoring
|
||||
## Requirements
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
|
||||
## Add your files
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin http://git.fossy.my.id/bagas/tunnel_pls.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
|
||||
- [ ] [Set up project integrations](http://git.fossy.my.id/bagas/tunnel_pls/-/settings/integrations)
|
||||
|
||||
## Collaborate with your team
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
||||
|
||||
## Test and Deploy
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
|
||||
***
|
||||
|
||||
# Editing this README
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
|
||||
## Suggestions for a good README
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
- Go 1.18 or higher
|
||||
- Valid domain name for subdomain routing
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
Contributions are welcome!
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
If you'd like to contribute to this project, please follow the workflow below:
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
1. **Fork** the repository
|
||||
2. Create a new branch for your changes
|
||||
3. Commit and push your updates
|
||||
4. Open a **Pull Request** targeting the **`staging`** branch
|
||||
5. Clearly describe your changes and the reasoning behind them
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
This project is licensed under the [Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)](https://creativecommons.org/licenses/by-nc-nd/4.0/) license.
|
||||
## Author
|
||||
**Bagas (fossyy)**
|
||||
|
||||
- Website: [fossy.my.id](https://fossy.my.id)
|
||||
- GitHub: [@fossyy](https://github.com/fossyy)
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
|
||||
@ -11,7 +11,6 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"tunnel_pls/session"
|
||||
"tunnel_pls/types"
|
||||
"tunnel_pls/utils"
|
||||
)
|
||||
|
||||
@ -30,7 +29,6 @@ type CustomWriter struct {
|
||||
respMW []ResponseMiddleware
|
||||
reqStartMW []RequestMiddleware
|
||||
reqEndMW []RequestMiddleware
|
||||
overflow []byte
|
||||
}
|
||||
|
||||
func (cw *CustomWriter) SetInteraction(interaction Interaction) {
|
||||
@ -38,14 +36,6 @@ func (cw *CustomWriter) SetInteraction(interaction Interaction) {
|
||||
}
|
||||
|
||||
func (cw *CustomWriter) Read(p []byte) (int, error) {
|
||||
if len(cw.overflow) > 0 {
|
||||
n := copy(p, cw.overflow)
|
||||
cw.overflow = cw.overflow[n:]
|
||||
if len(cw.overflow) == 0 {
|
||||
cw.overflow = nil
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
tmp := make([]byte, len(p))
|
||||
read, err := cw.reader.Read(tmp)
|
||||
if read == 0 && err != nil {
|
||||
@ -99,12 +89,6 @@ func (cw *CustomWriter) Read(p []byte) (int, error) {
|
||||
|
||||
n := copy(p, combined)
|
||||
|
||||
if n > len(p) {
|
||||
cw.overflow = make([]byte, len(combined)-n)
|
||||
copy(cw.overflow, combined[n:])
|
||||
log.Printf("output buffer too small (%d vs %d)", len(p), n)
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
@ -118,7 +102,7 @@ func NewCustomWriter(writer io.Writer, reader io.Reader, remoteAddr net.Addr) *C
|
||||
}
|
||||
}
|
||||
|
||||
var DELIMITER = []byte{0x0D, 0x0A, 0x0D, 0x0A} // HTTP HEADER DELIMITER `\r\n\r\n`
|
||||
var DELIMITER = []byte{0x0D, 0x0A, 0x0D, 0x0A}
|
||||
var requestLine = regexp.MustCompile(`^(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|TRACE|CONNECT) \S+ HTTP/\d\.\d$`)
|
||||
var responseLine = regexp.MustCompile(`^HTTP/\d\.\d \d{3} .+`)
|
||||
|
||||
@ -143,8 +127,8 @@ func isHTTPHeader(buf []byte) bool {
|
||||
}
|
||||
|
||||
func (cw *CustomWriter) Write(p []byte) (int, error) {
|
||||
if len(p) == len(types.BadGatewayResponse) && bytes.Equal(p, types.BadGatewayResponse) {
|
||||
return cw.writer.Write(p)
|
||||
if cw.respHeader != nil && len(cw.buf) == 0 && len(p) >= 5 && string(p[0:5]) == "HTTP/" {
|
||||
cw.respHeader = nil
|
||||
}
|
||||
|
||||
if cw.respHeader != nil {
|
||||
@ -166,9 +150,12 @@ func (cw *CustomWriter) Write(p []byte) (int, error) {
|
||||
body := cw.buf[idx+len(DELIMITER):]
|
||||
|
||||
if !isHTTPHeader(header) {
|
||||
n, err := cw.writer.Write(cw.buf)
|
||||
_, err := cw.writer.Write(cw.buf)
|
||||
cw.buf = nil
|
||||
return n, err
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
resphf := NewResponseHeaderFactory(header)
|
||||
@ -323,20 +310,12 @@ func forwardRequest(cw *CustomWriter, initialRequest *RequestHeaderFactory, sshS
|
||||
}
|
||||
}
|
||||
}()
|
||||
_, err = channel.Write(initialRequest.Finalize())
|
||||
if err != nil {
|
||||
log.Printf("Failed to forward request: %v", err)
|
||||
return
|
||||
}
|
||||
//TODO: Implement wrapper func buat add/remove middleware
|
||||
|
||||
fingerprintMiddleware := NewTunnelFingerprint()
|
||||
loggerMiddleware := NewRequestLogger(cw.interaction, cw.RemoteAddr)
|
||||
forwardedForMiddleware := NewForwardedFor(cw.RemoteAddr)
|
||||
|
||||
cw.respMW = append(cw.respMW, fingerprintMiddleware)
|
||||
cw.reqStartMW = append(cw.reqStartMW, loggerMiddleware)
|
||||
cw.reqStartMW = append(cw.reqStartMW, forwardedForMiddleware)
|
||||
//TODO: Tambah req Middleware
|
||||
cw.reqEndMW = nil
|
||||
cw.reqHeader = initialRequest
|
||||
|
||||
@ -348,6 +327,12 @@ func forwardRequest(cw *CustomWriter, initialRequest *RequestHeaderFactory, sshS
|
||||
}
|
||||
}
|
||||
|
||||
_, err = channel.Write(initialRequest.Finalize())
|
||||
if err != nil {
|
||||
log.Printf("Failed to forward request: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
sshSession.Forwarder.HandleConnection(cw, channel, cw.RemoteAddr)
|
||||
return
|
||||
}
|
||||
|
||||
@ -1,9 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
type RequestMiddleware interface {
|
||||
@ -30,18 +28,6 @@ type RequestLogger struct {
|
||||
remoteAddr net.Addr
|
||||
}
|
||||
|
||||
func NewRequestLogger(interaction Interaction, remoteAddr net.Addr) *RequestLogger {
|
||||
return &RequestLogger{
|
||||
interaction: interaction,
|
||||
remoteAddr: remoteAddr,
|
||||
}
|
||||
}
|
||||
|
||||
func (rl *RequestLogger) HandleRequest(header *RequestHeaderFactory) error {
|
||||
rl.interaction.SendMessage(fmt.Sprintf("\033[32m%s %s -> %s %s \033[0m\r\n", time.Now().UTC().Format(time.RFC3339), rl.remoteAddr.String(), header.Method, header.Path))
|
||||
return nil
|
||||
}
|
||||
|
||||
type ForwardedFor struct {
|
||||
addr net.Addr
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
@ -15,11 +16,12 @@ import (
|
||||
)
|
||||
|
||||
type Forwarder struct {
|
||||
Listener net.Listener
|
||||
TunnelType types.TunnelType
|
||||
ForwardedPort uint16
|
||||
SlugManager slug.Manager
|
||||
Lifecycle Lifecycle
|
||||
Listener net.Listener
|
||||
TunnelType types.TunnelType
|
||||
ForwardedPort uint16
|
||||
SlugManager slug.Manager
|
||||
Lifecycle Lifecycle
|
||||
ActiveForwarder []chan struct{}
|
||||
}
|
||||
|
||||
type Lifecycle interface {
|
||||
@ -39,6 +41,27 @@ type ForwardingController interface {
|
||||
SetLifecycle(lifecycle Lifecycle)
|
||||
CreateForwardedTCPIPPayload(origin net.Addr) []byte
|
||||
WriteBadGatewayResponse(dst io.Writer)
|
||||
AddActiveForwarder(drop chan struct{})
|
||||
DropAllForwarder() int
|
||||
GetForwarderCount() int
|
||||
}
|
||||
|
||||
func (f *Forwarder) AddActiveForwarder(drop chan struct{}) {
|
||||
f.ActiveForwarder = append(f.ActiveForwarder, drop)
|
||||
}
|
||||
|
||||
func (f *Forwarder) DropAllForwarder() int {
|
||||
total := 0
|
||||
for _, d := range f.ActiveForwarder {
|
||||
close(d)
|
||||
total += 1
|
||||
}
|
||||
f.ActiveForwarder = nil
|
||||
return total
|
||||
}
|
||||
|
||||
func (f *Forwarder) GetForwarderCount() int {
|
||||
return len(f.ActiveForwarder)
|
||||
}
|
||||
|
||||
func (f *Forwarder) SetLifecycle(lifecycle Lifecycle) {
|
||||
@ -76,6 +99,7 @@ func (f *Forwarder) AcceptTCPConnections() {
|
||||
}
|
||||
|
||||
func (f *Forwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel, remoteAddr net.Addr) {
|
||||
drop := make(chan struct{})
|
||||
defer func(src ssh.Channel) {
|
||||
_, err := io.Copy(io.Discard, src)
|
||||
if err != nil {
|
||||
@ -96,6 +120,16 @@ func (f *Forwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel, remoteA
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case <-drop:
|
||||
fmt.Println("Closinggggg")
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
f.AddActiveForwarder(drop)
|
||||
|
||||
_, err := io.Copy(dst, src)
|
||||
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
|
||||
27
session/interaction/constants.go
Normal file
27
session/interaction/constants.go
Normal file
@ -0,0 +1,27 @@
|
||||
package interaction
|
||||
|
||||
const (
|
||||
backspaceChar = 8
|
||||
deleteChar = 127
|
||||
enterChar = 13
|
||||
escapeChar = 27
|
||||
ctrlC = 3
|
||||
forwardSlash = '/'
|
||||
minPrintableChar = 32
|
||||
maxPrintableChar = 126
|
||||
|
||||
minSlugLength = 3
|
||||
maxSlugLength = 20
|
||||
|
||||
clearScreen = "\033[H\033[2J"
|
||||
clearLine = "\033[K"
|
||||
clearToLineEnd = "\r\033[K"
|
||||
backspaceSeq = "\b \b"
|
||||
|
||||
minBoxWidth = 50
|
||||
paddingRight = 4
|
||||
)
|
||||
|
||||
var forbiddenSlugs = []string{
|
||||
"ping",
|
||||
}
|
||||
@ -14,10 +14,6 @@ import (
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
var forbiddenSlug = []string{
|
||||
"ping",
|
||||
}
|
||||
|
||||
type Lifecycle interface {
|
||||
Close() error
|
||||
}
|
||||
@ -26,27 +22,32 @@ type Controller interface {
|
||||
SendMessage(message string)
|
||||
HandleUserInput()
|
||||
HandleCommand(command string)
|
||||
HandleSlugEditMode(connection ssh.Channel, char byte)
|
||||
HandleSlugSave(conn ssh.Channel)
|
||||
HandleSlugCancel(connection ssh.Channel)
|
||||
HandleSlugEditMode(char byte)
|
||||
HandleSlugSave()
|
||||
HandleSlugCancel()
|
||||
HandleSlugUpdateError()
|
||||
ShowWelcomeMessage()
|
||||
DisplaySlugEditor()
|
||||
SetChannel(channel ssh.Channel)
|
||||
SetLifecycle(lifecycle Lifecycle)
|
||||
SetSlugModificator(func(oldSlug, newSlug string) bool)
|
||||
WaitForKeyPress()
|
||||
ShowForwardingMessage()
|
||||
}
|
||||
|
||||
type Forwarder interface {
|
||||
Close() error
|
||||
GetTunnelType() types.TunnelType
|
||||
GetForwardedPort() uint16
|
||||
DropAllForwarder() int
|
||||
GetForwarderCount() int
|
||||
}
|
||||
|
||||
type Interaction struct {
|
||||
InputLength int
|
||||
CommandBuffer *bytes.Buffer
|
||||
EditMode bool
|
||||
InteractiveMode bool
|
||||
InteractionType types.InteractionType
|
||||
EditSlug string
|
||||
channel ssh.Channel
|
||||
SlugManager slug.Manager
|
||||
@ -65,317 +66,359 @@ func (i *Interaction) SetChannel(channel ssh.Channel) {
|
||||
}
|
||||
|
||||
func (i *Interaction) SendMessage(message string) {
|
||||
if i.channel != nil {
|
||||
_, err := i.channel.Write([]byte(message))
|
||||
if err != nil && err != io.EOF {
|
||||
log.Printf("Error writing to channel: %v", err)
|
||||
return
|
||||
}
|
||||
if i.channel == nil {
|
||||
log.Printf("channel is nil")
|
||||
}
|
||||
|
||||
_, err := i.channel.Write([]byte(message))
|
||||
if err != nil && err != io.EOF {
|
||||
log.Printf("error writing to channel: %s", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleUserInput() {
|
||||
buf := make([]byte, 1)
|
||||
i.EditMode = false
|
||||
i.InteractiveMode = false
|
||||
|
||||
for {
|
||||
n, err := i.channel.Read(buf)
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
log.Printf("Error reading from client: %s", err)
|
||||
}
|
||||
i.handleReadError(err)
|
||||
break
|
||||
}
|
||||
|
||||
if n > 0 {
|
||||
char := buf[0]
|
||||
|
||||
if i.EditMode {
|
||||
i.HandleSlugEditMode(i.channel, char)
|
||||
continue
|
||||
}
|
||||
|
||||
if i.pendingExit {
|
||||
if char != 3 {
|
||||
i.pendingExit = false
|
||||
i.SendMessage("Operation canceled.\r\n")
|
||||
}
|
||||
}
|
||||
|
||||
if char == 3 {
|
||||
if i.pendingExit {
|
||||
i.SendMessage("Closing connection...\r\n")
|
||||
err = i.Lifecycle.Close()
|
||||
if err != nil {
|
||||
log.Printf("failed to close session: %v", err)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
i.SendMessage("Please press Ctrl+C again to disconnect.\r\n")
|
||||
i.pendingExit = true
|
||||
}
|
||||
|
||||
i.SendMessage(string(buf[:n]))
|
||||
|
||||
if char == 8 || char == 127 {
|
||||
if i.InputLength > 0 {
|
||||
i.SendMessage("\b \b")
|
||||
}
|
||||
if i.CommandBuffer.Len() > 0 {
|
||||
i.CommandBuffer.Truncate(i.CommandBuffer.Len() - 1)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
i.InputLength += n
|
||||
|
||||
if char == '/' {
|
||||
i.CommandBuffer.Reset()
|
||||
i.CommandBuffer.WriteByte(char)
|
||||
continue
|
||||
}
|
||||
|
||||
if i.CommandBuffer.Len() > 0 {
|
||||
if char == 13 {
|
||||
i.SendMessage("\033[K")
|
||||
i.HandleCommand(i.CommandBuffer.String())
|
||||
continue
|
||||
}
|
||||
i.CommandBuffer.WriteByte(char)
|
||||
}
|
||||
|
||||
if char == 13 {
|
||||
i.SendMessage("\033[K")
|
||||
}
|
||||
|
||||
i.processCharacter(buf[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleSlugEditMode(connection ssh.Channel, char byte) {
|
||||
if char == 13 {
|
||||
i.HandleSlugSave(connection)
|
||||
} else if char == 27 || char == 3 {
|
||||
i.HandleSlugCancel(connection)
|
||||
} else if char == 8 || char == 127 {
|
||||
if len(i.EditSlug) > 0 {
|
||||
i.EditSlug = (i.EditSlug)[:len(i.EditSlug)-1]
|
||||
_, err := connection.Write([]byte("\r\033[K"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("➤ " + i.EditSlug + "." + utils.Getenv("domain")))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
} else if char >= 32 && char <= 126 {
|
||||
if (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || char == '-' {
|
||||
i.EditSlug += string(char)
|
||||
_, err := connection.Write([]byte("\r\033[K"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("➤ " + i.EditSlug + "." + utils.Getenv("domain")))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
func (i *Interaction) handleReadError(err error) {
|
||||
if err != io.EOF {
|
||||
log.Printf("Error reading from client: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleSlugSave(connection ssh.Channel) {
|
||||
isValid := isValidSlug(i.EditSlug)
|
||||
|
||||
_, err := connection.Write([]byte("\033[H\033[2J"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
func (i *Interaction) processCharacter(char byte) {
|
||||
if i.InteractiveMode {
|
||||
i.handleInteractiveMode(char)
|
||||
return
|
||||
}
|
||||
if isValid {
|
||||
oldSlug := i.SlugManager.Get()
|
||||
newSlug := i.EditSlug
|
||||
|
||||
if !i.updateClientSlug(oldSlug, newSlug) {
|
||||
i.HandleSlugUpdateError()
|
||||
return
|
||||
}
|
||||
|
||||
_, err := connection.Write([]byte("\r\n\r\n✅ SUBDOMAIN UPDATED ✅\r\n\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("Your new address is: " + newSlug + "." + utils.Getenv("domain") + "\r\n\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
} else if isForbiddenSlug(i.EditSlug) {
|
||||
_, err := connection.Write([]byte("\r\n\r\n❌ FORBIDDEN SUBDOMAIN ❌\r\n\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("This subdomain is not allowed.\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("Please try a different subdomain.\r\n\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
_, err := connection.Write([]byte("\r\n\r\n❌ INVALID SUBDOMAIN ❌\r\n\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("Use only lowercase letters, numbers, and hyphens.\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("Length must be 3-20 characters and cannot start or end with a hyphen.\r\n\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
waitForKeyPress(connection)
|
||||
|
||||
_, err = connection.Write([]byte("\033[H\033[2J"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
if i.handleExitSequence(char) {
|
||||
return
|
||||
}
|
||||
|
||||
i.SendMessage(string(char))
|
||||
i.handleNonInteractiveInput(char)
|
||||
}
|
||||
|
||||
func (i *Interaction) handleInteractiveMode(char byte) {
|
||||
switch i.InteractionType {
|
||||
case types.Slug:
|
||||
i.HandleSlugEditMode(char)
|
||||
case types.Drop:
|
||||
i.HandleDropMode(char)
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) handleExitSequence(char byte) bool {
|
||||
if char == ctrlC {
|
||||
if i.pendingExit {
|
||||
i.SendMessage("Closing connection...\r\n")
|
||||
if err := i.Lifecycle.Close(); err != nil {
|
||||
log.Printf("failed to close session: %v", err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
i.SendMessage("Please press Ctrl+C again to disconnect.\r\n")
|
||||
i.pendingExit = true
|
||||
return true
|
||||
}
|
||||
|
||||
if i.pendingExit && char != ctrlC {
|
||||
i.pendingExit = false
|
||||
i.SendMessage("Operation canceled.\r\n")
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (i *Interaction) handleNonInteractiveInput(char byte) {
|
||||
switch {
|
||||
case char == backspaceChar || char == deleteChar:
|
||||
i.handleBackspace()
|
||||
case char == forwardSlash:
|
||||
i.handleCommandStart()
|
||||
case i.CommandBuffer.Len() > 0:
|
||||
i.handleCommandInput(char)
|
||||
case char == enterChar:
|
||||
i.SendMessage(clearLine)
|
||||
default:
|
||||
i.InputLength++
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) handleBackspace() {
|
||||
if i.InputLength > 0 {
|
||||
i.SendMessage(backspaceSeq)
|
||||
}
|
||||
if i.CommandBuffer.Len() > 0 {
|
||||
i.CommandBuffer.Truncate(i.CommandBuffer.Len() - 1)
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) handleCommandStart() {
|
||||
i.CommandBuffer.Reset()
|
||||
i.CommandBuffer.WriteByte(forwardSlash)
|
||||
}
|
||||
|
||||
func (i *Interaction) handleCommandInput(char byte) {
|
||||
if char == enterChar {
|
||||
i.SendMessage(clearLine)
|
||||
i.HandleCommand(i.CommandBuffer.String())
|
||||
return
|
||||
}
|
||||
i.CommandBuffer.WriteByte(char)
|
||||
i.InputLength++
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleSlugEditMode(char byte) {
|
||||
switch {
|
||||
case char == enterChar:
|
||||
i.HandleSlugSave()
|
||||
case char == escapeChar || char == ctrlC:
|
||||
i.HandleSlugCancel()
|
||||
case char == backspaceChar || char == deleteChar:
|
||||
i.handleSlugBackspace()
|
||||
case char >= minPrintableChar && char <= maxPrintableChar:
|
||||
i.appendToSlug(char)
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) handleSlugBackspace() {
|
||||
if len(i.EditSlug) > 0 {
|
||||
i.EditSlug = i.EditSlug[:len(i.EditSlug)-1]
|
||||
i.refreshSlugDisplay()
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) appendToSlug(char byte) {
|
||||
if isValidSlugChar(char) {
|
||||
i.EditSlug += string(char)
|
||||
i.refreshSlugDisplay()
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) refreshSlugDisplay() {
|
||||
domain := utils.Getenv("domain")
|
||||
i.SendMessage(clearToLineEnd)
|
||||
i.SendMessage("➤ " + i.EditSlug + "." + domain)
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleSlugSave() {
|
||||
i.SendMessage(clearScreen)
|
||||
|
||||
switch {
|
||||
case isForbiddenSlug(i.EditSlug):
|
||||
i.showForbiddenSlugMessage()
|
||||
case !isValidSlug(i.EditSlug):
|
||||
i.showInvalidSlugMessage()
|
||||
default:
|
||||
i.updateSlug()
|
||||
}
|
||||
|
||||
i.WaitForKeyPress()
|
||||
i.returnToMainScreen()
|
||||
}
|
||||
|
||||
func (i *Interaction) updateSlug() {
|
||||
oldSlug := i.SlugManager.Get()
|
||||
newSlug := i.EditSlug
|
||||
|
||||
if !i.updateClientSlug(oldSlug, newSlug) {
|
||||
i.HandleSlugUpdateError()
|
||||
return
|
||||
}
|
||||
i.ShowWelcomeMessage()
|
||||
|
||||
domain := utils.Getenv("domain")
|
||||
protocol := "http"
|
||||
if utils.Getenv("tls_enabled") == "true" {
|
||||
protocol = "https"
|
||||
}
|
||||
_, err = connection.Write([]byte(fmt.Sprintf("Forwarding your traffic to %s://%s.%s \r\n", protocol, i.SlugManager.Get(), domain)))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
i.SendMessage("\r\n\r\n✅ SUBDOMAIN UPDATED ✅\r\n\r\n")
|
||||
i.SendMessage("Your new address is: " + newSlug + "." + domain + "\r\n\r\n")
|
||||
i.SendMessage("Press any key to continue...\r\n")
|
||||
}
|
||||
|
||||
i.EditMode = false
|
||||
func (i *Interaction) showForbiddenSlugMessage() {
|
||||
i.SendMessage("\r\n\r\n❌ FORBIDDEN SUBDOMAIN ❌\r\n\r\n")
|
||||
i.SendMessage("This subdomain is not allowed.\r\n")
|
||||
i.SendMessage("Please try a different subdomain.\r\n\r\n")
|
||||
i.SendMessage("Press any key to continue...\r\n")
|
||||
}
|
||||
|
||||
func (i *Interaction) showInvalidSlugMessage() {
|
||||
i.SendMessage("\r\n\r\n❌ INVALID SUBDOMAIN ❌\r\n\r\n")
|
||||
i.SendMessage("Use only lowercase letters, numbers, and hyphens.\r\n")
|
||||
i.SendMessage(fmt.Sprintf("Length must be %d-%d characters and cannot start or end with a hyphen.\r\n\r\n", minSlugLength, maxSlugLength))
|
||||
i.SendMessage("Press any key to continue...\r\n")
|
||||
}
|
||||
|
||||
func (i *Interaction) returnToMainScreen() {
|
||||
i.SendMessage(clearScreen)
|
||||
i.ShowWelcomeMessage()
|
||||
i.ShowForwardingMessage()
|
||||
i.InteractiveMode = false
|
||||
i.CommandBuffer.Reset()
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleSlugCancel(connection ssh.Channel) {
|
||||
i.EditMode = false
|
||||
_, err := connection.Write([]byte("\033[H\033[2J"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("\r\n\r\n⚠️ SUBDOMAIN EDIT CANCELLED ⚠️\r\n\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
waitForKeyPress(connection)
|
||||
|
||||
_, err = connection.Write([]byte("\033[H\033[2J"))
|
||||
if err != nil {
|
||||
log.Printf("failed to write to channel: %v", err)
|
||||
return
|
||||
}
|
||||
i.ShowWelcomeMessage()
|
||||
|
||||
i.CommandBuffer.Reset()
|
||||
func (i *Interaction) HandleSlugCancel() {
|
||||
i.InteractiveMode = false
|
||||
i.showMessageAndWait("\r\n\r\n⚠️ SUBDOMAIN EDIT CANCELLED ⚠️\r\n\r\n")
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleSlugUpdateError() {
|
||||
i.SendMessage("\r\n\r\n❌ SERVER ERROR ❌\r\n\r\n")
|
||||
i.SendMessage("Failed to update subdomain. You will be disconnected in 5 seconds.\r\n\r\n")
|
||||
|
||||
for iter := 5; iter > 0; iter-- {
|
||||
i.SendMessage(fmt.Sprintf("Disconnecting in %d...\r\n", iter))
|
||||
for countdown := 5; countdown > 0; countdown-- {
|
||||
i.SendMessage(fmt.Sprintf("Disconnecting in %d...\r\n", countdown))
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
err := i.Lifecycle.Close()
|
||||
if err != nil {
|
||||
|
||||
if err := i.Lifecycle.Close(); err != nil {
|
||||
log.Printf("failed to close session: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleCommand(command string) {
|
||||
switch command {
|
||||
case "/bye":
|
||||
i.SendMessage("Closing connection...\r\n")
|
||||
err := i.Lifecycle.Close()
|
||||
if err != nil {
|
||||
log.Printf("failed to close session: %v", err)
|
||||
return
|
||||
}
|
||||
return
|
||||
case "/help":
|
||||
i.SendMessage("\r\nAvailable commands: /bye, /help, /clear, /slug\r\n")
|
||||
case "/clear":
|
||||
i.SendMessage("\033[H\033[2J")
|
||||
i.ShowWelcomeMessage()
|
||||
domain := utils.Getenv("domain")
|
||||
if i.Forwarder.GetTunnelType() == types.HTTP {
|
||||
protocol := "http"
|
||||
if utils.Getenv("tls_enabled") == "true" {
|
||||
protocol = "https"
|
||||
}
|
||||
i.SendMessage(fmt.Sprintf("Forwarding your traffic to %s://%s.%s \r\n", protocol, i.SlugManager.Get(), domain))
|
||||
} else {
|
||||
i.SendMessage(fmt.Sprintf("Forwarding your traffic to tcp://%s:%d \r\n", domain, i.Forwarder.GetForwardedPort()))
|
||||
}
|
||||
case "/slug":
|
||||
if i.Forwarder.GetTunnelType() != types.HTTP {
|
||||
i.SendMessage(fmt.Sprintf("\r\n%s tunnels cannot have custom subdomains", i.Forwarder.GetTunnelType()))
|
||||
} else {
|
||||
i.EditMode = true
|
||||
i.EditSlug = i.SlugManager.Get()
|
||||
i.SendMessage("\033[H\033[2J")
|
||||
i.DisplaySlugEditor()
|
||||
i.SendMessage("➤ " + i.EditSlug + "." + utils.Getenv("domain"))
|
||||
}
|
||||
default:
|
||||
handlers := map[string]func(){
|
||||
"/bye": i.handleByeCommand,
|
||||
"/help": i.handleHelpCommand,
|
||||
"/clear": i.handleClearCommand,
|
||||
"/slug": i.handleSlugCommand,
|
||||
"/drop": i.handleDropCommand,
|
||||
}
|
||||
|
||||
if handler, exists := handlers[command]; exists {
|
||||
handler()
|
||||
} else {
|
||||
i.SendMessage("Unknown command\r\n")
|
||||
}
|
||||
|
||||
i.CommandBuffer.Reset()
|
||||
}
|
||||
|
||||
func (i *Interaction) handleByeCommand() {
|
||||
i.SendMessage("Closing connection...\r\n")
|
||||
if err := i.Lifecycle.Close(); err != nil {
|
||||
log.Printf("failed to close session: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) handleHelpCommand() {
|
||||
i.SendMessage("\r\nAvailable commands: /bye, /help, /clear, /slug, /drop\r\n")
|
||||
}
|
||||
|
||||
func (i *Interaction) handleClearCommand() {
|
||||
i.SendMessage(clearScreen)
|
||||
i.ShowWelcomeMessage()
|
||||
i.ShowForwardingMessage()
|
||||
}
|
||||
|
||||
func (i *Interaction) handleSlugCommand() {
|
||||
if i.Forwarder.GetTunnelType() != types.HTTP {
|
||||
i.SendMessage(fmt.Sprintf("\r\n%s tunnels cannot have custom subdomains\r\n", i.Forwarder.GetTunnelType()))
|
||||
return
|
||||
}
|
||||
|
||||
i.InteractiveMode = true
|
||||
i.InteractionType = types.Slug
|
||||
i.EditSlug = i.SlugManager.Get()
|
||||
i.SendMessage(clearScreen)
|
||||
i.DisplaySlugEditor()
|
||||
|
||||
domain := utils.Getenv("domain")
|
||||
i.SendMessage("➤ " + i.EditSlug + "." + domain)
|
||||
}
|
||||
|
||||
func (i *Interaction) handleDropCommand() {
|
||||
i.InteractiveMode = true
|
||||
i.InteractionType = types.Drop
|
||||
i.SendMessage(clearScreen)
|
||||
i.ShowDropMessage()
|
||||
}
|
||||
|
||||
func (i *Interaction) ShowForwardingMessage() {
|
||||
domain := utils.Getenv("domain")
|
||||
|
||||
if i.Forwarder.GetTunnelType() == types.HTTP {
|
||||
protocol := "http"
|
||||
if utils.Getenv("tls_enabled") == "true" {
|
||||
protocol = "https"
|
||||
}
|
||||
i.SendMessage(fmt.Sprintf("Forwarding your traffic to %s://%s.%s \r\n", protocol, i.SlugManager.Get(), domain))
|
||||
} else {
|
||||
i.SendMessage(fmt.Sprintf("Forwarding your traffic to tcp://%s:%d \r\n", domain, i.Forwarder.GetForwardedPort()))
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) HandleDropMode(char byte) {
|
||||
switch {
|
||||
case char == enterChar || char == 'y' || char == 'Y':
|
||||
i.executeDropAll()
|
||||
case char == escapeChar || char == 'n' || char == 'N' || char == ctrlC:
|
||||
i.cancelDrop()
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Interaction) executeDropAll() {
|
||||
count := i.Forwarder.DropAllForwarder()
|
||||
message := fmt.Sprintf("Dropped %d forwarders\r\n", count)
|
||||
i.showMessageAndWait(message)
|
||||
}
|
||||
|
||||
func (i *Interaction) cancelDrop() {
|
||||
i.showMessageAndWait("Dropping canceled.\r\n")
|
||||
}
|
||||
|
||||
func (i *Interaction) showMessageAndWait(message string) {
|
||||
i.SendMessage(clearScreen)
|
||||
i.SendMessage(message)
|
||||
i.SendMessage("Press any key to continue...\r\n")
|
||||
|
||||
i.InteractiveMode = false
|
||||
i.InteractionType = ""
|
||||
i.WaitForKeyPress()
|
||||
|
||||
i.SendMessage(clearScreen)
|
||||
i.ShowWelcomeMessage()
|
||||
i.ShowForwardingMessage()
|
||||
}
|
||||
|
||||
func (i *Interaction) ShowDropMessage() {
|
||||
confirmText := fmt.Sprintf(" ║ Drop ALL %d active connections?", i.Forwarder.GetForwarderCount())
|
||||
boxWidth := calculateBoxWidth(confirmText)
|
||||
|
||||
box := buildDropConfirmationBox(boxWidth, confirmText)
|
||||
i.SendMessage("\r\n" + box + "\r\n\r\n")
|
||||
}
|
||||
|
||||
func buildDropConfirmationBox(boxWidth int, confirmText string) string {
|
||||
topBorder := " ╔" + strings.Repeat("═", boxWidth-4) + "╗\r\n"
|
||||
title := centerText("DROP CONFIRMATION", boxWidth-4)
|
||||
header := " ║" + title + "║\r\n"
|
||||
midBorder := " ╠" + strings.Repeat("═", boxWidth-4) + "╣\r\n"
|
||||
emptyLine := " ║" + strings.Repeat(" ", boxWidth-4) + "║\r\n"
|
||||
|
||||
confirmLine := confirmText + strings.Repeat(" ", boxWidth-len(confirmText)+1) + "║\r\n"
|
||||
|
||||
controlText := " ║ [Enter/Y] Confirm [N/Esc] Cancel"
|
||||
controlLine := controlText + strings.Repeat(" ", boxWidth-len(controlText)+1) + "║\r\n"
|
||||
|
||||
bottomBorder := " ╚" + strings.Repeat("═", boxWidth-4) + "╝\r\n"
|
||||
|
||||
return topBorder + header + midBorder + emptyLine + confirmLine + emptyLine + controlLine + emptyLine + bottomBorder
|
||||
}
|
||||
|
||||
func (i *Interaction) ShowWelcomeMessage() {
|
||||
asciiArt := []string{
|
||||
` _______ _ _____ _ `,
|
||||
@ -393,6 +436,7 @@ func (i *Interaction) ShowWelcomeMessage() {
|
||||
` - '/help' : Show this help message`,
|
||||
` - '/clear' : Clear the current line`,
|
||||
` - '/slug' : Set custom subdomain`,
|
||||
` - '/drop' : Drop all active forwarders`,
|
||||
}
|
||||
|
||||
for _, line := range asciiArt {
|
||||
@ -405,14 +449,14 @@ func (i *Interaction) DisplaySlugEditor() {
|
||||
domain := utils.Getenv("domain")
|
||||
fullDomain := i.SlugManager.Get() + "." + domain
|
||||
|
||||
const paddingRight = 4
|
||||
|
||||
contentLine := " ║ Current: " + fullDomain
|
||||
boxWidth := len(contentLine) + paddingRight + 1
|
||||
if boxWidth < 50 {
|
||||
boxWidth = 50
|
||||
}
|
||||
boxWidth := calculateBoxWidth(contentLine)
|
||||
|
||||
box := buildSlugEditorBox(boxWidth, fullDomain)
|
||||
i.SendMessage("\r\n\r\n" + box + "\r\n\r\n")
|
||||
}
|
||||
|
||||
func buildSlugEditorBox(boxWidth int, fullDomain string) string {
|
||||
topBorder := " ╔" + strings.Repeat("═", boxWidth-4) + "╗\r\n"
|
||||
title := centerText("SUBDOMAIN EDITOR", boxWidth-4)
|
||||
header := " ║" + title + "║\r\n"
|
||||
@ -425,24 +469,31 @@ func (i *Interaction) DisplaySlugEditor() {
|
||||
saveCancel := " ║ [Enter] Save | [Esc] Cancel" + strings.Repeat(" ", boxWidth-35) + "║\r\n"
|
||||
bottomBorder := " ╚" + strings.Repeat("═", boxWidth-4) + "╝\r\n"
|
||||
|
||||
i.SendMessage("\r\n\r\n")
|
||||
i.SendMessage(topBorder)
|
||||
i.SendMessage(header)
|
||||
i.SendMessage(midBorder)
|
||||
i.SendMessage(emptyLine)
|
||||
i.SendMessage(currentLine)
|
||||
i.SendMessage(emptyLine)
|
||||
i.SendMessage(emptyLine)
|
||||
i.SendMessage(midBorder)
|
||||
i.SendMessage(saveCancel)
|
||||
i.SendMessage(bottomBorder)
|
||||
i.SendMessage("\r\n\r\n")
|
||||
return topBorder + header + midBorder + emptyLine + currentLine + emptyLine + emptyLine + midBorder + saveCancel + bottomBorder
|
||||
}
|
||||
|
||||
func (i *Interaction) SetSlugModificator(modificator func(oldSlug, newSlug string) bool) {
|
||||
i.updateClientSlug = modificator
|
||||
}
|
||||
|
||||
func (i *Interaction) WaitForKeyPress() {
|
||||
keyBuf := make([]byte, 1)
|
||||
for {
|
||||
_, err := i.channel.Read(keyBuf)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func calculateBoxWidth(contentLine string) int {
|
||||
boxWidth := len(contentLine) + paddingRight + 1
|
||||
if boxWidth < minBoxWidth {
|
||||
boxWidth = minBoxWidth
|
||||
}
|
||||
return boxWidth
|
||||
}
|
||||
|
||||
func centerText(text string, width int) string {
|
||||
padding := (width - len(text)) / 2
|
||||
if padding < 0 {
|
||||
@ -452,7 +503,7 @@ func centerText(text string, width int) string {
|
||||
}
|
||||
|
||||
func isValidSlug(slug string) bool {
|
||||
if len(slug) < 3 || len(slug) > 20 {
|
||||
if len(slug) < minSlugLength || len(slug) > maxSlugLength {
|
||||
return false
|
||||
}
|
||||
|
||||
@ -461,7 +512,7 @@ func isValidSlug(slug string) bool {
|
||||
}
|
||||
|
||||
for _, c := range slug {
|
||||
if !((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') {
|
||||
if !isValidSlugChar(byte(c)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@ -469,18 +520,12 @@ func isValidSlug(slug string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func waitForKeyPress(connection ssh.Channel) {
|
||||
keyBuf := make([]byte, 1)
|
||||
for {
|
||||
_, err := connection.Read(keyBuf)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
func isValidSlugChar(c byte) bool {
|
||||
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-'
|
||||
}
|
||||
|
||||
func isForbiddenSlug(slug string) bool {
|
||||
for _, s := range forbiddenSlug {
|
||||
for _, s := range forbiddenSlugs {
|
||||
if slug == s {
|
||||
return true
|
||||
}
|
||||
|
||||
@ -43,12 +43,12 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
|
||||
SlugManager: slugManager,
|
||||
}
|
||||
interactionManager := &interaction.Interaction{
|
||||
CommandBuffer: bytes.NewBuffer(make([]byte, 0, 20)),
|
||||
EditMode: false,
|
||||
EditSlug: "",
|
||||
SlugManager: slugManager,
|
||||
Forwarder: forwarderManager,
|
||||
Lifecycle: nil,
|
||||
CommandBuffer: bytes.NewBuffer(make([]byte, 0, 20)),
|
||||
InteractiveMode: false,
|
||||
EditSlug: "",
|
||||
SlugManager: slugManager,
|
||||
Forwarder: forwarderManager,
|
||||
Lifecycle: nil,
|
||||
}
|
||||
lifecycleManager := &lifecycle.Lifecycle{
|
||||
Status: "",
|
||||
@ -71,28 +71,25 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
|
||||
SlugManager: slugManager,
|
||||
}
|
||||
|
||||
go func() {
|
||||
go session.Lifecycle.WaitForRunningStatus()
|
||||
|
||||
for channel := range sshChan {
|
||||
ch, reqs, err := channel.Accept()
|
||||
if err != nil {
|
||||
log.Printf("failed to accept channel: %v", err)
|
||||
continue
|
||||
}
|
||||
session.channelOnce.Do(func() {
|
||||
session.Lifecycle.SetChannel(ch)
|
||||
session.Interaction.SetChannel(ch)
|
||||
session.Lifecycle.SetStatus(types.SETUP)
|
||||
go session.HandleGlobalRequest(forwardingReq)
|
||||
})
|
||||
|
||||
go session.HandleGlobalRequest(reqs)
|
||||
for channel := range sshChan {
|
||||
ch, reqs, err := channel.Accept()
|
||||
if err != nil {
|
||||
log.Printf("failed to accept channel: %v", err)
|
||||
continue
|
||||
}
|
||||
if err := session.Lifecycle.Close(); err != nil {
|
||||
log.Printf("failed to close session: %v", err)
|
||||
}
|
||||
}()
|
||||
session.channelOnce.Do(func() {
|
||||
session.Lifecycle.SetChannel(ch)
|
||||
session.Interaction.SetChannel(ch)
|
||||
session.Lifecycle.SetStatus(types.SETUP)
|
||||
go session.HandleGlobalRequest(forwardingReq)
|
||||
session.Lifecycle.WaitForRunningStatus()
|
||||
})
|
||||
|
||||
go session.HandleGlobalRequest(reqs)
|
||||
}
|
||||
if err := session.Lifecycle.Close(); err != nil {
|
||||
log.Printf("failed to close session: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func updateClientSlug(oldSlug, newSlug string) bool {
|
||||
|
||||
@ -15,6 +15,13 @@ const (
|
||||
TCP TunnelType = "TCP"
|
||||
)
|
||||
|
||||
type InteractionType string
|
||||
|
||||
const (
|
||||
Slug InteractionType = "SLUG"
|
||||
Drop InteractionType = "DROP"
|
||||
)
|
||||
|
||||
var BadGatewayResponse = []byte("HTTP/1.1 502 Bad Gateway\r\n" +
|
||||
"Content-Length: 11\r\n" +
|
||||
"Content-Type: text/plain\r\n\r\n" +
|
||||
|
||||
Reference in New Issue
Block a user