add tls
All checks were successful
Build Multi-Platform Binaries / build (push) Successful in 11m8s

This commit is contained in:
Flik
2025-12-26 00:00:29 +08:00
parent f1038a132b
commit 1870b59214
6 changed files with 80 additions and 36 deletions

View File

@@ -1,15 +1,16 @@
package tunnel
import (
"crypto/tls"
"fmt"
"log"
"net"
"sync"
"time"
"github.com/google/uuid"
"github.com/gotunnel/pkg/protocol"
"github.com/gotunnel/pkg/relay"
"github.com/google/uuid"
"github.com/hashicorp/yamux"
)
@@ -18,6 +19,8 @@ type Client struct {
ServerAddr string
Token string
ID string
TLSEnabled bool
TLSConfig *tls.Config
session *yamux.Session
rules []protocol.ProxyRule
mu sync.RWMutex
@@ -53,7 +56,15 @@ func (c *Client) Run() error {
// connect 连接到服务端并认证
func (c *Client) connect() error {
conn, err := net.DialTimeout("tcp", c.ServerAddr, 10*time.Second)
var conn net.Conn
var err error
if c.TLSEnabled && c.TLSConfig != nil {
dialer := &net.Dialer{Timeout: 10 * time.Second}
conn, err = tls.DialWithDialer(dialer, "tcp", c.ServerAddr, c.TLSConfig)
} else {
conn, err = net.DialTimeout("tcp", c.ServerAddr, 10*time.Second)
}
if err != nil {
return err
}

View File

@@ -22,6 +22,7 @@ type ServerSettings struct {
HeartbeatSec int `yaml:"heartbeat_sec"`
HeartbeatTimeout int `yaml:"heartbeat_timeout"`
DBPath string `yaml:"db_path"`
TLSDisabled bool `yaml:"tls_disabled"` // 默认启用 TLS设置为 true 禁用
}
// WebSettings Web控制台设置

View File

@@ -1,6 +1,7 @@
package tunnel
import (
"crypto/tls"
"fmt"
"log"
"net"
@@ -26,6 +27,7 @@ type Server struct {
portManager *utils.PortManager
clients map[string]*ClientSession
mu sync.RWMutex
tlsConfig *tls.Config
}
// ClientSession 客户端会话
@@ -52,17 +54,33 @@ func NewServer(cs db.ClientStore, bindAddr string, bindPort int, token string, h
}
}
// SetTLSConfig 设置 TLS 配置
func (s *Server) SetTLSConfig(config *tls.Config) {
s.tlsConfig = config
}
// Run 启动服务端
func (s *Server) Run() error {
addr := fmt.Sprintf("%s:%d", s.bindAddr, s.bindPort)
ln, err := net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("failed to listen on %s: %v", addr, err)
var ln net.Listener
var err error
if s.tlsConfig != nil {
ln, err = tls.Listen("tcp", addr, s.tlsConfig)
if err != nil {
return fmt.Errorf("failed to listen TLS on %s: %v", addr, err)
}
log.Printf("[Server] TLS listening on %s", addr)
} else {
ln, err = net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("failed to listen on %s: %v", addr, err)
}
log.Printf("[Server] Listening on %s (no TLS)", addr)
}
defer ln.Close()
log.Printf("[Server] Listening on %s", addr)
for {
conn, err := ln.Accept()
if err != nil {