Skip to content

Commit

Permalink
Support whitelist now
Browse files Browse the repository at this point in the history
  • Loading branch information
songquanpeng committed Apr 12, 2023
1 parent c012e80 commit 8d67740
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ _✨ Easily forward your local port to the public network. ✨_
+ [x] Very easy to use
+ [x] Support TCP
+ [ ] Support UDP
+ [ ] Support IP whitelist
+ [x] Support IP whitelist

## Usages

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ _✨ 基于 Go 的本地端口转发工具,开箱即用 ✨_
+ [x] 开箱即用
+ [x] 支持 TCP
+ [ ] 支持 UDP
+ [ ] 支持 IP 白名单
+ [x] 支持 IP 白名单

## 用法

Expand Down
2 changes: 1 addition & 1 deletion common/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
type serverConfig struct {
Port int `yaml:"port"`
Token string `yaml:"token"`
WhiteList []string `yaml:"white_list"`
Whitelist []string `yaml:"whitelist"`
}

type clientConfig struct {
Expand Down
5 changes: 5 additions & 0 deletions handler/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ func ServeForever() {
println(err.Error())
continue
}
ip := conn.RemoteAddr().(*net.TCPAddr).IP.String()
if !isInWhitelist(ip) {
conn.Close()
continue
}
go handleClientConnection(conn)
}
}
Expand Down
52 changes: 52 additions & 0 deletions handler/whitelist.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package handler

import (
"go-public/common"
"sync"
)

var ipStore = struct {
sync.RWMutex
ips map[string]bool
}{
ips: make(map[string]bool),
}

var whitelistCacheThreshold = 4

func isInWhitelist(ip string) bool {
// If whitelist is empty, just return true
if len(common.ServerConfig.Whitelist) == 0 {
return true
}
// If ip is localhost, just return true
if ip == "::1" {
return true
}
// If whitelist is too short, we don't cache it
if len(common.ServerConfig.Whitelist) < whitelistCacheThreshold {
for _, v := range common.ServerConfig.Whitelist {
if v == ip {
return true
}
}
return false
}
// Check the cache
ipStore.RLock()
if _, ok := ipStore.ips[ip]; ok {
ipStore.RUnlock()
return true
}
ipStore.RUnlock()
// Check the whitelist
for _, v := range common.ServerConfig.Whitelist {
if v == ip {
ipStore.Lock()
ipStore.ips[ip] = true
ipStore.Unlock()
return true
}
}
return false
}

0 comments on commit 8d67740

Please sign in to comment.