Skip to content

Commit

Permalink
feat: add connection limit (#3)
Browse files Browse the repository at this point in the history
Added a connection limit so only one user can connect to the flipper at
a time. Allowing multiple connections simultaneously doesn't make much sense for
this tool.
  • Loading branch information
jon4hz authored Jul 29, 2022
1 parent eae9ef2 commit 9073d16
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
53 changes: 53 additions & 0 deletions middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package main

import (
"errors"
"sync"

"github.com/charmbracelet/wish"
"github.com/gliderlabs/ssh"
)

type connLimiter struct {
sync.Mutex
conns int
maxConns int
}

func newConnLimiter(maxConns int) *connLimiter {
return &connLimiter{
maxConns: maxConns,
}
}

func (u *connLimiter) Add() error {
u.Lock()
defer u.Unlock()
if u.conns >= u.maxConns {
return errors.New("max connections reached")
}
u.conns++
return nil
}

func (u *connLimiter) Remove() {
u.Lock()
defer u.Unlock()
u.conns--
if u.conns < 0 {
u.conns = 0
}
}

func connLimit(limiter *connLimiter) wish.Middleware {
return func(sh ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
if err := limiter.Add(); err != nil {
wish.Fatalf(s, "max connections reached\n")
return
}
sh(s)
limiter.Remove()
}
}
}
4 changes: 4 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ func server(cmd *coral.Command, args []string) {
if err != nil {
log.Fatal(err)
}

cl := newConnLimiter(1)

s, err := wish.NewServer(
wish.WithAddress(serverFlags.listen),
wish.WithHostKeyPath(".ssh/flipperzero_tea_ed25519"),
Expand All @@ -54,6 +57,7 @@ func server(cmd *coral.Command, args []string) {
return m, []tea.ProgramOption{tea.WithAltScreen(), tea.WithMouseCellMotion()}
}),
lm.Middleware(),
connLimit(cl),
),
)
if err != nil {
Expand Down

0 comments on commit 9073d16

Please sign in to comment.