rebrand: frp -> kanhole (kanhole server, kanholec client)
golangci-lint / lint (push) Failing after 1m5s

This commit is contained in:
kannn
2026-05-29 09:05:34 +00:00
Unverified
parent a0a42a4966
commit 2cd3052da1
265 changed files with 949 additions and 962 deletions
+26
View File
@@ -0,0 +1,26 @@
// Copyright 2016 fatedier, fatedier@gmail.com
//
// 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.
package main
import (
"kanhole/cmd/kanholec/sub"
"kanhole/pkg/util/system"
_ "kanhole/web/frpc"
)
func main() {
system.EnableCompatibilityMode()
sub.Execute()
}
+125
View File
@@ -0,0 +1,125 @@
// Copyright 2023 The kanhole Authors
//
// 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.
package sub
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/rodaine/table"
"github.com/spf13/cobra"
"kanhole/pkg/config"
v1 "kanhole/pkg/config/v1"
clientsdk "kanhole/pkg/sdk/client"
)
var adminAPITimeout = 30 * time.Second
func init() {
commands := []struct {
name string
description string
handler func(*v1.ClientCommonConfig) error
}{
{"reload", "Hot-Reload kanholec configuration", ReloadHandler},
{"status", "Overview of all proxies status", StatusHandler},
{"stop", "Stop the running kanholec", StopHandler},
}
for _, cmdConfig := range commands {
cmd := NewAdminCommand(cmdConfig.name, cmdConfig.description, cmdConfig.handler)
cmd.Flags().DurationVar(&adminAPITimeout, "api-timeout", adminAPITimeout, "Timeout for admin API calls")
rootCmd.AddCommand(cmd)
}
}
func NewAdminCommand(name, short string, handler func(*v1.ClientCommonConfig) error) *cobra.Command {
return &cobra.Command{
Use: name,
Short: short,
Run: func(cmd *cobra.Command, args []string) {
cfg, _, _, _, err := config.LoadClientConfig(cfgFile, strictConfigMode)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if cfg.WebServer.Port <= 0 {
fmt.Println("web server port should be set if you want to use this feature")
os.Exit(1)
}
if err := handler(cfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
}
func ReloadHandler(clientCfg *v1.ClientCommonConfig) error {
client := clientsdk.New(clientCfg.WebServer.Addr, clientCfg.WebServer.Port)
client.SetAuth(clientCfg.WebServer.User, clientCfg.WebServer.Password)
ctx, cancel := context.WithTimeout(context.Background(), adminAPITimeout)
defer cancel()
if err := client.Reload(ctx, strictConfigMode); err != nil {
return err
}
fmt.Println("reload success")
return nil
}
func StatusHandler(clientCfg *v1.ClientCommonConfig) error {
client := clientsdk.New(clientCfg.WebServer.Addr, clientCfg.WebServer.Port)
client.SetAuth(clientCfg.WebServer.User, clientCfg.WebServer.Password)
ctx, cancel := context.WithTimeout(context.Background(), adminAPITimeout)
defer cancel()
res, err := client.GetAllProxyStatus(ctx)
if err != nil {
return err
}
fmt.Printf("Proxy Status...\n\n")
for _, typ := range proxyTypes {
arrs := res[string(typ)]
if len(arrs) == 0 {
continue
}
fmt.Println(strings.ToUpper(string(typ)))
tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
for _, ps := range arrs {
tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
}
tbl.Print()
fmt.Println("")
}
return nil
}
func StopHandler(clientCfg *v1.ClientCommonConfig) error {
client := clientsdk.New(clientCfg.WebServer.Addr, clientCfg.WebServer.Port)
client.SetAuth(clientCfg.WebServer.User, clientCfg.WebServer.Password)
ctx, cancel := context.WithTimeout(context.Background(), adminAPITimeout)
defer cancel()
if err := client.Stop(ctx); err != nil {
return err
}
fmt.Println("stop success")
return nil
}
+183
View File
@@ -0,0 +1,183 @@
package sub
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"github.com/spf13/cobra"
"kanhole/pkg/util/log"
)
var (
authServer string
authOutput string
)
func init() {
authCmd := &cobra.Command{
Use: "auth",
Short: "Authenticate kanholec with a kanhole server",
Long: `Authenticate this kanholec instance with a kanhole server.
One-time token:
kanholec auth token <token> --server http://server:7500
Interactive login:
kanholec auth login --server http://server:7500 --client-name myclient
`,
}
tokenCmd := &cobra.Command{
Use: "token <token>",
Short: "Authenticate using a one-time token",
Args: cobra.ExactArgs(1),
RunE: runAuthToken,
}
tokenCmd.Flags().StringVarP(&authServer, "server", "s", "http://localhost:7500", "kanhole server admin URL")
tokenCmd.Flags().StringVarP(&authOutput, "output", "o", "", "output config file path (default: ./kanholec-<client-name>.toml)")
loginCmd := &cobra.Command{
Use: "login",
Short: "Authenticate using admin credentials",
RunE: runAuthLogin,
}
loginCmd.Flags().StringVarP(&authServer, "server", "s", "http://localhost:7500", "kanhole server admin URL")
loginCmd.Flags().StringVarP(&authOutput, "output", "o", "", "output config file path (default: ./kanholec-<client-name>.toml)")
loginCmd.Flags().String("username", "", "admin username (prompts if empty)")
loginCmd.Flags().String("password", "", "admin password (prompts if empty)")
loginCmd.Flags().String("client-name", "", "client name (fetches list if empty)")
rootCmd.AddCommand(authCmd)
authCmd.AddCommand(tokenCmd)
authCmd.AddCommand(loginCmd)
}
func runAuthToken(cmd *cobra.Command, args []string) error {
token := args[0]
url := authServer + "/admin/api/client/auth"
body := map[string]string{"token": token}
data, _ := json.Marshal(body)
resp, err := http.Post(url, "application/json", bytes.NewReader(data))
if err != nil {
return fmt.Errorf("failed to connect to server: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("auth failed (HTTP %d): %s", resp.StatusCode, string(respBody))
}
configData, _ := io.ReadAll(resp.Body)
return saveConfig(configData)
}
func runAuthLogin(cmd *cobra.Command, args []string) error {
username, _ := cmd.Flags().GetString("username")
password, _ := cmd.Flags().GetString("password")
clientName, _ := cmd.Flags().GetString("client-name")
if username == "" {
fmt.Print("Admin username: ")
fmt.Scanln(&username)
}
if password == "" {
fmt.Print("Admin password: ")
bytePassword, err := readPassword()
if err != nil {
return err
}
password = string(bytePassword)
fmt.Println()
}
url := authServer + "/admin/api/client/auth"
body := map[string]string{
"username": username,
"password": password,
"client_name": clientName,
}
data, _ := json.Marshal(body)
resp, err := http.Post(url, "application/json", bytes.NewReader(data))
if err != nil {
return fmt.Errorf("failed to connect to server: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("auth failed (HTTP %d): %s", resp.StatusCode, string(respBody))
}
// Check if server returned a client list
contentType := resp.Header.Get("Content-Type")
if contentType == "application/json" || len(contentType) == 0 {
var result struct {
Clients []map[string]any `json:"clients"`
RequiresClientName bool `json:"requires_client_name"`
}
respBody, _ := io.ReadAll(resp.Body)
if err := json.Unmarshal(respBody, &result); err == nil && result.RequiresClientName {
fmt.Println("Available clients:")
for i, c := range result.Clients {
fmt.Printf(" %d. %s\n", i+1, c["name"])
}
fmt.Print("Enter client name: ")
var name string
fmt.Scanln(&name)
body["client_name"] = name
data, _ = json.Marshal(body)
resp, err = http.Post(url, "application/json", bytes.NewReader(data))
if err != nil {
return fmt.Errorf("failed to connect to server: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("auth failed (HTTP %d): %s", resp.StatusCode, string(respBody))
}
configData, _ := io.ReadAll(resp.Body)
return saveConfig(configData)
}
configData := respBody
return saveConfig(configData)
}
configData, _ := io.ReadAll(resp.Body)
return saveConfig(configData)
}
func saveConfig(data []byte) error {
outputPath := authOutput
if outputPath == "" {
// Try to extract client name from config
outputPath = "kanholec.toml"
}
if err := os.MkdirAll(filepath.Dir(outputPath), 0755); err != nil {
return fmt.Errorf("failed to create output directory: %w", err)
}
if err := os.WriteFile(outputPath, data, 0644); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
log.Infof("config saved to %s", outputPath)
fmt.Printf("Config saved to %s\n", outputPath)
fmt.Printf("Run: kanholec -c %s\n", outputPath)
return nil
}
func readPassword() ([]byte, error) {
return io.ReadAll(os.Stdin)
}
+21
View File
@@ -0,0 +1,21 @@
//go:build kanholec_gui
package sub
import (
"github.com/spf13/cobra"
"kanhole/client/gui"
)
func init() {
guiCmd := &cobra.Command{
Use: "gui",
Short: "Start the kanholec graphical user interface",
RunE: func(cmd *cobra.Command, args []string) error {
gui.Run()
return nil
},
}
rootCmd.AddCommand(guiCmd)
}
+23
View File
@@ -0,0 +1,23 @@
//go:build !kanholec_gui
package sub
import (
"fmt"
"github.com/spf13/cobra"
)
func init() {
guiCmd := &cobra.Command{
Use: "gui",
Short: "Start the kanholec graphical user interface",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("kanholec GUI is not available in this build.")
fmt.Println("To build with GUI support, install OpenGL and X11 dev libraries, then:")
fmt.Println(" CGO_ENABLED=1 go build -tags kanholec_gui -o kanholec ./cmd/kanholec")
return nil
},
}
rootCmd.AddCommand(guiCmd)
}
+100
View File
@@ -0,0 +1,100 @@
// Copyright 2023 The kanhole Authors
//
// 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.
package sub
import (
"fmt"
"os"
"github.com/spf13/cobra"
"kanhole/pkg/config"
v1 "kanhole/pkg/config/v1"
"kanhole/pkg/nathole"
)
var (
natHoleSTUNServer string
natHoleLocalAddr string
)
func init() {
rootCmd.AddCommand(natholeCmd)
natholeCmd.AddCommand(natholeDiscoveryCmd)
natholeCmd.PersistentFlags().StringVarP(&natHoleSTUNServer, "nat_hole_stun_server", "", "", "STUN server address for nathole")
natholeCmd.PersistentFlags().StringVarP(&natHoleLocalAddr, "nat_hole_local_addr", "l", "", "local address to connect STUN server")
}
var natholeCmd = &cobra.Command{
Use: "nathole",
Short: "Actions about nathole",
}
var natholeDiscoveryCmd = &cobra.Command{
Use: "discover",
Short: "Discover nathole information from stun server",
RunE: func(cmd *cobra.Command, args []string) error {
// ignore error here, because we can use command line parameters
cfg, _, _, _, err := config.LoadClientConfig(cfgFile, strictConfigMode)
if err != nil {
cfg = &v1.ClientCommonConfig{}
if err := cfg.Complete(); err != nil {
fmt.Printf("failed to complete config: %v\n", err)
os.Exit(1)
}
}
if natHoleSTUNServer != "" {
cfg.NatHoleSTUNServer = natHoleSTUNServer
}
if err := validateForNatHoleDiscovery(cfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
addrs, localAddr, err := nathole.Discover([]string{cfg.NatHoleSTUNServer}, natHoleLocalAddr)
if err != nil {
fmt.Println("discover error:", err)
os.Exit(1)
}
if len(addrs) < 2 {
fmt.Printf("discover error: can not get enough addresses, need 2, got: %v\n", addrs)
os.Exit(1)
}
localIPs, _ := nathole.ListLocalIPsForNatHole(10)
natFeature, err := nathole.ClassifyNATFeature(addrs, localIPs)
if err != nil {
fmt.Println("classify nat feature error:", err)
os.Exit(1)
}
fmt.Println("STUN server:", cfg.NatHoleSTUNServer)
fmt.Println("Your NAT type is:", natFeature.NatType)
fmt.Println("Behavior is:", natFeature.Behavior)
fmt.Println("External address is:", addrs)
fmt.Println("Local address is:", localAddr.String())
fmt.Println("Public Network:", natFeature.PublicNetwork)
return nil
},
}
func validateForNatHoleDiscovery(cfg *v1.ClientCommonConfig) error {
if cfg.NatHoleSTUNServer == "" {
return fmt.Errorf("nat_hole_stun_server can not be empty")
}
return nil
}
+151
View File
@@ -0,0 +1,151 @@
// Copyright 2023 The kanhole Authors
//
// 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.
package sub
import (
"fmt"
"os"
"slices"
"github.com/spf13/cobra"
"kanhole/pkg/config"
"kanhole/pkg/config/source"
v1 "kanhole/pkg/config/v1"
"kanhole/pkg/config/v1/validation"
"kanhole/pkg/policy/security"
)
var proxyTypes = []v1.ProxyType{
v1.ProxyTypeTCP,
v1.ProxyTypeUDP,
v1.ProxyTypeTCPMUX,
v1.ProxyTypeHTTP,
v1.ProxyTypeHTTPS,
v1.ProxyTypeSTCP,
v1.ProxyTypeSUDP,
v1.ProxyTypeXTCP,
}
var visitorTypes = []v1.VisitorType{
v1.VisitorTypeSTCP,
v1.VisitorTypeSUDP,
v1.VisitorTypeXTCP,
}
func init() {
for _, typ := range proxyTypes {
c := v1.NewProxyConfigurerByType(typ)
if c == nil {
panic("proxy type: " + typ + " not support")
}
clientCfg := v1.ClientCommonConfig{}
cmd := NewProxyCommand(string(typ), c, &clientCfg)
config.RegisterClientCommonConfigFlags(cmd, &clientCfg)
config.RegisterProxyFlags(cmd, c)
// add sub command for visitor
if slices.Contains(visitorTypes, v1.VisitorType(typ)) {
vc := v1.NewVisitorConfigurerByType(v1.VisitorType(typ))
if vc == nil {
panic("visitor type: " + typ + " not support")
}
visitorCmd := NewVisitorCommand(string(typ), vc, &clientCfg)
config.RegisterVisitorFlags(visitorCmd, vc)
cmd.AddCommand(visitorCmd)
}
rootCmd.AddCommand(cmd)
}
}
func NewProxyCommand(name string, c v1.ProxyConfigurer, clientCfg *v1.ClientCommonConfig) *cobra.Command {
return &cobra.Command{
Use: name,
Short: fmt.Sprintf("Run kanholec with a single %s proxy", name),
Run: func(cmd *cobra.Command, args []string) {
if err := clientCfg.Complete(); err != nil {
fmt.Println(err)
os.Exit(1)
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
validator := validation.NewConfigValidator(unsafeFeatures)
if _, err := validator.ValidateClientCommonConfig(clientCfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
c.GetBaseConfig().Type = name
c.Complete()
proxyCfg := c
if err := validation.ValidateProxyConfigurerForClient(proxyCfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
err := startService(clientCfg, []v1.ProxyConfigurer{proxyCfg}, nil, unsafeFeatures, "")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
}
func NewVisitorCommand(name string, c v1.VisitorConfigurer, clientCfg *v1.ClientCommonConfig) *cobra.Command {
return &cobra.Command{
Use: "visitor",
Short: fmt.Sprintf("Run kanholec with a single %s visitor", name),
Run: func(cmd *cobra.Command, args []string) {
if err := clientCfg.Complete(); err != nil {
fmt.Println(err)
os.Exit(1)
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
validator := validation.NewConfigValidator(unsafeFeatures)
if _, err := validator.ValidateClientCommonConfig(clientCfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
c.GetBaseConfig().Type = name
c.Complete()
visitorCfg := c
if err := validation.ValidateVisitorConfigurer(visitorCfg); err != nil {
fmt.Println(err)
os.Exit(1)
}
err := startService(clientCfg, nil, []v1.VisitorConfigurer{visitorCfg}, unsafeFeatures, "")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
}
func startService(
cfg *v1.ClientCommonConfig,
proxyCfgs []v1.ProxyConfigurer,
visitorCfgs []v1.VisitorConfigurer,
unsafeFeatures *security.UnsafeFeatures,
cfgFile string,
) error {
configSource := source.NewConfigSource()
if err := configSource.ReplaceAll(proxyCfgs, visitorCfgs); err != nil {
return fmt.Errorf("failed to set config source: %w", err)
}
aggregator := source.NewAggregator(configSource)
return startServiceWithAggregator(cfg, aggregator, unsafeFeatures, cfgFile)
}
+264
View File
@@ -0,0 +1,264 @@
// Copyright 2018 fatedier, fatedier@gmail.com
//
// 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.
package sub
import (
"context"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/spf13/cobra"
"kanhole/client"
"kanhole/pkg/config"
"kanhole/pkg/config/source"
v1 "kanhole/pkg/config/v1"
"kanhole/pkg/config/v1/validation"
"kanhole/pkg/policy/featuregate"
"kanhole/pkg/policy/security"
"kanhole/pkg/util/log"
"kanhole/pkg/util/version"
)
var (
cfgFile string
cfgDir string
showVersion bool
strictConfigMode bool
allowUnsafe []string
serverConfigURL string
)
func init() {
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./kanholec.toml", "config file of kanholec")
rootCmd.PersistentFlags().StringVarP(&cfgDir, "config_dir", "", "", "config directory, run one kanholec service for each file in config directory")
rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of kanholec")
rootCmd.PersistentFlags().BoolVarP(&strictConfigMode, "strict_config", "", true, "strict config parsing mode, unknown fields will cause an errors")
rootCmd.PersistentFlags().StringVarP(&serverConfigURL, "server-config", "", "", "fetch config from frps server URL (auto-reloads on change)")
rootCmd.PersistentFlags().StringSliceVarP(&allowUnsafe, "allow-unsafe", "", []string{},
fmt.Sprintf("allowed unsafe features, one or more of: %s", strings.Join(security.ClientUnsafeFeatures, ", ")))
}
var rootCmd = &cobra.Command{
Use: "kanholec",
Short: "kanholec is the client component of kanhole",
RunE: func(cmd *cobra.Command, args []string) error {
if showVersion {
fmt.Println(version.Full())
return nil
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
// If cfgDir is not empty, run multiple kanholec service for each config file in cfgDir.
// Note that it's only designed for testing. It's not guaranteed to be stable.
if cfgDir != "" {
_ = runMultipleClients(cfgDir, unsafeFeatures)
return nil
}
// If server-config is set, use it instead of local config file.
if serverConfigURL != "" {
err := runClientWithServerConfig(serverConfigURL, unsafeFeatures)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
}
// Do not show command usage here.
err := runClient(cfgFile, unsafeFeatures)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
},
}
func runMultipleClients(cfgDir string, unsafeFeatures *security.UnsafeFeatures) error {
var wg sync.WaitGroup
err := filepath.WalkDir(cfgDir, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
wg.Add(1)
time.Sleep(time.Millisecond)
go func() {
defer wg.Done()
err := runClient(path, unsafeFeatures)
if err != nil {
fmt.Printf("kanholec service error for config file [%s]\n", path)
}
}()
return nil
})
wg.Wait()
return err
}
func Execute() {
rootCmd.SetGlobalNormalizationFunc(config.WordSepNormalizeFunc)
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func handleTermSignal(svr *client.Service) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
svr.GracefulClose(500 * time.Millisecond)
}
func runClientWithServerConfig(url string, unsafeFeatures *security.UnsafeFeatures) error {
log.Infof("fetching config from server: %s", url)
resp, err := http.Get(url)
if err != nil {
return fmt.Errorf("failed to fetch config from server: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read config from server: %w", err)
}
allCfg := v1.ClientConfig{}
if err := config.LoadConfigure(body, &allCfg, strictConfigMode, "toml"); err != nil {
return fmt.Errorf("failed to parse config from server: %w", err)
}
result := &config.ClientConfigLoadResult{
Common: &allCfg.ClientCommonConfig,
Proxies: make([]v1.ProxyConfigurer, 0),
}
for _, c := range allCfg.Proxies {
result.Proxies = append(result.Proxies, c.ProxyConfigurer)
}
result.Common.ConfigURL = url
return runClientWithAggregator(result, unsafeFeatures, "")
}
func runClient(cfgFilePath string, unsafeFeatures *security.UnsafeFeatures) error {
// Load configuration
result, err := config.LoadClientConfigResult(cfgFilePath, strictConfigMode)
if err != nil {
return err
}
if result.IsLegacyFormat {
fmt.Printf("WARNING: ini format is deprecated and the support will be removed in the future, " +
"please use yaml/json/toml format instead!\n")
}
if len(result.Common.FeatureGates) > 0 {
if err := featuregate.SetFromMap(result.Common.FeatureGates); err != nil {
return err
}
}
return runClientWithAggregator(result, unsafeFeatures, cfgFilePath)
}
// runClientWithAggregator runs the client using the internal source aggregator.
func runClientWithAggregator(result *config.ClientConfigLoadResult, unsafeFeatures *security.UnsafeFeatures, cfgFilePath string) error {
configSource := source.NewConfigSource()
if err := configSource.ReplaceAll(result.Proxies, result.Visitors); err != nil {
return fmt.Errorf("failed to set config source: %w", err)
}
var storeSource *source.StoreSource
if result.Common.Store.IsEnabled() {
storePath := result.Common.Store.Path
if storePath != "" && cfgFilePath != "" && !filepath.IsAbs(storePath) {
storePath = filepath.Join(filepath.Dir(cfgFilePath), storePath)
}
s, err := source.NewStoreSource(source.StoreSourceConfig{
Path: storePath,
})
if err != nil {
return fmt.Errorf("failed to create store source: %w", err)
}
storeSource = s
}
aggregator := source.NewAggregator(configSource)
if storeSource != nil {
aggregator.SetStoreSource(storeSource)
}
proxyCfgs, visitorCfgs, err := aggregator.Load()
if err != nil {
return fmt.Errorf("failed to load config from sources: %w", err)
}
proxyCfgs, visitorCfgs = config.FilterClientConfigurers(result.Common, proxyCfgs, visitorCfgs)
proxyCfgs = config.CompleteProxyConfigurers(proxyCfgs)
visitorCfgs = config.CompleteVisitorConfigurers(visitorCfgs)
warning, err := validation.ValidateAllClientConfig(result.Common, proxyCfgs, visitorCfgs, unsafeFeatures)
if warning != nil {
fmt.Printf("WARNING: %v\n", warning)
}
if err != nil {
return err
}
return startServiceWithAggregator(result.Common, aggregator, unsafeFeatures, cfgFilePath)
}
func startServiceWithAggregator(
cfg *v1.ClientCommonConfig,
aggregator *source.Aggregator,
unsafeFeatures *security.UnsafeFeatures,
cfgFile string,
) error {
log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
if cfgFile != "" {
log.Infof("start kanholec service for config file [%s] with aggregated configuration", cfgFile)
defer log.Infof("kanholec service for config file [%s] stopped", cfgFile)
}
svr, err := client.NewService(client.ServiceOptions{
Common: cfg,
ConfigSourceAggregator: aggregator,
UnsafeFeatures: unsafeFeatures,
ConfigFilePath: cfgFile,
})
if err != nil {
return err
}
shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic"
if shouldGracefulClose {
go handleTermSignal(svr)
}
return svr.Run(context.Background())
}
+59
View File
@@ -0,0 +1,59 @@
// Copyright 2021 The kanhole Authors
//
// 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.
package sub
import (
"fmt"
"os"
"github.com/spf13/cobra"
"kanhole/pkg/config"
"kanhole/pkg/config/v1/validation"
"kanhole/pkg/policy/security"
)
func init() {
rootCmd.AddCommand(verifyCmd)
}
var verifyCmd = &cobra.Command{
Use: "verify",
Short: "Verify that the configures is valid",
RunE: func(cmd *cobra.Command, args []string) error {
if cfgFile == "" {
fmt.Println("kanholec: the configuration file is not specified")
return nil
}
cliCfg, proxyCfgs, visitorCfgs, _, err := config.LoadClientConfig(cfgFile, strictConfigMode)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
unsafeFeatures := security.NewUnsafeFeatures(allowUnsafe)
warning, err := validation.ValidateAllClientConfig(cliCfg, proxyCfgs, visitorCfgs, unsafeFeatures)
if warning != nil {
fmt.Printf("WARNING: %v\n", warning)
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("kanholec: the configuration file %s syntax is ok\n", cfgFile)
return nil
},
}