repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/plugin/client.go
test/e2e/legacy/plugin/client.go
package plugin import ( "crypto/tls" "fmt" "strconv" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/pkg/transport" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/mock/server/httpserver" "github.com/fatedier/frp/test/e2e/pkg/cert" "github.com/fatedier/frp/test/e2e/pkg/port" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: Client-Plugins]", func() { f := framework.NewDefaultFramework() ginkgo.Describe("UnixDomainSocket", func() { ginkgo.It("Expose a unix domain socket echo server", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig getProxyConf := func(proxyName string, portName string, extra string) string { return fmt.Sprintf(` [%s] type = tcp remote_port = {{ .%s }} plugin = unix_domain_socket plugin_unix_path = {{ .%s }} `+extra, proxyName, portName, framework.UDSEchoServerAddr) } tests := []struct { proxyName string portName string extraConfig string }{ { proxyName: "normal", portName: port.GenName("Normal"), }, { proxyName: "with-encryption", portName: port.GenName("WithEncryption"), extraConfig: "use_encryption = true", }, { proxyName: "with-compression", portName: port.GenName("WithCompression"), extraConfig: "use_compression = true", }, { proxyName: "with-encryption-and-compression", portName: port.GenName("WithEncryptionAndCompression"), extraConfig: ` use_encryption = true use_compression = true `, }, } // build all client config for _, test := range tests { clientConf += getProxyConf(test.proxyName, test.portName, test.extraConfig) + "\n" } // run frps and frpc f.RunProcesses([]string{serverConf}, []string{clientConf}) for _, test := range tests { framework.NewRequestExpect(f).Port(f.PortByName(test.portName)).Ensure() } }) }) ginkgo.It("http_proxy", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [tcp] type = tcp remote_port = %d plugin = http_proxy plugin_http_user = abc plugin_http_passwd = 123 `, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // http proxy, no auth info framework.NewRequestExpect(f).PortName(framework.HTTPSimpleServerPort).RequestModify(func(r *request.Request) { r.HTTP().Proxy("http://127.0.0.1:" + strconv.Itoa(remotePort)) }).Ensure(framework.ExpectResponseCode(407)) // http proxy, correct auth framework.NewRequestExpect(f).PortName(framework.HTTPSimpleServerPort).RequestModify(func(r *request.Request) { r.HTTP().Proxy("http://abc:123@127.0.0.1:" + strconv.Itoa(remotePort)) }).Ensure() // connect TCP server by CONNECT method framework.NewRequestExpect(f).PortName(framework.TCPEchoServerPort).RequestModify(func(r *request.Request) { r.TCP().Proxy("http://abc:123@127.0.0.1:" + strconv.Itoa(remotePort)) }) }) ginkgo.It("socks5 proxy", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [tcp] type = tcp remote_port = %d plugin = socks5 plugin_user = abc plugin_passwd = 123 `, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // http proxy, no auth info framework.NewRequestExpect(f).PortName(framework.TCPEchoServerPort).RequestModify(func(r *request.Request) { r.TCP().Proxy("socks5://127.0.0.1:" + strconv.Itoa(remotePort)) }).ExpectError(true).Ensure() // http proxy, correct auth framework.NewRequestExpect(f).PortName(framework.TCPEchoServerPort).RequestModify(func(r *request.Request) { r.TCP().Proxy("socks5://abc:123@127.0.0.1:" + strconv.Itoa(remotePort)) }).Ensure() }) ginkgo.It("static_file", func() { vhostPort := f.AllocPort() serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` vhost_http_port = %d `, vhostPort) clientConf := consts.LegacyDefaultClientConfig remotePort := f.AllocPort() f.WriteTempFile("test_static_file", "foo") clientConf += fmt.Sprintf(` [tcp] type = tcp remote_port = %d plugin = static_file plugin_local_path = %s [http] type = http custom_domains = example.com plugin = static_file plugin_local_path = %s [http-with-auth] type = http custom_domains = other.example.com plugin = static_file plugin_local_path = %s plugin_http_user = abc plugin_http_passwd = 123 `, remotePort, f.TempDirectory, f.TempDirectory, f.TempDirectory) f.RunProcesses([]string{serverConf}, []string{clientConf}) // from tcp proxy framework.NewRequestExpect(f).Request( framework.NewHTTPRequest().HTTPPath("/test_static_file").Port(remotePort), ).ExpectResp([]byte("foo")).Ensure() // from http proxy without auth framework.NewRequestExpect(f).Request( framework.NewHTTPRequest().HTTPHost("example.com").HTTPPath("/test_static_file").Port(vhostPort), ).ExpectResp([]byte("foo")).Ensure() // from http proxy with auth framework.NewRequestExpect(f).Request( framework.NewHTTPRequest().HTTPHost("other.example.com").HTTPPath("/test_static_file").Port(vhostPort).HTTPAuth("abc", "123"), ).ExpectResp([]byte("foo")).Ensure() }) ginkgo.It("http2https", func() { serverConf := consts.LegacyDefaultServerConfig vhostHTTPPort := f.AllocPort() serverConf += fmt.Sprintf(` vhost_http_port = %d `, vhostHTTPPort) localPort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` [http2https] type = http custom_domains = example.com plugin = http2https plugin_local_addr = 127.0.0.1:%d `, localPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) tlsConfig, err := transport.NewServerTLSConfig("", "", "") framework.ExpectNoError(err) localServer := httpserver.New( httpserver.WithBindPort(localPort), httpserver.WithTLSConfig(tlsConfig), httpserver.WithResponse([]byte("test")), ) f.RunServer("", localServer) framework.NewRequestExpect(f). Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("example.com") }). ExpectResp([]byte("test")). Ensure() }) ginkgo.It("https2http", func() { generator := &cert.SelfSignedCertGenerator{} artifacts, err := generator.Generate("example.com") framework.ExpectNoError(err) crtPath := f.WriteTempFile("server.crt", string(artifacts.Cert)) keyPath := f.WriteTempFile("server.key", string(artifacts.Key)) serverConf := consts.LegacyDefaultServerConfig vhostHTTPSPort := f.AllocPort() serverConf += fmt.Sprintf(` vhost_https_port = %d `, vhostHTTPSPort) localPort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` [https2http] type = https custom_domains = example.com plugin = https2http plugin_local_addr = 127.0.0.1:%d plugin_crt_path = %s plugin_key_path = %s `, localPort, crtPath, keyPath) f.RunProcesses([]string{serverConf}, []string{clientConf}) localServer := httpserver.New( httpserver.WithBindPort(localPort), httpserver.WithResponse([]byte("test")), ) f.RunServer("", localServer) framework.NewRequestExpect(f). Port(vhostHTTPSPort). RequestModify(func(r *request.Request) { r.HTTPS().HTTPHost("example.com").TLSConfig(&tls.Config{ ServerName: "example.com", InsecureSkipVerify: true, }) }). ExpectResp([]byte("test")). Ensure() }) ginkgo.It("https2https", func() { generator := &cert.SelfSignedCertGenerator{} artifacts, err := generator.Generate("example.com") framework.ExpectNoError(err) crtPath := f.WriteTempFile("server.crt", string(artifacts.Cert)) keyPath := f.WriteTempFile("server.key", string(artifacts.Key)) serverConf := consts.LegacyDefaultServerConfig vhostHTTPSPort := f.AllocPort() serverConf += fmt.Sprintf(` vhost_https_port = %d `, vhostHTTPSPort) localPort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` [https2https] type = https custom_domains = example.com plugin = https2https plugin_local_addr = 127.0.0.1:%d plugin_crt_path = %s plugin_key_path = %s `, localPort, crtPath, keyPath) f.RunProcesses([]string{serverConf}, []string{clientConf}) tlsConfig, err := transport.NewServerTLSConfig("", "", "") framework.ExpectNoError(err) localServer := httpserver.New( httpserver.WithBindPort(localPort), httpserver.WithResponse([]byte("test")), httpserver.WithTLSConfig(tlsConfig), ) f.RunServer("", localServer) framework.NewRequestExpect(f). Port(vhostHTTPSPort). RequestModify(func(r *request.Request) { r.HTTPS().HTTPHost("example.com").TLSConfig(&tls.Config{ ServerName: "example.com", InsecureSkipVerify: true, }) }). ExpectResp([]byte("test")). Ensure() }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/plugin/server.go
test/e2e/legacy/plugin/server.go
package plugin import ( "fmt" "time" "github.com/onsi/ginkgo/v2" plugin "github.com/fatedier/frp/pkg/plugin/server" "github.com/fatedier/frp/pkg/transport" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" pluginpkg "github.com/fatedier/frp/test/e2e/pkg/plugin" ) var _ = ginkgo.Describe("[Feature: Server-Plugins]", func() { f := framework.NewDefaultFramework() ginkgo.Describe("Login", func() { newFunc := func() *plugin.Request { var r plugin.Request r.Content = &plugin.LoginContent{} return &r } ginkgo.It("Auth for custom meta token", func() { localPort := f.AllocPort() clientAddressGot := false handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.LoginContent) if content.ClientAddress != "" { clientAddressGot = true } if content.Metas["token"] == "123" { ret.Unchange = true } else { ret.Reject = true ret.RejectReason = "invalid token" } return &ret } pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.user-manager] addr = 127.0.0.1:%d path = /handler ops = Login `, localPort) clientConf := consts.LegacyDefaultClientConfig remotePort := f.AllocPort() clientConf += fmt.Sprintf(` meta_token = 123 [tcp] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort) remotePort2 := f.AllocPort() invalidTokenClientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` [tcp2] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort2) f.RunProcesses([]string{serverConf}, []string{clientConf, invalidTokenClientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() framework.NewRequestExpect(f).Port(remotePort2).ExpectError(true).Ensure() framework.ExpectTrue(clientAddressGot) }) }) ginkgo.Describe("NewProxy", func() { newFunc := func() *plugin.Request { var r plugin.Request r.Content = &plugin.NewProxyContent{} return &r } ginkgo.It("Validate Info", func() { localPort := f.AllocPort() handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.NewProxyContent) if content.ProxyName == "tcp" { ret.Unchange = true } else { ret.Reject = true } return &ret } pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.test] addr = 127.0.0.1:%d path = /handler ops = NewProxy `, localPort) clientConf := consts.LegacyDefaultClientConfig remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() }) ginkgo.It("Modify RemotePort", func() { localPort := f.AllocPort() remotePort := f.AllocPort() handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.NewProxyContent) content.RemotePort = remotePort ret.Content = content return &ret } pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.test] addr = 127.0.0.1:%d path = /handler ops = NewProxy `, localPort) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = {{ .%s }} remote_port = 0 `, framework.TCPEchoServerPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() }) }) ginkgo.Describe("CloseProxy", func() { newFunc := func() *plugin.Request { var r plugin.Request r.Content = &plugin.CloseProxyContent{} return &r } ginkgo.It("Validate Info", func() { localPort := f.AllocPort() var recordProxyName string handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.CloseProxyContent) recordProxyName = content.ProxyName return &ret } pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.test] addr = 127.0.0.1:%d path = /handler ops = CloseProxy `, localPort) clientConf := consts.LegacyDefaultClientConfig remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort) _, clients := f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() for _, c := range clients { _ = c.Stop() } time.Sleep(1 * time.Second) framework.ExpectEqual(recordProxyName, "tcp") }) }) ginkgo.Describe("Ping", func() { newFunc := func() *plugin.Request { var r plugin.Request r.Content = &plugin.PingContent{} return &r } ginkgo.It("Validate Info", func() { localPort := f.AllocPort() var record string handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.PingContent) record = content.PrivilegeKey ret.Unchange = true return &ret } pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.test] addr = 127.0.0.1:%d path = /handler ops = Ping `, localPort) remotePort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` heartbeat_interval = 1 authenticate_heartbeats = true [tcp] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() time.Sleep(3 * time.Second) framework.ExpectNotEqual("", record) }) }) ginkgo.Describe("NewWorkConn", func() { newFunc := func() *plugin.Request { var r plugin.Request r.Content = &plugin.NewWorkConnContent{} return &r } ginkgo.It("Validate Info", func() { localPort := f.AllocPort() var record string handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.NewWorkConnContent) record = content.RunID ret.Unchange = true return &ret } pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.test] addr = 127.0.0.1:%d path = /handler ops = NewWorkConn `, localPort) remotePort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() framework.ExpectNotEqual("", record) }) }) ginkgo.Describe("NewUserConn", func() { newFunc := func() *plugin.Request { var r plugin.Request r.Content = &plugin.NewUserConnContent{} return &r } ginkgo.It("Validate Info", func() { localPort := f.AllocPort() var record string handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.NewUserConnContent) record = content.RemoteAddr ret.Unchange = true return &ret } pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, nil) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.test] addr = 127.0.0.1:%d path = /handler ops = NewUserConn `, localPort) remotePort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() framework.ExpectNotEqual("", record) }) }) ginkgo.Describe("HTTPS Protocol", func() { newFunc := func() *plugin.Request { var r plugin.Request r.Content = &plugin.NewUserConnContent{} return &r } ginkgo.It("Validate Login Info, disable tls verify", func() { localPort := f.AllocPort() var record string handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.NewUserConnContent) record = content.RemoteAddr ret.Unchange = true return &ret } tlsConfig, err := transport.NewServerTLSConfig("", "", "") framework.ExpectNoError(err) pluginServer := pluginpkg.NewHTTPPluginServer(localPort, newFunc, handler, tlsConfig) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.test] addr = https://127.0.0.1:%d path = /handler ops = NewUserConn `, localPort) remotePort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() framework.ExpectNotEqual("", record) }) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/basic.go
test/e2e/legacy/basic/basic.go
package basic import ( "crypto/tls" "fmt" "strings" "time" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/pkg/transport" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/mock/server/httpserver" "github.com/fatedier/frp/test/e2e/mock/server/streamserver" "github.com/fatedier/frp/test/e2e/pkg/port" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: Basic]", func() { f := framework.NewDefaultFramework() ginkgo.Describe("TCP && UDP", func() { types := []string{"tcp", "udp"} for _, t := range types { proxyType := t ginkgo.It(fmt.Sprintf("Expose a %s echo server", strings.ToUpper(proxyType)), func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig localPortName := "" protocol := "tcp" switch proxyType { case "tcp": localPortName = framework.TCPEchoServerPort protocol = "tcp" case "udp": localPortName = framework.UDPEchoServerPort protocol = "udp" } getProxyConf := func(proxyName string, portName string, extra string) string { return fmt.Sprintf(` [%s] type = %s local_port = {{ .%s }} remote_port = {{ .%s }} `+extra, proxyName, proxyType, localPortName, portName) } tests := []struct { proxyName string portName string extraConfig string }{ { proxyName: "normal", portName: port.GenName("Normal"), }, { proxyName: "with-encryption", portName: port.GenName("WithEncryption"), extraConfig: "use_encryption = true", }, { proxyName: "with-compression", portName: port.GenName("WithCompression"), extraConfig: "use_compression = true", }, { proxyName: "with-encryption-and-compression", portName: port.GenName("WithEncryptionAndCompression"), extraConfig: ` use_encryption = true use_compression = true `, }, } // build all client config for _, test := range tests { clientConf += getProxyConf(test.proxyName, test.portName, test.extraConfig) + "\n" } // run frps and frpc f.RunProcesses([]string{serverConf}, []string{clientConf}) for _, test := range tests { framework.NewRequestExpect(f). Protocol(protocol). PortName(test.portName). Explain(test.proxyName). Ensure() } }) } }) ginkgo.Describe("HTTP", func() { ginkgo.It("proxy to HTTP server", func() { serverConf := consts.LegacyDefaultServerConfig vhostHTTPPort := f.AllocPort() serverConf += fmt.Sprintf(` vhost_http_port = %d `, vhostHTTPPort) clientConf := consts.LegacyDefaultClientConfig getProxyConf := func(proxyName string, customDomains string, extra string) string { return fmt.Sprintf(` [%s] type = http local_port = {{ .%s }} custom_domains = %s `+extra, proxyName, framework.HTTPSimpleServerPort, customDomains) } tests := []struct { proxyName string customDomains string extraConfig string }{ { proxyName: "normal", }, { proxyName: "with-encryption", extraConfig: "use_encryption = true", }, { proxyName: "with-compression", extraConfig: "use_compression = true", }, { proxyName: "with-encryption-and-compression", extraConfig: ` use_encryption = true use_compression = true `, }, { proxyName: "multiple-custom-domains", customDomains: "a.example.com, b.example.com", }, } // build all client config for i, test := range tests { if tests[i].customDomains == "" { tests[i].customDomains = test.proxyName + ".example.com" } clientConf += getProxyConf(test.proxyName, tests[i].customDomains, test.extraConfig) + "\n" } // run frps and frpc f.RunProcesses([]string{serverConf}, []string{clientConf}) for _, test := range tests { for _, domain := range strings.Split(test.customDomains, ",") { domain = strings.TrimSpace(domain) framework.NewRequestExpect(f). Explain(test.proxyName + "-" + domain). Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost(domain) }). Ensure() } } // not exist host framework.NewRequestExpect(f). Explain("not exist host"). Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("not-exist.example.com") }). Ensure(framework.ExpectResponseCode(404)) }) }) ginkgo.Describe("HTTPS", func() { ginkgo.It("proxy to HTTPS server", func() { serverConf := consts.LegacyDefaultServerConfig vhostHTTPSPort := f.AllocPort() serverConf += fmt.Sprintf(` vhost_https_port = %d `, vhostHTTPSPort) localPort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig getProxyConf := func(proxyName string, customDomains string, extra string) string { return fmt.Sprintf(` [%s] type = https local_port = %d custom_domains = %s `+extra, proxyName, localPort, customDomains) } tests := []struct { proxyName string customDomains string extraConfig string }{ { proxyName: "normal", }, { proxyName: "with-encryption", extraConfig: "use_encryption = true", }, { proxyName: "with-compression", extraConfig: "use_compression = true", }, { proxyName: "with-encryption-and-compression", extraConfig: ` use_encryption = true use_compression = true `, }, { proxyName: "multiple-custom-domains", customDomains: "a.example.com, b.example.com", }, } // build all client config for i, test := range tests { if tests[i].customDomains == "" { tests[i].customDomains = test.proxyName + ".example.com" } clientConf += getProxyConf(test.proxyName, tests[i].customDomains, test.extraConfig) + "\n" } // run frps and frpc f.RunProcesses([]string{serverConf}, []string{clientConf}) tlsConfig, err := transport.NewServerTLSConfig("", "", "") framework.ExpectNoError(err) localServer := httpserver.New( httpserver.WithBindPort(localPort), httpserver.WithTLSConfig(tlsConfig), httpserver.WithResponse([]byte("test")), ) f.RunServer("", localServer) for _, test := range tests { for _, domain := range strings.Split(test.customDomains, ",") { domain = strings.TrimSpace(domain) framework.NewRequestExpect(f). Explain(test.proxyName + "-" + domain). Port(vhostHTTPSPort). RequestModify(func(r *request.Request) { r.HTTPS().HTTPHost(domain).TLSConfig(&tls.Config{ ServerName: domain, InsecureSkipVerify: true, }) }). ExpectResp([]byte("test")). Ensure() } } // not exist host notExistDomain := "not-exist.example.com" framework.NewRequestExpect(f). Explain("not exist host"). Port(vhostHTTPSPort). RequestModify(func(r *request.Request) { r.HTTPS().HTTPHost(notExistDomain).TLSConfig(&tls.Config{ ServerName: notExistDomain, InsecureSkipVerify: true, }) }). ExpectError(true). Ensure() }) }) ginkgo.Describe("STCP && SUDP && XTCP", func() { types := []string{"stcp", "sudp", "xtcp"} for _, t := range types { proxyType := t ginkgo.It(fmt.Sprintf("Expose echo server with %s", strings.ToUpper(proxyType)), func() { serverConf := consts.LegacyDefaultServerConfig clientServerConf := consts.LegacyDefaultClientConfig + "\nuser = user1" clientVisitorConf := consts.LegacyDefaultClientConfig + "\nuser = user1" clientUser2VisitorConf := consts.LegacyDefaultClientConfig + "\nuser = user2" localPortName := "" protocol := "tcp" switch proxyType { case "stcp": localPortName = framework.TCPEchoServerPort protocol = "tcp" case "sudp": localPortName = framework.UDPEchoServerPort protocol = "udp" case "xtcp": localPortName = framework.TCPEchoServerPort protocol = "tcp" ginkgo.Skip("stun server is not stable") } correctSK := "abc" wrongSK := "123" getProxyServerConf := func(proxyName string, extra string) string { return fmt.Sprintf(` [%s] type = %s role = server sk = %s local_port = {{ .%s }} `+extra, proxyName, proxyType, correctSK, localPortName) } getProxyVisitorConf := func(proxyName string, portName, visitorSK, extra string) string { return fmt.Sprintf(` [%s] type = %s role = visitor server_name = %s sk = %s bind_port = {{ .%s }} `+extra, proxyName, proxyType, proxyName, visitorSK, portName) } tests := []struct { proxyName string bindPortName string visitorSK string commonExtraConfig string proxyExtraConfig string visitorExtraConfig string expectError bool deployUser2Client bool // skipXTCP is used to skip xtcp test case skipXTCP bool }{ { proxyName: "normal", bindPortName: port.GenName("Normal"), visitorSK: correctSK, skipXTCP: true, }, { proxyName: "with-encryption", bindPortName: port.GenName("WithEncryption"), visitorSK: correctSK, commonExtraConfig: "use_encryption = true", skipXTCP: true, }, { proxyName: "with-compression", bindPortName: port.GenName("WithCompression"), visitorSK: correctSK, commonExtraConfig: "use_compression = true", skipXTCP: true, }, { proxyName: "with-encryption-and-compression", bindPortName: port.GenName("WithEncryptionAndCompression"), visitorSK: correctSK, commonExtraConfig: ` use_encryption = true use_compression = true `, skipXTCP: true, }, { proxyName: "with-error-sk", bindPortName: port.GenName("WithErrorSK"), visitorSK: wrongSK, expectError: true, }, { proxyName: "allowed-user", bindPortName: port.GenName("AllowedUser"), visitorSK: correctSK, proxyExtraConfig: "allow_users = another, user2", visitorExtraConfig: "server_user = user1", deployUser2Client: true, }, { proxyName: "not-allowed-user", bindPortName: port.GenName("NotAllowedUser"), visitorSK: correctSK, proxyExtraConfig: "allow_users = invalid", visitorExtraConfig: "server_user = user1", expectError: true, }, { proxyName: "allow-all", bindPortName: port.GenName("AllowAll"), visitorSK: correctSK, proxyExtraConfig: "allow_users = *", visitorExtraConfig: "server_user = user1", deployUser2Client: true, }, } // build all client config for _, test := range tests { clientServerConf += getProxyServerConf(test.proxyName, test.commonExtraConfig+"\n"+test.proxyExtraConfig) + "\n" } for _, test := range tests { config := getProxyVisitorConf( test.proxyName, test.bindPortName, test.visitorSK, test.commonExtraConfig+"\n"+test.visitorExtraConfig, ) + "\n" if test.deployUser2Client { clientUser2VisitorConf += config } else { clientVisitorConf += config } } // run frps and frpc f.RunProcesses([]string{serverConf}, []string{clientServerConf, clientVisitorConf, clientUser2VisitorConf}) for _, test := range tests { timeout := time.Second if t == "xtcp" { if test.skipXTCP { continue } timeout = 10 * time.Second } framework.NewRequestExpect(f). RequestModify(func(r *request.Request) { r.Timeout(timeout) }). Protocol(protocol). PortName(test.bindPortName). Explain(test.proxyName). ExpectError(test.expectError). Ensure() } }) } }) ginkgo.Describe("TCPMUX", func() { ginkgo.It("Type tcpmux", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig tcpmuxHTTPConnectPortName := port.GenName("TCPMUX") serverConf += fmt.Sprintf(` tcpmux_httpconnect_port = {{ .%s }} `, tcpmuxHTTPConnectPortName) getProxyConf := func(proxyName string, extra string) string { return fmt.Sprintf(` [%s] type = tcpmux multiplexer = httpconnect local_port = {{ .%s }} custom_domains = %s `+extra, proxyName, port.GenName(proxyName), proxyName) } tests := []struct { proxyName string extraConfig string }{ { proxyName: "normal", }, { proxyName: "with-encryption", extraConfig: "use_encryption = true", }, { proxyName: "with-compression", extraConfig: "use_compression = true", }, { proxyName: "with-encryption-and-compression", extraConfig: ` use_encryption = true use_compression = true `, }, } // build all client config for _, test := range tests { clientConf += getProxyConf(test.proxyName, test.extraConfig) + "\n" localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(f.AllocPort()), streamserver.WithRespContent([]byte(test.proxyName))) f.RunServer(port.GenName(test.proxyName), localServer) } // run frps and frpc f.RunProcesses([]string{serverConf}, []string{clientConf}) // Request without HTTP connect should get error framework.NewRequestExpect(f). PortName(tcpmuxHTTPConnectPortName). ExpectError(true). Explain("request without HTTP connect expect error"). Ensure() proxyURL := fmt.Sprintf("http://127.0.0.1:%d", f.PortByName(tcpmuxHTTPConnectPortName)) // Request with incorrect connect hostname framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.Addr("invalid").Proxy(proxyURL) }).ExpectError(true).Explain("request without HTTP connect expect error").Ensure() // Request with correct connect hostname for _, test := range tests { framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.Addr(test.proxyName).Proxy(proxyURL) }).ExpectResp([]byte(test.proxyName)).Explain(test.proxyName).Ensure() } }) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/client.go
test/e2e/legacy/basic/client.go
package basic import ( "context" "fmt" "strconv" "strings" "time" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: ClientManage]", func() { f := framework.NewDefaultFramework() ginkgo.It("Update && Reload API", func() { serverConf := consts.LegacyDefaultServerConfig adminPort := f.AllocPort() p1Port := f.AllocPort() p2Port := f.AllocPort() p3Port := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` admin_port = %d [p1] type = tcp local_port = {{ .%s }} remote_port = %d [p2] type = tcp local_port = {{ .%s }} remote_port = %d [p3] type = tcp local_port = {{ .%s }} remote_port = %d `, adminPort, framework.TCPEchoServerPort, p1Port, framework.TCPEchoServerPort, p2Port, framework.TCPEchoServerPort, p3Port) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(p1Port).Ensure() framework.NewRequestExpect(f).Port(p2Port).Ensure() framework.NewRequestExpect(f).Port(p3Port).Ensure() client := f.APIClientForFrpc(adminPort) conf, err := client.GetConfig(context.Background()) framework.ExpectNoError(err) newP2Port := f.AllocPort() // change p2 port and remove p3 proxy newClientConf := strings.ReplaceAll(conf, strconv.Itoa(p2Port), strconv.Itoa(newP2Port)) p3Index := strings.Index(newClientConf, "[p3]") if p3Index >= 0 { newClientConf = newClientConf[:p3Index] } err = client.UpdateConfig(context.Background(), newClientConf) framework.ExpectNoError(err) err = client.Reload(context.Background(), true) framework.ExpectNoError(err) time.Sleep(time.Second) framework.NewRequestExpect(f).Port(p1Port).Explain("p1 port").Ensure() framework.NewRequestExpect(f).Port(p2Port).Explain("original p2 port").ExpectError(true).Ensure() framework.NewRequestExpect(f).Port(newP2Port).Explain("new p2 port").Ensure() framework.NewRequestExpect(f).Port(p3Port).Explain("p3 port").ExpectError(true).Ensure() }) ginkgo.It("healthz", func() { serverConf := consts.LegacyDefaultServerConfig dashboardPort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` admin_addr = 0.0.0.0 admin_port = %d admin_user = admin admin_pwd = admin `, dashboardPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.HTTP().HTTPPath("/healthz") }).Port(dashboardPort).ExpectResp([]byte("")).Ensure() framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.HTTP().HTTPPath("/") }).Port(dashboardPort). Ensure(framework.ExpectResponseCode(401)) }) ginkgo.It("stop", func() { serverConf := consts.LegacyDefaultServerConfig adminPort := f.AllocPort() testPort := f.AllocPort() clientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` admin_port = %d [test] type = tcp local_port = {{ .%s }} remote_port = %d `, adminPort, framework.TCPEchoServerPort, testPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(testPort).Ensure() client := f.APIClientForFrpc(adminPort) err := client.Stop(context.Background()) framework.ExpectNoError(err) time.Sleep(3 * time.Second) // frpc stopped so the port is not listened, expect error framework.NewRequestExpect(f).Port(testPort).ExpectError(true).Ensure() }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/xtcp.go
test/e2e/legacy/basic/xtcp.go
package basic import ( "fmt" "time" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/pkg/port" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: XTCP]", func() { f := framework.NewDefaultFramework() ginkgo.It("Fallback To STCP", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig bindPortName := port.GenName("XTCP") clientConf += fmt.Sprintf(` [foo] type = stcp local_port = {{ .%s }} [foo-visitor] type = stcp role = visitor server_name = foo bind_port = -1 [bar-visitor] type = xtcp role = visitor server_name = bar bind_port = {{ .%s }} keep_tunnel_open = true fallback_to = foo-visitor fallback_timeout_ms = 200 `, framework.TCPEchoServerPort, bindPortName) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f). RequestModify(func(r *request.Request) { r.Timeout(time.Second) }). PortName(bindPortName). Ensure() }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/config.go
test/e2e/legacy/basic/config.go
package basic import ( "fmt" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/pkg/port" ) var _ = ginkgo.Describe("[Feature: Config]", func() { f := framework.NewDefaultFramework() ginkgo.Describe("Template", func() { ginkgo.It("render by env", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig portName := port.GenName("TCP") serverConf += fmt.Sprintf(` token = {{ %s{{ .Envs.FRP_TOKEN }}%s }} `, "`", "`") clientConf += fmt.Sprintf(` token = {{ %s{{ .Envs.FRP_TOKEN }}%s }} [tcp] type = tcp local_port = {{ .%s }} remote_port = {{ .%s }} `, "`", "`", framework.TCPEchoServerPort, portName) f.SetEnvs([]string{"FRP_TOKEN=123"}) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).PortName(portName).Ensure() }) }) ginkgo.Describe("Includes", func() { ginkgo.It("split tcp proxies into different files", func() { serverPort := f.AllocPort() serverConfigPath := f.GenerateConfigFile(fmt.Sprintf(` [common] bind_addr = 0.0.0.0 bind_port = %d `, serverPort)) remotePort := f.AllocPort() proxyConfigPath := f.GenerateConfigFile(fmt.Sprintf(` [tcp] type = tcp local_port = %d remote_port = %d `, f.PortByName(framework.TCPEchoServerPort), remotePort)) remotePort2 := f.AllocPort() proxyConfigPath2 := f.GenerateConfigFile(fmt.Sprintf(` [tcp2] type = tcp local_port = %d remote_port = %d `, f.PortByName(framework.TCPEchoServerPort), remotePort2)) clientConfigPath := f.GenerateConfigFile(fmt.Sprintf(` [common] server_port = %d includes = %s,%s `, serverPort, proxyConfigPath, proxyConfigPath2)) _, _, err := f.RunFrps("-c", serverConfigPath) framework.ExpectNoError(err) _, _, err = f.RunFrpc("-c", clientConfigPath) framework.ExpectNoError(err) framework.NewRequestExpect(f).Port(remotePort).Ensure() framework.NewRequestExpect(f).Port(remotePort2).Ensure() }) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/cmd.go
test/e2e/legacy/basic/cmd.go
package basic import ( "strconv" "strings" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/pkg/request" ) const ( ConfigValidStr = "syntax is ok" ) var _ = ginkgo.Describe("[Feature: Cmd]", func() { f := framework.NewDefaultFramework() ginkgo.Describe("Verify", func() { ginkgo.It("frps valid", func() { path := f.GenerateConfigFile(` [common] bind_addr = 0.0.0.0 bind_port = 7000 `) _, output, err := f.RunFrps("verify", "-c", path) framework.ExpectNoError(err) framework.ExpectTrue(strings.Contains(output, ConfigValidStr), "output: %s", output) }) ginkgo.It("frps invalid", func() { path := f.GenerateConfigFile(` [common] bind_addr = 0.0.0.0 bind_port = 70000 `) _, output, err := f.RunFrps("verify", "-c", path) framework.ExpectNoError(err) framework.ExpectTrue(!strings.Contains(output, ConfigValidStr), "output: %s", output) }) ginkgo.It("frpc valid", func() { path := f.GenerateConfigFile(` [common] server_addr = 0.0.0.0 server_port = 7000 `) _, output, err := f.RunFrpc("verify", "-c", path) framework.ExpectNoError(err) framework.ExpectTrue(strings.Contains(output, ConfigValidStr), "output: %s", output) }) ginkgo.It("frpc invalid", func() { path := f.GenerateConfigFile(` [common] server_addr = 0.0.0.0 server_port = 7000 protocol = invalid `) _, output, err := f.RunFrpc("verify", "-c", path) framework.ExpectNoError(err) framework.ExpectTrue(!strings.Contains(output, ConfigValidStr), "output: %s", output) }) }) ginkgo.Describe("Single proxy", func() { ginkgo.It("TCP", func() { serverPort := f.AllocPort() _, _, err := f.RunFrps("-t", "123", "-p", strconv.Itoa(serverPort)) framework.ExpectNoError(err) localPort := f.PortByName(framework.TCPEchoServerPort) remotePort := f.AllocPort() _, _, err = f.RunFrpc("tcp", "-s", "127.0.0.1", "-P", strconv.Itoa(serverPort), "-t", "123", "-u", "test", "-l", strconv.Itoa(localPort), "-r", strconv.Itoa(remotePort), "-n", "tcp_test") framework.ExpectNoError(err) framework.NewRequestExpect(f).Port(remotePort).Ensure() }) ginkgo.It("UDP", func() { serverPort := f.AllocPort() _, _, err := f.RunFrps("-t", "123", "-p", strconv.Itoa(serverPort)) framework.ExpectNoError(err) localPort := f.PortByName(framework.UDPEchoServerPort) remotePort := f.AllocPort() _, _, err = f.RunFrpc("udp", "-s", "127.0.0.1", "-P", strconv.Itoa(serverPort), "-t", "123", "-u", "test", "-l", strconv.Itoa(localPort), "-r", strconv.Itoa(remotePort), "-n", "udp_test") framework.ExpectNoError(err) framework.NewRequestExpect(f).Protocol("udp"). Port(remotePort).Ensure() }) ginkgo.It("HTTP", func() { serverPort := f.AllocPort() vhostHTTPPort := f.AllocPort() _, _, err := f.RunFrps("-t", "123", "-p", strconv.Itoa(serverPort), "--vhost_http_port", strconv.Itoa(vhostHTTPPort)) framework.ExpectNoError(err) _, _, err = f.RunFrpc("http", "-s", "127.0.0.1", "-P", strconv.Itoa(serverPort), "-t", "123", "-u", "test", "-n", "udp_test", "-l", strconv.Itoa(f.PortByName(framework.HTTPSimpleServerPort)), "--custom_domain", "test.example.com") framework.ExpectNoError(err) framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("test.example.com") }). Ensure() }) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/server.go
test/e2e/legacy/basic/server.go
package basic import ( "context" "fmt" "net" "strconv" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/pkg/port" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: Server Manager]", func() { f := framework.NewDefaultFramework() ginkgo.It("Ports Whitelist", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig serverConf += ` allow_ports = 10000-11000,11002,12000-13000 ` tcpPortName := port.GenName("TCP", port.WithRangePorts(10000, 11000)) udpPortName := port.GenName("UDP", port.WithRangePorts(12000, 13000)) clientConf += fmt.Sprintf(` [tcp-allowded-in-range] type = tcp local_port = {{ .%s }} remote_port = {{ .%s }} `, framework.TCPEchoServerPort, tcpPortName) clientConf += fmt.Sprintf(` [tcp-port-not-allowed] type = tcp local_port = {{ .%s }} remote_port = 11001 `, framework.TCPEchoServerPort) clientConf += fmt.Sprintf(` [tcp-port-unavailable] type = tcp local_port = {{ .%s }} remote_port = {{ .%s }} `, framework.TCPEchoServerPort, consts.PortServerName) clientConf += fmt.Sprintf(` [udp-allowed-in-range] type = udp local_port = {{ .%s }} remote_port = {{ .%s }} `, framework.UDPEchoServerPort, udpPortName) clientConf += fmt.Sprintf(` [udp-port-not-allowed] type = udp local_port = {{ .%s }} remote_port = 11003 `, framework.UDPEchoServerPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // TCP // Allowed in range framework.NewRequestExpect(f).PortName(tcpPortName).Ensure() // Not Allowed framework.NewRequestExpect(f).Port(11001).ExpectError(true).Ensure() // Unavailable, already bind by frps framework.NewRequestExpect(f).PortName(consts.PortServerName).ExpectError(true).Ensure() // UDP // Allowed in range framework.NewRequestExpect(f).Protocol("udp").PortName(udpPortName).Ensure() // Not Allowed framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.UDP().Port(11003) }).ExpectError(true).Ensure() }) ginkgo.It("Alloc Random Port", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig adminPort := f.AllocPort() clientConf += fmt.Sprintf(` admin_port = %d [tcp] type = tcp local_port = {{ .%s }} [udp] type = udp local_port = {{ .%s }} `, adminPort, framework.TCPEchoServerPort, framework.UDPEchoServerPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) client := f.APIClientForFrpc(adminPort) // tcp random port status, err := client.GetProxyStatus(context.Background(), "tcp") framework.ExpectNoError(err) _, portStr, err := net.SplitHostPort(status.RemoteAddr) framework.ExpectNoError(err) port, err := strconv.Atoi(portStr) framework.ExpectNoError(err) framework.NewRequestExpect(f).Port(port).Ensure() // udp random port status, err = client.GetProxyStatus(context.Background(), "udp") framework.ExpectNoError(err) _, portStr, err = net.SplitHostPort(status.RemoteAddr) framework.ExpectNoError(err) port, err = strconv.Atoi(portStr) framework.ExpectNoError(err) framework.NewRequestExpect(f).Protocol("udp").Port(port).Ensure() }) ginkgo.It("Port Reuse", func() { serverConf := consts.LegacyDefaultServerConfig // Use same port as PortServer serverConf += fmt.Sprintf(` vhost_http_port = {{ .%s }} `, consts.PortServerName) clientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` [http] type = http local_port = {{ .%s }} custom_domains = example.com `, framework.HTTPSimpleServerPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("example.com") }).PortName(consts.PortServerName).Ensure() }) ginkgo.It("healthz", func() { serverConf := consts.LegacyDefaultServerConfig dashboardPort := f.AllocPort() // Use same port as PortServer serverConf += fmt.Sprintf(` vhost_http_port = {{ .%s }} dashboard_addr = 0.0.0.0 dashboard_port = %d dashboard_user = admin dashboard_pwd = admin `, consts.PortServerName, dashboardPort) clientConf := consts.LegacyDefaultClientConfig + fmt.Sprintf(` [http] type = http local_port = {{ .%s }} custom_domains = example.com `, framework.HTTPSimpleServerPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.HTTP().HTTPPath("/healthz") }).Port(dashboardPort).ExpectResp([]byte("")).Ensure() framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.HTTP().HTTPPath("/") }).Port(dashboardPort). Ensure(framework.ExpectResponseCode(401)) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/http.go
test/e2e/legacy/basic/http.go
package basic import ( "fmt" "net/http" "net/url" "strconv" "github.com/gorilla/websocket" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/mock/server/httpserver" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: HTTP]", func() { f := framework.NewDefaultFramework() getDefaultServerConf := func(vhostHTTPPort int) string { conf := consts.LegacyDefaultServerConfig + ` vhost_http_port = %d ` return fmt.Sprintf(conf, vhostHTTPPort) } newHTTPServer := func(port int, respContent string) *httpserver.Server { return httpserver.New( httpserver.WithBindPort(port), httpserver.WithHandler(framework.SpecifiedHTTPBodyHandler([]byte(respContent))), ) } ginkgo.It("HTTP route by locations", func() { vhostHTTPPort := f.AllocPort() serverConf := getDefaultServerConf(vhostHTTPPort) fooPort := f.AllocPort() f.RunServer("", newHTTPServer(fooPort, "foo")) barPort := f.AllocPort() f.RunServer("", newHTTPServer(barPort, "bar")) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [foo] type = http local_port = %d custom_domains = normal.example.com locations = /,/foo [bar] type = http local_port = %d custom_domains = normal.example.com locations = /bar `, fooPort, barPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) tests := []struct { path string expectResp string desc string }{ {path: "/foo", expectResp: "foo", desc: "foo path"}, {path: "/bar", expectResp: "bar", desc: "bar path"}, {path: "/other", expectResp: "foo", desc: "other path"}, } for _, test := range tests { framework.NewRequestExpect(f).Explain(test.desc).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com").HTTPPath(test.path) }). ExpectResp([]byte(test.expectResp)). Ensure() } }) ginkgo.It("HTTP route by HTTP user", func() { vhostHTTPPort := f.AllocPort() serverConf := getDefaultServerConf(vhostHTTPPort) fooPort := f.AllocPort() f.RunServer("", newHTTPServer(fooPort, "foo")) barPort := f.AllocPort() f.RunServer("", newHTTPServer(barPort, "bar")) otherPort := f.AllocPort() f.RunServer("", newHTTPServer(otherPort, "other")) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [foo] type = http local_port = %d custom_domains = normal.example.com route_by_http_user = user1 [bar] type = http local_port = %d custom_domains = normal.example.com route_by_http_user = user2 [catchAll] type = http local_port = %d custom_domains = normal.example.com `, fooPort, barPort, otherPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // user1 framework.NewRequestExpect(f).Explain("user1").Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com").HTTPAuth("user1", "") }). ExpectResp([]byte("foo")). Ensure() // user2 framework.NewRequestExpect(f).Explain("user2").Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com").HTTPAuth("user2", "") }). ExpectResp([]byte("bar")). Ensure() // other user framework.NewRequestExpect(f).Explain("other user").Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com").HTTPAuth("user3", "") }). ExpectResp([]byte("other")). Ensure() }) ginkgo.It("HTTP Basic Auth", func() { vhostHTTPPort := f.AllocPort() serverConf := getDefaultServerConf(vhostHTTPPort) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [test] type = http local_port = {{ .%s }} custom_domains = normal.example.com http_user = test http_pwd = test `, framework.HTTPSimpleServerPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // not set auth header framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com") }). Ensure(framework.ExpectResponseCode(401)) // set incorrect auth header framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com").HTTPAuth("test", "invalid") }). Ensure(framework.ExpectResponseCode(401)) // set correct auth header framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com").HTTPAuth("test", "test") }). Ensure() }) ginkgo.It("Wildcard domain", func() { vhostHTTPPort := f.AllocPort() serverConf := getDefaultServerConf(vhostHTTPPort) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [test] type = http local_port = {{ .%s }} custom_domains = *.example.com `, framework.HTTPSimpleServerPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // not match host framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("not-match.test.com") }). Ensure(framework.ExpectResponseCode(404)) // test.example.com match *.example.com framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("test.example.com") }). Ensure() // sub.test.example.com match *.example.com framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("sub.test.example.com") }). Ensure() }) ginkgo.It("Subdomain", func() { vhostHTTPPort := f.AllocPort() serverConf := getDefaultServerConf(vhostHTTPPort) serverConf += ` subdomain_host = example.com ` fooPort := f.AllocPort() f.RunServer("", newHTTPServer(fooPort, "foo")) barPort := f.AllocPort() f.RunServer("", newHTTPServer(barPort, "bar")) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [foo] type = http local_port = %d subdomain = foo [bar] type = http local_port = %d subdomain = bar `, fooPort, barPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // foo framework.NewRequestExpect(f).Explain("foo subdomain").Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("foo.example.com") }). ExpectResp([]byte("foo")). Ensure() // bar framework.NewRequestExpect(f).Explain("bar subdomain").Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("bar.example.com") }). ExpectResp([]byte("bar")). Ensure() }) ginkgo.It("Modify headers", func() { vhostHTTPPort := f.AllocPort() serverConf := getDefaultServerConf(vhostHTTPPort) localPort := f.AllocPort() localServer := httpserver.New( httpserver.WithBindPort(localPort), httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { _, _ = w.Write([]byte(req.Header.Get("X-From-Where"))) })), ) f.RunServer("", localServer) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [test] type = http local_port = %d custom_domains = normal.example.com header_X-From-Where = frp `, localPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // not set auth header framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com") }). ExpectResp([]byte("frp")). // local http server will write this X-From-Where header to response body Ensure() }) ginkgo.It("Host Header Rewrite", func() { vhostHTTPPort := f.AllocPort() serverConf := getDefaultServerConf(vhostHTTPPort) localPort := f.AllocPort() localServer := httpserver.New( httpserver.WithBindPort(localPort), httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { _, _ = w.Write([]byte(req.Host)) })), ) f.RunServer("", localServer) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [test] type = http local_port = %d custom_domains = normal.example.com host_header_rewrite = rewrite.example.com `, localPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com") }). ExpectResp([]byte("rewrite.example.com")). // local http server will write host header to response body Ensure() }) ginkgo.It("Websocket protocol", func() { vhostHTTPPort := f.AllocPort() serverConf := getDefaultServerConf(vhostHTTPPort) upgrader := websocket.Upgrader{} localPort := f.AllocPort() localServer := httpserver.New( httpserver.WithBindPort(localPort), httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { c, err := upgrader.Upgrade(w, req, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })), ) f.RunServer("", localServer) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [test] type = http local_port = %d custom_domains = 127.0.0.1 `, localPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) u := url.URL{Scheme: "ws", Host: "127.0.0.1:" + strconv.Itoa(vhostHTTPPort)} c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) framework.ExpectNoError(err) err = c.WriteMessage(websocket.TextMessage, []byte(consts.TestString)) framework.ExpectNoError(err) _, msg, err := c.ReadMessage() framework.ExpectNoError(err) framework.ExpectEqualValues(consts.TestString, string(msg)) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/client_server.go
test/e2e/legacy/basic/client_server.go
package basic import ( "fmt" "strings" "time" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/pkg/cert" "github.com/fatedier/frp/test/e2e/pkg/port" ) type generalTestConfigures struct { server string client string clientPrefix string client2 string client2Prefix string testDelay time.Duration expectError bool } func renderBindPortConfig(protocol string) string { switch protocol { case "kcp": return fmt.Sprintf(`kcp_bind_port = {{ .%s }}`, consts.PortServerName) case "quic": return fmt.Sprintf(`quic_bind_port = {{ .%s }}`, consts.PortServerName) default: return "" } } func runClientServerTest(f *framework.Framework, configures *generalTestConfigures) { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig if configures.clientPrefix != "" { clientConf = configures.clientPrefix } serverConf += fmt.Sprintf(` %s `, configures.server) tcpPortName := port.GenName("TCP") udpPortName := port.GenName("UDP") clientConf += fmt.Sprintf(` %s [tcp] type = tcp local_port = {{ .%s }} remote_port = {{ .%s }} [udp] type = udp local_port = {{ .%s }} remote_port = {{ .%s }} `, configures.client, framework.TCPEchoServerPort, tcpPortName, framework.UDPEchoServerPort, udpPortName, ) clientConfs := []string{clientConf} if configures.client2 != "" { client2Conf := consts.LegacyDefaultClientConfig if configures.client2Prefix != "" { client2Conf = configures.client2Prefix } client2Conf += fmt.Sprintf(` %s `, configures.client2) clientConfs = append(clientConfs, client2Conf) } f.RunProcesses([]string{serverConf}, clientConfs) if configures.testDelay > 0 { time.Sleep(configures.testDelay) } framework.NewRequestExpect(f).PortName(tcpPortName).ExpectError(configures.expectError).Explain("tcp proxy").Ensure() framework.NewRequestExpect(f).Protocol("udp"). PortName(udpPortName).ExpectError(configures.expectError).Explain("udp proxy").Ensure() } // defineClientServerTest test a normal tcp and udp proxy with specified TestConfigures. func defineClientServerTest(desc string, f *framework.Framework, configures *generalTestConfigures) { ginkgo.It(desc, func() { runClientServerTest(f, configures) }) } var _ = ginkgo.Describe("[Feature: Client-Server]", func() { f := framework.NewDefaultFramework() ginkgo.Describe("Protocol", func() { supportProtocols := []string{"tcp", "kcp", "quic", "websocket"} for _, protocol := range supportProtocols { configures := &generalTestConfigures{ server: fmt.Sprintf(` %s `, renderBindPortConfig(protocol)), client: "protocol = " + protocol, } defineClientServerTest(protocol, f, configures) } }) // wss is special, it needs to be tested separately. // frps only supports ws, so there should be a proxy to terminate TLS before frps. ginkgo.Describe("Protocol wss", func() { wssPort := f.AllocPort() configures := &generalTestConfigures{ clientPrefix: fmt.Sprintf(` [common] server_addr = 127.0.0.1 server_port = %d protocol = wss log_level = trace login_fail_exit = false `, wssPort), // Due to the fact that frps cannot directly accept wss connections, we use the https2http plugin of another frpc to terminate TLS. client2: fmt.Sprintf(` [wss2ws] type = tcp remote_port = %d plugin = https2http plugin_local_addr = 127.0.0.1:{{ .%s }} `, wssPort, consts.PortServerName), testDelay: 10 * time.Second, } defineClientServerTest("wss", f, configures) }) ginkgo.Describe("Authentication", func() { defineClientServerTest("Token Correct", f, &generalTestConfigures{ server: "token = 123456", client: "token = 123456", }) defineClientServerTest("Token Incorrect", f, &generalTestConfigures{ server: "token = 123456", client: "token = invalid", expectError: true, }) }) ginkgo.Describe("TLS", func() { supportProtocols := []string{"tcp", "kcp", "quic", "websocket"} for _, protocol := range supportProtocols { tmp := protocol // Since v0.50.0, the default value of tls_enable has been changed to true. // Therefore, here it needs to be set as false to test the scenario of turning it off. defineClientServerTest("Disable TLS over "+strings.ToUpper(tmp), f, &generalTestConfigures{ server: fmt.Sprintf(` %s `, renderBindPortConfig(protocol)), client: fmt.Sprintf(`tls_enable = false protocol = %s `, protocol), }) } defineClientServerTest("enable tls_only, client with TLS", f, &generalTestConfigures{ server: "tls_only = true", }) defineClientServerTest("enable tls_only, client without TLS", f, &generalTestConfigures{ server: "tls_only = true", client: "tls_enable = false", expectError: true, }) }) ginkgo.Describe("TLS with custom certificate", func() { supportProtocols := []string{"tcp", "kcp", "quic", "websocket"} var ( caCrtPath string serverCrtPath, serverKeyPath string clientCrtPath, clientKeyPath string ) ginkgo.JustBeforeEach(func() { generator := &cert.SelfSignedCertGenerator{} artifacts, err := generator.Generate("127.0.0.1") framework.ExpectNoError(err) caCrtPath = f.WriteTempFile("ca.crt", string(artifacts.CACert)) serverCrtPath = f.WriteTempFile("server.crt", string(artifacts.Cert)) serverKeyPath = f.WriteTempFile("server.key", string(artifacts.Key)) generator.SetCA(artifacts.CACert, artifacts.CAKey) _, err = generator.Generate("127.0.0.1") framework.ExpectNoError(err) clientCrtPath = f.WriteTempFile("client.crt", string(artifacts.Cert)) clientKeyPath = f.WriteTempFile("client.key", string(artifacts.Key)) }) for _, protocol := range supportProtocols { tmp := protocol ginkgo.It("one-way authentication: "+tmp, func() { runClientServerTest(f, &generalTestConfigures{ server: fmt.Sprintf(` %s tls_trusted_ca_file = %s `, renderBindPortConfig(tmp), caCrtPath), client: fmt.Sprintf(` protocol = %s tls_cert_file = %s tls_key_file = %s `, tmp, clientCrtPath, clientKeyPath), }) }) ginkgo.It("mutual authentication: "+tmp, func() { runClientServerTest(f, &generalTestConfigures{ server: fmt.Sprintf(` %s tls_cert_file = %s tls_key_file = %s tls_trusted_ca_file = %s `, renderBindPortConfig(tmp), serverCrtPath, serverKeyPath, caCrtPath), client: fmt.Sprintf(` protocol = %s tls_cert_file = %s tls_key_file = %s tls_trusted_ca_file = %s `, tmp, clientCrtPath, clientKeyPath, caCrtPath), }) }) } }) ginkgo.Describe("TLS with custom certificate and specified server name", func() { var ( caCrtPath string serverCrtPath, serverKeyPath string clientCrtPath, clientKeyPath string ) ginkgo.JustBeforeEach(func() { generator := &cert.SelfSignedCertGenerator{} artifacts, err := generator.Generate("example.com") framework.ExpectNoError(err) caCrtPath = f.WriteTempFile("ca.crt", string(artifacts.CACert)) serverCrtPath = f.WriteTempFile("server.crt", string(artifacts.Cert)) serverKeyPath = f.WriteTempFile("server.key", string(artifacts.Key)) generator.SetCA(artifacts.CACert, artifacts.CAKey) _, err = generator.Generate("example.com") framework.ExpectNoError(err) clientCrtPath = f.WriteTempFile("client.crt", string(artifacts.Cert)) clientKeyPath = f.WriteTempFile("client.key", string(artifacts.Key)) }) ginkgo.It("mutual authentication", func() { runClientServerTest(f, &generalTestConfigures{ server: fmt.Sprintf(` tls_cert_file = %s tls_key_file = %s tls_trusted_ca_file = %s `, serverCrtPath, serverKeyPath, caCrtPath), client: fmt.Sprintf(` tls_server_name = example.com tls_cert_file = %s tls_key_file = %s tls_trusted_ca_file = %s `, clientCrtPath, clientKeyPath, caCrtPath), }) }) ginkgo.It("mutual authentication with incorrect server name", func() { runClientServerTest(f, &generalTestConfigures{ server: fmt.Sprintf(` tls_cert_file = %s tls_key_file = %s tls_trusted_ca_file = %s `, serverCrtPath, serverKeyPath, caCrtPath), client: fmt.Sprintf(` tls_server_name = invalid.com tls_cert_file = %s tls_key_file = %s tls_trusted_ca_file = %s `, clientCrtPath, clientKeyPath, caCrtPath), expectError: true, }) }) }) ginkgo.Describe("TLS with disable_custom_tls_first_byte set to false", func() { supportProtocols := []string{"tcp", "kcp", "quic", "websocket"} for _, protocol := range supportProtocols { tmp := protocol defineClientServerTest("TLS over "+strings.ToUpper(tmp), f, &generalTestConfigures{ server: fmt.Sprintf(` %s `, renderBindPortConfig(protocol)), client: fmt.Sprintf(` protocol = %s disable_custom_tls_first_byte = false `, protocol), }) } }) ginkgo.Describe("IPv6 bind address", func() { supportProtocols := []string{"tcp", "kcp", "quic", "websocket"} for _, protocol := range supportProtocols { tmp := protocol defineClientServerTest("IPv6 bind address: "+strings.ToUpper(tmp), f, &generalTestConfigures{ server: fmt.Sprintf(` bind_addr = :: %s `, renderBindPortConfig(protocol)), client: fmt.Sprintf(` protocol = %s `, protocol), }) } }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/basic/tcpmux.go
test/e2e/legacy/basic/tcpmux.go
package basic import ( "bufio" "fmt" "net" "net/http" "github.com/onsi/ginkgo/v2" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/mock/server/streamserver" "github.com/fatedier/frp/test/e2e/pkg/request" "github.com/fatedier/frp/test/e2e/pkg/rpc" ) var _ = ginkgo.Describe("[Feature: TCPMUX httpconnect]", func() { f := framework.NewDefaultFramework() getDefaultServerConf := func(httpconnectPort int) string { conf := consts.LegacyDefaultServerConfig + ` tcpmux_httpconnect_port = %d ` return fmt.Sprintf(conf, httpconnectPort) } newServer := func(port int, respContent string) *streamserver.Server { return streamserver.New( streamserver.TCP, streamserver.WithBindPort(port), streamserver.WithRespContent([]byte(respContent)), ) } proxyURLWithAuth := func(username, password string, port int) string { if username == "" { return fmt.Sprintf("http://127.0.0.1:%d", port) } return fmt.Sprintf("http://%s:%s@127.0.0.1:%d", username, password, port) } ginkgo.It("Route by HTTP user", func() { vhostPort := f.AllocPort() serverConf := getDefaultServerConf(vhostPort) fooPort := f.AllocPort() f.RunServer("", newServer(fooPort, "foo")) barPort := f.AllocPort() f.RunServer("", newServer(barPort, "bar")) otherPort := f.AllocPort() f.RunServer("", newServer(otherPort, "other")) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [foo] type = tcpmux multiplexer = httpconnect local_port = %d custom_domains = normal.example.com route_by_http_user = user1 [bar] type = tcpmux multiplexer = httpconnect local_port = %d custom_domains = normal.example.com route_by_http_user = user2 [catchAll] type = tcpmux multiplexer = httpconnect local_port = %d custom_domains = normal.example.com `, fooPort, barPort, otherPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // user1 framework.NewRequestExpect(f).Explain("user1"). RequestModify(func(r *request.Request) { r.Addr("normal.example.com").Proxy(proxyURLWithAuth("user1", "", vhostPort)) }). ExpectResp([]byte("foo")). Ensure() // user2 framework.NewRequestExpect(f).Explain("user2"). RequestModify(func(r *request.Request) { r.Addr("normal.example.com").Proxy(proxyURLWithAuth("user2", "", vhostPort)) }). ExpectResp([]byte("bar")). Ensure() // other user framework.NewRequestExpect(f).Explain("other user"). RequestModify(func(r *request.Request) { r.Addr("normal.example.com").Proxy(proxyURLWithAuth("user3", "", vhostPort)) }). ExpectResp([]byte("other")). Ensure() }) ginkgo.It("Proxy auth", func() { vhostPort := f.AllocPort() serverConf := getDefaultServerConf(vhostPort) fooPort := f.AllocPort() f.RunServer("", newServer(fooPort, "foo")) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [test] type = tcpmux multiplexer = httpconnect local_port = %d custom_domains = normal.example.com http_user = test http_pwd = test `, fooPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // not set auth header framework.NewRequestExpect(f).Explain("no auth"). RequestModify(func(r *request.Request) { r.Addr("normal.example.com").Proxy(proxyURLWithAuth("", "", vhostPort)) }). ExpectError(true). Ensure() // set incorrect auth header framework.NewRequestExpect(f).Explain("incorrect auth"). RequestModify(func(r *request.Request) { r.Addr("normal.example.com").Proxy(proxyURLWithAuth("test", "invalid", vhostPort)) }). ExpectError(true). Ensure() // set correct auth header framework.NewRequestExpect(f).Explain("correct auth"). RequestModify(func(r *request.Request) { r.Addr("normal.example.com").Proxy(proxyURLWithAuth("test", "test", vhostPort)) }). ExpectResp([]byte("foo")). Ensure() }) ginkgo.It("TCPMux Passthrough", func() { vhostPort := f.AllocPort() serverConf := getDefaultServerConf(vhostPort) serverConf += ` tcpmux_passthrough = true ` var ( respErr error connectRequestHost string ) newServer := func(port int) *streamserver.Server { return streamserver.New( streamserver.TCP, streamserver.WithBindPort(port), streamserver.WithCustomHandler(func(conn net.Conn) { defer conn.Close() // read HTTP CONNECT request bufioReader := bufio.NewReader(conn) req, err := http.ReadRequest(bufioReader) if err != nil { respErr = err return } connectRequestHost = req.Host // return ok response res := httppkg.OkResponse() if res.Body != nil { defer res.Body.Close() } _ = res.Write(conn) buf, err := rpc.ReadBytes(conn) if err != nil { respErr = err return } _, _ = rpc.WriteBytes(conn, buf) }), ) } localPort := f.AllocPort() f.RunServer("", newServer(localPort)) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [test] type = tcpmux multiplexer = httpconnect local_port = %d custom_domains = normal.example.com `, localPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f). RequestModify(func(r *request.Request) { r.Addr("normal.example.com").Proxy(proxyURLWithAuth("", "", vhostPort)).Body([]byte("frp")) }). ExpectResp([]byte("frp")). Ensure() framework.ExpectNoError(respErr) framework.ExpectEqualValues(connectRequestHost, "normal.example.com") }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/features/chaos.go
test/e2e/legacy/features/chaos.go
package features import ( "fmt" "time" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" ) var _ = ginkgo.Describe("[Feature: Chaos]", func() { f := framework.NewDefaultFramework() ginkgo.It("reconnect after frps restart", func() { serverPort := f.AllocPort() serverConfigPath := f.GenerateConfigFile(fmt.Sprintf(` [common] bind_addr = 0.0.0.0 bind_port = %d `, serverPort)) remotePort := f.AllocPort() clientConfigPath := f.GenerateConfigFile(fmt.Sprintf(` [common] server_port = %d log_level = trace [tcp] type = tcp local_port = %d remote_port = %d `, serverPort, f.PortByName(framework.TCPEchoServerPort), remotePort)) // 1. start frps and frpc, expect request success ps, _, err := f.RunFrps("-c", serverConfigPath) framework.ExpectNoError(err) pc, _, err := f.RunFrpc("-c", clientConfigPath) framework.ExpectNoError(err) framework.NewRequestExpect(f).Port(remotePort).Ensure() // 2. stop frps, expect request failed _ = ps.Stop() time.Sleep(200 * time.Millisecond) framework.NewRequestExpect(f).Port(remotePort).ExpectError(true).Ensure() // 3. restart frps, expect request success _, _, err = f.RunFrps("-c", serverConfigPath) framework.ExpectNoError(err) time.Sleep(2 * time.Second) framework.NewRequestExpect(f).Port(remotePort).Ensure() // 4. stop frpc, expect request failed _ = pc.Stop() time.Sleep(200 * time.Millisecond) framework.NewRequestExpect(f).Port(remotePort).ExpectError(true).Ensure() // 5. restart frpc, expect request success _, _, err = f.RunFrpc("-c", clientConfigPath) framework.ExpectNoError(err) time.Sleep(time.Second) framework.NewRequestExpect(f).Port(remotePort).Ensure() }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/features/heartbeat.go
test/e2e/legacy/features/heartbeat.go
package features import ( "fmt" "time" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" ) var _ = ginkgo.Describe("[Feature: Heartbeat]", func() { f := framework.NewDefaultFramework() ginkgo.It("disable application layer heartbeat", func() { serverPort := f.AllocPort() serverConf := fmt.Sprintf(` [common] bind_addr = 0.0.0.0 bind_port = %d heartbeat_timeout = -1 tcp_mux_keepalive_interval = 2 `, serverPort) remotePort := f.AllocPort() clientConf := fmt.Sprintf(` [common] server_port = %d log_level = trace heartbeat_interval = -1 heartbeat_timeout = -1 tcp_mux_keepalive_interval = 2 [tcp] type = tcp local_port = %d remote_port = %d `, serverPort, f.PortByName(framework.TCPEchoServerPort), remotePort) // run frps and frpc f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Protocol("tcp").Port(remotePort).Ensure() time.Sleep(5 * time.Second) framework.NewRequestExpect(f).Protocol("tcp").Port(remotePort).Ensure() }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/features/bandwidth_limit.go
test/e2e/legacy/features/bandwidth_limit.go
package features import ( "fmt" "strings" "time" "github.com/onsi/ginkgo/v2" plugin "github.com/fatedier/frp/pkg/plugin/server" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/mock/server/streamserver" pluginpkg "github.com/fatedier/frp/test/e2e/pkg/plugin" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: Bandwidth Limit]", func() { f := framework.NewDefaultFramework() ginkgo.It("Proxy Bandwidth Limit by Client", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig localPort := f.AllocPort() localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(localPort)) f.RunServer("", localServer) remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = %d remote_port = %d bandwidth_limit = 10KB `, localPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) content := strings.Repeat("a", 50*1024) // 5KB start := time.Now() framework.NewRequestExpect(f).Port(remotePort).RequestModify(func(r *request.Request) { r.Body([]byte(content)).Timeout(30 * time.Second) }).ExpectResp([]byte(content)).Ensure() duration := time.Since(start) framework.Logf("request duration: %s", duration.String()) framework.ExpectTrue(duration.Seconds() > 8, "100Kb with 10KB limit, want > 8 seconds, but got %s", duration.String()) }) ginkgo.It("Proxy Bandwidth Limit by Server", func() { // new test plugin server newFunc := func() *plugin.Request { var r plugin.Request r.Content = &plugin.NewProxyContent{} return &r } pluginPort := f.AllocPort() handler := func(req *plugin.Request) *plugin.Response { var ret plugin.Response content := req.Content.(*plugin.NewProxyContent) content.BandwidthLimit = "10KB" content.BandwidthLimitMode = "server" ret.Content = content return &ret } pluginServer := pluginpkg.NewHTTPPluginServer(pluginPort, newFunc, handler, nil) f.RunServer("", pluginServer) serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` [plugin.test] addr = 127.0.0.1:%d path = /handler ops = NewProxy `, pluginPort) clientConf := consts.LegacyDefaultClientConfig localPort := f.AllocPort() localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(localPort)) f.RunServer("", localServer) remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = %d remote_port = %d `, localPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) content := strings.Repeat("a", 50*1024) // 5KB start := time.Now() framework.NewRequestExpect(f).Port(remotePort).RequestModify(func(r *request.Request) { r.Body([]byte(content)).Timeout(30 * time.Second) }).ExpectResp([]byte(content)).Ensure() duration := time.Since(start) framework.Logf("request duration: %s", duration.String()) framework.ExpectTrue(duration.Seconds() > 8, "100Kb with 10KB limit, want > 8 seconds, but got %s", duration.String()) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/features/group.go
test/e2e/legacy/features/group.go
package features import ( "fmt" "strconv" "sync" "time" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/mock/server/httpserver" "github.com/fatedier/frp/test/e2e/mock/server/streamserver" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: Group]", func() { f := framework.NewDefaultFramework() newHTTPServer := func(port int, respContent string) *httpserver.Server { return httpserver.New( httpserver.WithBindPort(port), httpserver.WithHandler(framework.SpecifiedHTTPBodyHandler([]byte(respContent))), ) } validateFooBarResponse := func(resp *request.Response) bool { if string(resp.Content) == "foo" || string(resp.Content) == "bar" { return true } return false } doFooBarHTTPRequest := func(vhostPort int, host string) []string { results := []string{} var wait sync.WaitGroup var mu sync.Mutex expectFn := func() { framework.NewRequestExpect(f).Port(vhostPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost(host) }). Ensure(validateFooBarResponse, func(resp *request.Response) bool { mu.Lock() defer mu.Unlock() results = append(results, string(resp.Content)) return true }) } for i := 0; i < 10; i++ { wait.Add(1) go func() { defer wait.Done() expectFn() }() } wait.Wait() return results } ginkgo.Describe("Load Balancing", func() { ginkgo.It("TCP", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig fooPort := f.AllocPort() fooServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(fooPort), streamserver.WithRespContent([]byte("foo"))) f.RunServer("", fooServer) barPort := f.AllocPort() barServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(barPort), streamserver.WithRespContent([]byte("bar"))) f.RunServer("", barServer) remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [foo] type = tcp local_port = %d remote_port = %d group = test group_key = 123 [bar] type = tcp local_port = %d remote_port = %d group = test group_key = 123 `, fooPort, remotePort, barPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) fooCount := 0 barCount := 0 for i := 0; i < 10; i++ { framework.NewRequestExpect(f).Explain("times " + strconv.Itoa(i)).Port(remotePort).Ensure(func(resp *request.Response) bool { switch string(resp.Content) { case "foo": fooCount++ case "bar": barCount++ default: return false } return true }) } framework.ExpectTrue(fooCount > 1 && barCount > 1, "fooCount: %d, barCount: %d", fooCount, barCount) }) }) ginkgo.Describe("Health Check", func() { ginkgo.It("TCP", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig fooPort := f.AllocPort() fooServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(fooPort), streamserver.WithRespContent([]byte("foo"))) f.RunServer("", fooServer) barPort := f.AllocPort() barServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(barPort), streamserver.WithRespContent([]byte("bar"))) f.RunServer("", barServer) remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [foo] type = tcp local_port = %d remote_port = %d group = test group_key = 123 health_check_type = tcp health_check_interval_s = 1 [bar] type = tcp local_port = %d remote_port = %d group = test group_key = 123 health_check_type = tcp health_check_interval_s = 1 `, fooPort, remotePort, barPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // check foo and bar is ok results := []string{} for i := 0; i < 10; i++ { framework.NewRequestExpect(f).Port(remotePort).Ensure(validateFooBarResponse, func(resp *request.Response) bool { results = append(results, string(resp.Content)) return true }) } framework.ExpectContainElements(results, []string{"foo", "bar"}) // close bar server, check foo is ok barServer.Close() time.Sleep(2 * time.Second) for i := 0; i < 10; i++ { framework.NewRequestExpect(f).Port(remotePort).ExpectResp([]byte("foo")).Ensure() } // resume bar server, check foo and bar is ok f.RunServer("", barServer) time.Sleep(2 * time.Second) results = []string{} for i := 0; i < 10; i++ { framework.NewRequestExpect(f).Port(remotePort).Ensure(validateFooBarResponse, func(resp *request.Response) bool { results = append(results, string(resp.Content)) return true }) } framework.ExpectContainElements(results, []string{"foo", "bar"}) }) ginkgo.It("HTTP", func() { vhostPort := f.AllocPort() serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` vhost_http_port = %d `, vhostPort) clientConf := consts.LegacyDefaultClientConfig fooPort := f.AllocPort() fooServer := newHTTPServer(fooPort, "foo") f.RunServer("", fooServer) barPort := f.AllocPort() barServer := newHTTPServer(barPort, "bar") f.RunServer("", barServer) clientConf += fmt.Sprintf(` [foo] type = http local_port = %d custom_domains = example.com group = test group_key = 123 health_check_type = http health_check_interval_s = 1 health_check_url = /healthz [bar] type = http local_port = %d custom_domains = example.com group = test group_key = 123 health_check_type = http health_check_interval_s = 1 health_check_url = /healthz `, fooPort, barPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) // send first HTTP request var contents []string framework.NewRequestExpect(f).Port(vhostPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("example.com") }). Ensure(func(resp *request.Response) bool { contents = append(contents, string(resp.Content)) return true }) // send second HTTP request, should be forwarded to another service framework.NewRequestExpect(f).Port(vhostPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("example.com") }). Ensure(func(resp *request.Response) bool { contents = append(contents, string(resp.Content)) return true }) framework.ExpectContainElements(contents, []string{"foo", "bar"}) // check foo and bar is ok results := doFooBarHTTPRequest(vhostPort, "example.com") framework.ExpectContainElements(results, []string{"foo", "bar"}) // close bar server, check foo is ok barServer.Close() time.Sleep(2 * time.Second) results = doFooBarHTTPRequest(vhostPort, "example.com") framework.ExpectContainElements(results, []string{"foo"}) framework.ExpectNotContainElements(results, []string{"bar"}) // resume bar server, check foo and bar is ok f.RunServer("", barServer) time.Sleep(2 * time.Second) results = doFooBarHTTPRequest(vhostPort, "example.com") framework.ExpectContainElements(results, []string{"foo", "bar"}) }) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/features/real_ip.go
test/e2e/legacy/features/real_ip.go
package features import ( "bufio" "fmt" "net" "net/http" "github.com/onsi/ginkgo/v2" pp "github.com/pires/go-proxyproto" "github.com/fatedier/frp/pkg/util/log" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/mock/server/httpserver" "github.com/fatedier/frp/test/e2e/mock/server/streamserver" "github.com/fatedier/frp/test/e2e/pkg/request" "github.com/fatedier/frp/test/e2e/pkg/rpc" ) var _ = ginkgo.Describe("[Feature: Real IP]", func() { f := framework.NewDefaultFramework() ginkgo.It("HTTP X-Forwarded-For", func() { vhostHTTPPort := f.AllocPort() serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` vhost_http_port = %d `, vhostHTTPPort) localPort := f.AllocPort() localServer := httpserver.New( httpserver.WithBindPort(localPort), httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { _, _ = w.Write([]byte(req.Header.Get("X-Forwarded-For"))) })), ) f.RunServer("", localServer) clientConf := consts.LegacyDefaultClientConfig clientConf += fmt.Sprintf(` [test] type = http local_port = %d custom_domains = normal.example.com `, localPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(vhostHTTPPort). RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com") }). ExpectResp([]byte("127.0.0.1")). Ensure() }) ginkgo.Describe("Proxy Protocol", func() { ginkgo.It("TCP", func() { serverConf := consts.LegacyDefaultServerConfig clientConf := consts.LegacyDefaultClientConfig localPort := f.AllocPort() localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(localPort), streamserver.WithCustomHandler(func(c net.Conn) { defer c.Close() rd := bufio.NewReader(c) ppHeader, err := pp.Read(rd) if err != nil { log.Errorf("read proxy protocol error: %v", err) return } for { if _, err := rpc.ReadBytes(rd); err != nil { return } buf := []byte(ppHeader.SourceAddr.String()) _, _ = rpc.WriteBytes(c, buf) } })) f.RunServer("", localServer) remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = %d remote_port = %d proxy_protocol_version = v2 `, localPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure(func(resp *request.Response) bool { log.Tracef("proxy protocol get SourceAddr: %s", string(resp.Content)) addr, err := net.ResolveTCPAddr("tcp", string(resp.Content)) if err != nil { return false } if addr.IP.String() != "127.0.0.1" { return false } return true }) }) ginkgo.It("HTTP", func() { vhostHTTPPort := f.AllocPort() serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` vhost_http_port = %d `, vhostHTTPPort) clientConf := consts.LegacyDefaultClientConfig localPort := f.AllocPort() var srcAddrRecord string localServer := streamserver.New(streamserver.TCP, streamserver.WithBindPort(localPort), streamserver.WithCustomHandler(func(c net.Conn) { defer c.Close() rd := bufio.NewReader(c) ppHeader, err := pp.Read(rd) if err != nil { log.Errorf("read proxy protocol error: %v", err) return } srcAddrRecord = ppHeader.SourceAddr.String() })) f.RunServer("", localServer) clientConf += fmt.Sprintf(` [test] type = http local_port = %d custom_domains = normal.example.com proxy_protocol_version = v2 `, localPort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(vhostHTTPPort).RequestModify(func(r *request.Request) { r.HTTP().HTTPHost("normal.example.com") }).Ensure(framework.ExpectResponseCode(404)) log.Tracef("proxy protocol get SourceAddr: %s", srcAddrRecord) addr, err := net.ResolveTCPAddr("tcp", srcAddrRecord) framework.ExpectNoError(err, srcAddrRecord) framework.ExpectEqualValues("127.0.0.1", addr.IP.String()) }) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/test/e2e/legacy/features/monitor.go
test/e2e/legacy/features/monitor.go
package features import ( "fmt" "strings" "time" "github.com/onsi/ginkgo/v2" "github.com/fatedier/frp/pkg/util/log" "github.com/fatedier/frp/test/e2e/framework" "github.com/fatedier/frp/test/e2e/framework/consts" "github.com/fatedier/frp/test/e2e/pkg/request" ) var _ = ginkgo.Describe("[Feature: Monitor]", func() { f := framework.NewDefaultFramework() ginkgo.It("Prometheus metrics", func() { dashboardPort := f.AllocPort() serverConf := consts.LegacyDefaultServerConfig + fmt.Sprintf(` enable_prometheus = true dashboard_addr = 0.0.0.0 dashboard_port = %d `, dashboardPort) clientConf := consts.LegacyDefaultClientConfig remotePort := f.AllocPort() clientConf += fmt.Sprintf(` [tcp] type = tcp local_port = {{ .%s }} remote_port = %d `, framework.TCPEchoServerPort, remotePort) f.RunProcesses([]string{serverConf}, []string{clientConf}) framework.NewRequestExpect(f).Port(remotePort).Ensure() time.Sleep(500 * time.Millisecond) framework.NewRequestExpect(f).RequestModify(func(r *request.Request) { r.HTTP().Port(dashboardPort).HTTPPath("/metrics") }).Ensure(func(resp *request.Response) bool { log.Tracef("prometheus metrics response: \n%s", resp.Content) if resp.Code != 200 { return false } if !strings.Contains(string(resp.Content), "traffic_in") { return false } return true }) }) })
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/assets/assets.go
assets/assets.go
// 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 assets import ( "io/fs" "net/http" ) var ( // read-only filesystem created by "embed" for embedded files content fs.FS FileSystem http.FileSystem // if prefix is not empty, we get file content from disk prefixPath string ) // if path is empty, load assets in memory // or set FileSystem using disk files func Load(path string) { prefixPath = path if prefixPath != "" { FileSystem = http.Dir(prefixPath) } else { FileSystem = http.FS(content) } } func Register(fileSystem fs.FS) { subFs, err := fs.Sub(fileSystem, "static") if err == nil { content = subFs } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/assets/frps/embed.go
assets/frps/embed.go
package frpc import ( "embed" "github.com/fatedier/frp/assets" ) //go:embed static/* var content embed.FS func init() { assets.Register(content) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/assets/frpc/embed.go
assets/frpc/embed.go
package frpc import ( "embed" "github.com/fatedier/frp/assets" ) //go:embed static/* var content embed.FS func init() { assets.Register(content) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/service.go
server/service.go
// Copyright 2017 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 server import ( "bytes" "context" "crypto/tls" "fmt" "net" "net/http" "os" "strconv" "time" "github.com/fatedier/golib/crypto" "github.com/fatedier/golib/net/mux" fmux "github.com/hashicorp/yamux" quic "github.com/quic-go/quic-go" "github.com/samber/lo" "github.com/fatedier/frp/pkg/auth" v1 "github.com/fatedier/frp/pkg/config/v1" modelmetrics "github.com/fatedier/frp/pkg/metrics" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/nathole" plugin "github.com/fatedier/frp/pkg/plugin/server" "github.com/fatedier/frp/pkg/ssh" "github.com/fatedier/frp/pkg/transport" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/tcpmux" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/version" "github.com/fatedier/frp/pkg/util/vhost" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/server/controller" "github.com/fatedier/frp/server/group" "github.com/fatedier/frp/server/metrics" "github.com/fatedier/frp/server/ports" "github.com/fatedier/frp/server/proxy" "github.com/fatedier/frp/server/visitor" ) const ( connReadTimeout time.Duration = 10 * time.Second vhostReadWriteTimeout time.Duration = 30 * time.Second ) func init() { crypto.DefaultSalt = "frp" // Disable quic-go's receive buffer warning. os.Setenv("QUIC_GO_DISABLE_RECEIVE_BUFFER_WARNING", "true") // Disable quic-go's ECN support by default. It may cause issues on certain operating systems. if os.Getenv("QUIC_GO_DISABLE_ECN") == "" { os.Setenv("QUIC_GO_DISABLE_ECN", "true") } } // Server service type Service struct { // Dispatch connections to different handlers listen on same port muxer *mux.Mux // Accept connections from client listener net.Listener // Accept connections using kcp kcpListener net.Listener // Accept connections using quic quicListener *quic.Listener // Accept connections using websocket websocketListener net.Listener // Accept frp tls connections tlsListener net.Listener // Accept pipe connections from ssh tunnel gateway sshTunnelListener *netpkg.InternalListener // Manage all controllers ctlManager *ControlManager // Manage all proxies pxyManager *proxy.Manager // Manage all plugins pluginManager *plugin.Manager // HTTP vhost router httpVhostRouter *vhost.Routers // All resource managers and controllers rc *controller.ResourceController // web server for dashboard UI and apis webServer *httppkg.Server sshTunnelGateway *ssh.Gateway // Auth runtime and encryption materials auth *auth.ServerAuth tlsConfig *tls.Config cfg *v1.ServerConfig // service context ctx context.Context // call cancel to stop service cancel context.CancelFunc } func NewService(cfg *v1.ServerConfig) (*Service, error) { tlsConfig, err := transport.NewServerTLSConfig( cfg.Transport.TLS.CertFile, cfg.Transport.TLS.KeyFile, cfg.Transport.TLS.TrustedCaFile) if err != nil { return nil, err } var webServer *httppkg.Server if cfg.WebServer.Port > 0 { ws, err := httppkg.NewServer(cfg.WebServer) if err != nil { return nil, err } webServer = ws modelmetrics.EnableMem() if cfg.EnablePrometheus { modelmetrics.EnablePrometheus() } } authRuntime, err := auth.BuildServerAuth(&cfg.Auth) if err != nil { return nil, err } svr := &Service{ ctlManager: NewControlManager(), pxyManager: proxy.NewManager(), pluginManager: plugin.NewManager(), rc: &controller.ResourceController{ VisitorManager: visitor.NewManager(), TCPPortManager: ports.NewManager("tcp", cfg.ProxyBindAddr, cfg.AllowPorts), UDPPortManager: ports.NewManager("udp", cfg.ProxyBindAddr, cfg.AllowPorts), }, sshTunnelListener: netpkg.NewInternalListener(), httpVhostRouter: vhost.NewRouters(), auth: authRuntime, webServer: webServer, tlsConfig: tlsConfig, cfg: cfg, ctx: context.Background(), } if webServer != nil { webServer.RouteRegister(svr.registerRouteHandlers) } // Create tcpmux httpconnect multiplexer. if cfg.TCPMuxHTTPConnectPort > 0 { var l net.Listener address := net.JoinHostPort(cfg.ProxyBindAddr, strconv.Itoa(cfg.TCPMuxHTTPConnectPort)) l, err = net.Listen("tcp", address) if err != nil { return nil, fmt.Errorf("create server listener error, %v", err) } svr.rc.TCPMuxHTTPConnectMuxer, err = tcpmux.NewHTTPConnectTCPMuxer(l, cfg.TCPMuxPassthrough, vhostReadWriteTimeout) if err != nil { return nil, fmt.Errorf("create vhost tcpMuxer error, %v", err) } log.Infof("tcpmux httpconnect multiplexer listen on %s, passthough: %v", address, cfg.TCPMuxPassthrough) } // Init all plugins for _, p := range cfg.HTTPPlugins { svr.pluginManager.Register(plugin.NewHTTPPluginOptions(p)) log.Infof("plugin [%s] has been registered", p.Name) } svr.rc.PluginManager = svr.pluginManager // Init group controller svr.rc.TCPGroupCtl = group.NewTCPGroupCtl(svr.rc.TCPPortManager) // Init HTTP group controller svr.rc.HTTPGroupCtl = group.NewHTTPGroupController(svr.httpVhostRouter) // Init TCP mux group controller svr.rc.TCPMuxGroupCtl = group.NewTCPMuxGroupCtl(svr.rc.TCPMuxHTTPConnectMuxer) // Init 404 not found page vhost.NotFoundPagePath = cfg.Custom404Page var ( httpMuxOn bool httpsMuxOn bool ) if cfg.BindAddr == cfg.ProxyBindAddr { if cfg.BindPort == cfg.VhostHTTPPort { httpMuxOn = true } if cfg.BindPort == cfg.VhostHTTPSPort { httpsMuxOn = true } } // Listen for accepting connections from client. address := net.JoinHostPort(cfg.BindAddr, strconv.Itoa(cfg.BindPort)) ln, err := net.Listen("tcp", address) if err != nil { return nil, fmt.Errorf("create server listener error, %v", err) } svr.muxer = mux.NewMux(ln) svr.muxer.SetKeepAlive(time.Duration(cfg.Transport.TCPKeepAlive) * time.Second) go func() { _ = svr.muxer.Serve() }() ln = svr.muxer.DefaultListener() svr.listener = ln log.Infof("frps tcp listen on %s", address) // Listen for accepting connections from client using kcp protocol. if cfg.KCPBindPort > 0 { address := net.JoinHostPort(cfg.BindAddr, strconv.Itoa(cfg.KCPBindPort)) svr.kcpListener, err = netpkg.ListenKcp(address) if err != nil { return nil, fmt.Errorf("listen on kcp udp address %s error: %v", address, err) } log.Infof("frps kcp listen on udp %s", address) } if cfg.QUICBindPort > 0 { address := net.JoinHostPort(cfg.BindAddr, strconv.Itoa(cfg.QUICBindPort)) quicTLSCfg := tlsConfig.Clone() quicTLSCfg.NextProtos = []string{"frp"} svr.quicListener, err = quic.ListenAddr(address, quicTLSCfg, &quic.Config{ MaxIdleTimeout: time.Duration(cfg.Transport.QUIC.MaxIdleTimeout) * time.Second, MaxIncomingStreams: int64(cfg.Transport.QUIC.MaxIncomingStreams), KeepAlivePeriod: time.Duration(cfg.Transport.QUIC.KeepalivePeriod) * time.Second, }) if err != nil { return nil, fmt.Errorf("listen on quic udp address %s error: %v", address, err) } log.Infof("frps quic listen on %s", address) } if cfg.SSHTunnelGateway.BindPort > 0 { sshGateway, err := ssh.NewGateway(cfg.SSHTunnelGateway, cfg.BindAddr, svr.sshTunnelListener) if err != nil { return nil, fmt.Errorf("create ssh gateway error: %v", err) } svr.sshTunnelGateway = sshGateway log.Infof("frps sshTunnelGateway listen on port %d", cfg.SSHTunnelGateway.BindPort) } // Listen for accepting connections from client using websocket protocol. websocketPrefix := []byte("GET " + netpkg.FrpWebsocketPath) websocketLn := svr.muxer.Listen(0, uint32(len(websocketPrefix)), func(data []byte) bool { return bytes.Equal(data, websocketPrefix) }) svr.websocketListener = netpkg.NewWebsocketListener(websocketLn) // Create http vhost muxer. if cfg.VhostHTTPPort > 0 { rp := vhost.NewHTTPReverseProxy(vhost.HTTPReverseProxyOptions{ ResponseHeaderTimeoutS: cfg.VhostHTTPTimeout, }, svr.httpVhostRouter) svr.rc.HTTPReverseProxy = rp address := net.JoinHostPort(cfg.ProxyBindAddr, strconv.Itoa(cfg.VhostHTTPPort)) server := &http.Server{ Addr: address, Handler: rp, ReadHeaderTimeout: 60 * time.Second, } var l net.Listener if httpMuxOn { l = svr.muxer.ListenHTTP(1) } else { l, err = net.Listen("tcp", address) if err != nil { return nil, fmt.Errorf("create vhost http listener error, %v", err) } } go func() { _ = server.Serve(l) }() log.Infof("http service listen on %s", address) } // Create https vhost muxer. if cfg.VhostHTTPSPort > 0 { var l net.Listener if httpsMuxOn { l = svr.muxer.ListenHTTPS(1) } else { address := net.JoinHostPort(cfg.ProxyBindAddr, strconv.Itoa(cfg.VhostHTTPSPort)) l, err = net.Listen("tcp", address) if err != nil { return nil, fmt.Errorf("create server listener error, %v", err) } log.Infof("https service listen on %s", address) } svr.rc.VhostHTTPSMuxer, err = vhost.NewHTTPSMuxer(l, vhostReadWriteTimeout) if err != nil { return nil, fmt.Errorf("create vhost httpsMuxer error, %v", err) } // Init HTTPS group controller after HTTPSMuxer is created svr.rc.HTTPSGroupCtl = group.NewHTTPSGroupController(svr.rc.VhostHTTPSMuxer) } // frp tls listener svr.tlsListener = svr.muxer.Listen(2, 1, func(data []byte) bool { // tls first byte can be 0x16 only when vhost https port is not same with bind port return int(data[0]) == netpkg.FRPTLSHeadByte || int(data[0]) == 0x16 }) // Create nat hole controller. nc, err := nathole.NewController(time.Duration(cfg.NatHoleAnalysisDataReserveHours) * time.Hour) if err != nil { return nil, fmt.Errorf("create nat hole controller error, %v", err) } svr.rc.NatHoleController = nc return svr, nil } func (svr *Service) Run(ctx context.Context) { ctx, cancel := context.WithCancel(ctx) svr.ctx = ctx svr.cancel = cancel // run dashboard web server. if svr.webServer != nil { go func() { log.Infof("dashboard listen on %s", svr.webServer.Address()) if err := svr.webServer.Run(); err != nil { log.Warnf("dashboard server exit with error: %v", err) } }() } go svr.HandleListener(svr.sshTunnelListener, true) if svr.kcpListener != nil { go svr.HandleListener(svr.kcpListener, false) } if svr.quicListener != nil { go svr.HandleQUICListener(svr.quicListener) } go svr.HandleListener(svr.websocketListener, false) go svr.HandleListener(svr.tlsListener, false) if svr.rc.NatHoleController != nil { go svr.rc.NatHoleController.CleanWorker(svr.ctx) } if svr.sshTunnelGateway != nil { go svr.sshTunnelGateway.Run() } svr.HandleListener(svr.listener, false) <-svr.ctx.Done() // service context may not be canceled by svr.Close(), we should call it here to release resources if svr.listener != nil { svr.Close() } } func (svr *Service) Close() error { if svr.kcpListener != nil { svr.kcpListener.Close() } if svr.quicListener != nil { svr.quicListener.Close() } if svr.websocketListener != nil { svr.websocketListener.Close() } if svr.tlsListener != nil { svr.tlsListener.Close() } if svr.sshTunnelListener != nil { svr.sshTunnelListener.Close() } if svr.listener != nil { svr.listener.Close() } if svr.webServer != nil { svr.webServer.Close() } if svr.sshTunnelGateway != nil { svr.sshTunnelGateway.Close() } svr.rc.Close() svr.muxer.Close() svr.ctlManager.Close() if svr.cancel != nil { svr.cancel() } return nil } func (svr *Service) handleConnection(ctx context.Context, conn net.Conn, internal bool) { xl := xlog.FromContextSafe(ctx) var ( rawMsg msg.Message err error ) _ = conn.SetReadDeadline(time.Now().Add(connReadTimeout)) if rawMsg, err = msg.ReadMsg(conn); err != nil { log.Tracef("failed to read message: %v", err) conn.Close() return } _ = conn.SetReadDeadline(time.Time{}) switch m := rawMsg.(type) { case *msg.Login: // server plugin hook content := &plugin.LoginContent{ Login: *m, ClientAddress: conn.RemoteAddr().String(), } retContent, err := svr.pluginManager.Login(content) if err == nil { m = &retContent.Login err = svr.RegisterControl(conn, m, internal) } // If login failed, send error message there. // Otherwise send success message in control's work goroutine. if err != nil { xl.Warnf("register control error: %v", err) _ = msg.WriteMsg(conn, &msg.LoginResp{ Version: version.Full(), Error: util.GenerateResponseErrorString("register control error", err, lo.FromPtr(svr.cfg.DetailedErrorsToClient)), }) conn.Close() } case *msg.NewWorkConn: if err := svr.RegisterWorkConn(conn, m); err != nil { conn.Close() } case *msg.NewVisitorConn: if err = svr.RegisterVisitorConn(conn, m); err != nil { xl.Warnf("register visitor conn error: %v", err) _ = msg.WriteMsg(conn, &msg.NewVisitorConnResp{ ProxyName: m.ProxyName, Error: util.GenerateResponseErrorString("register visitor conn error", err, lo.FromPtr(svr.cfg.DetailedErrorsToClient)), }) conn.Close() } else { _ = msg.WriteMsg(conn, &msg.NewVisitorConnResp{ ProxyName: m.ProxyName, Error: "", }) } default: log.Warnf("error message type for the new connection [%s]", conn.RemoteAddr().String()) conn.Close() } } // HandleListener accepts connections from client and call handleConnection to handle them. // If internal is true, it means that this listener is used for internal communication like ssh tunnel gateway. // TODO(fatedier): Pass some parameters of listener/connection through context to avoid passing too many parameters. func (svr *Service) HandleListener(l net.Listener, internal bool) { // Listen for incoming connections from client. for { c, err := l.Accept() if err != nil { log.Warnf("listener for incoming connections from client closed") return } // inject xlog object into net.Conn context xl := xlog.New() ctx := context.Background() c = netpkg.NewContextConn(xlog.NewContext(ctx, xl), c) if !internal { log.Tracef("start check TLS connection...") originConn := c forceTLS := svr.cfg.Transport.TLS.Force var isTLS, custom bool c, isTLS, custom, err = netpkg.CheckAndEnableTLSServerConnWithTimeout(c, svr.tlsConfig, forceTLS, connReadTimeout) if err != nil { log.Warnf("checkAndEnableTLSServerConnWithTimeout error: %v", err) originConn.Close() continue } log.Tracef("check TLS connection success, isTLS: %v custom: %v internal: %v", isTLS, custom, internal) } // Start a new goroutine to handle connection. go func(ctx context.Context, frpConn net.Conn) { if lo.FromPtr(svr.cfg.Transport.TCPMux) && !internal { fmuxCfg := fmux.DefaultConfig() fmuxCfg.KeepAliveInterval = time.Duration(svr.cfg.Transport.TCPMuxKeepaliveInterval) * time.Second // Use trace level for yamux logs fmuxCfg.LogOutput = xlog.NewTraceWriter(xlog.FromContextSafe(ctx)) fmuxCfg.MaxStreamWindowSize = 6 * 1024 * 1024 session, err := fmux.Server(frpConn, fmuxCfg) if err != nil { log.Warnf("failed to create mux connection: %v", err) frpConn.Close() return } for { stream, err := session.AcceptStream() if err != nil { log.Debugf("accept new mux stream error: %v", err) session.Close() return } go svr.handleConnection(ctx, stream, internal) } } else { svr.handleConnection(ctx, frpConn, internal) } }(ctx, c) } } func (svr *Service) HandleQUICListener(l *quic.Listener) { // Listen for incoming connections from client. for { c, err := l.Accept(context.Background()) if err != nil { log.Warnf("quic listener for incoming connections from client closed") return } // Start a new goroutine to handle connection. go func(ctx context.Context, frpConn *quic.Conn) { for { stream, err := frpConn.AcceptStream(context.Background()) if err != nil { log.Debugf("accept new quic mux stream error: %v", err) _ = frpConn.CloseWithError(0, "") return } go svr.handleConnection(ctx, netpkg.QuicStreamToNetConn(stream, frpConn), false) } }(context.Background(), c) } } func (svr *Service) RegisterControl(ctlConn net.Conn, loginMsg *msg.Login, internal bool) error { // If client's RunID is empty, it's a new client, we just create a new controller. // Otherwise, we check if there is one controller has the same run id. If so, we release previous controller and start new one. var err error if loginMsg.RunID == "" { loginMsg.RunID, err = util.RandID() if err != nil { return err } } ctx := netpkg.NewContextFromConn(ctlConn) xl := xlog.FromContextSafe(ctx) xl.AppendPrefix(loginMsg.RunID) ctx = xlog.NewContext(ctx, xl) xl.Infof("client login info: ip [%s] version [%s] hostname [%s] os [%s] arch [%s]", ctlConn.RemoteAddr().String(), loginMsg.Version, loginMsg.Hostname, loginMsg.Os, loginMsg.Arch) // Check auth. authVerifier := svr.auth.Verifier if internal && loginMsg.ClientSpec.AlwaysAuthPass { authVerifier = auth.AlwaysPassVerifier } if err := authVerifier.VerifyLogin(loginMsg); err != nil { return err } // TODO(fatedier): use SessionContext ctl, err := NewControl(ctx, svr.rc, svr.pxyManager, svr.pluginManager, authVerifier, svr.auth.EncryptionKey(), ctlConn, !internal, loginMsg, svr.cfg) if err != nil { xl.Warnf("create new controller error: %v", err) // don't return detailed errors to client return fmt.Errorf("unexpected error when creating new controller") } if oldCtl := svr.ctlManager.Add(loginMsg.RunID, ctl); oldCtl != nil { oldCtl.WaitClosed() } ctl.Start() // for statistics metrics.Server.NewClient() go func() { // block until control closed ctl.WaitClosed() svr.ctlManager.Del(loginMsg.RunID, ctl) }() return nil } // RegisterWorkConn register a new work connection to control and proxies need it. func (svr *Service) RegisterWorkConn(workConn net.Conn, newMsg *msg.NewWorkConn) error { xl := netpkg.NewLogFromConn(workConn) ctl, exist := svr.ctlManager.GetByID(newMsg.RunID) if !exist { xl.Warnf("no client control found for run id [%s]", newMsg.RunID) return fmt.Errorf("no client control found for run id [%s]", newMsg.RunID) } // server plugin hook content := &plugin.NewWorkConnContent{ User: plugin.UserInfo{ User: ctl.loginMsg.User, Metas: ctl.loginMsg.Metas, RunID: ctl.loginMsg.RunID, }, NewWorkConn: *newMsg, } retContent, err := svr.pluginManager.NewWorkConn(content) if err == nil { newMsg = &retContent.NewWorkConn // Check auth. err = ctl.authVerifier.VerifyNewWorkConn(newMsg) } if err != nil { xl.Warnf("invalid NewWorkConn with run id [%s]", newMsg.RunID) _ = msg.WriteMsg(workConn, &msg.StartWorkConn{ Error: util.GenerateResponseErrorString("invalid NewWorkConn", err, lo.FromPtr(svr.cfg.DetailedErrorsToClient)), }) return fmt.Errorf("invalid NewWorkConn with run id [%s]", newMsg.RunID) } return ctl.RegisterWorkConn(workConn) } func (svr *Service) RegisterVisitorConn(visitorConn net.Conn, newMsg *msg.NewVisitorConn) error { visitorUser := "" // TODO(deprecation): Compatible with old versions, can be without runID, user is empty. In later versions, it will be mandatory to include runID. // If runID is required, it is not compatible with versions prior to v0.50.0. if newMsg.RunID != "" { ctl, exist := svr.ctlManager.GetByID(newMsg.RunID) if !exist { return fmt.Errorf("no client control found for run id [%s]", newMsg.RunID) } visitorUser = ctl.loginMsg.User } return svr.rc.VisitorManager.NewConn(newMsg.ProxyName, visitorConn, newMsg.Timestamp, newMsg.SignKey, newMsg.UseEncryption, newMsg.UseCompression, visitorUser) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/dashboard_api.go
server/dashboard_api.go
// Copyright 2017 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 server import ( "cmp" "encoding/json" "net/http" "slices" "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/fatedier/frp/pkg/config/types" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/metrics/mem" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/version" ) type GeneralResponse struct { Code int Msg string } func (svr *Service) registerRouteHandlers(helper *httppkg.RouterRegisterHelper) { helper.Router.HandleFunc("/healthz", svr.healthz) subRouter := helper.Router.NewRoute().Subrouter() subRouter.Use(helper.AuthMiddleware.Middleware) // metrics if svr.cfg.EnablePrometheus { subRouter.Handle("/metrics", promhttp.Handler()) } // apis subRouter.HandleFunc("/api/serverinfo", svr.apiServerInfo).Methods("GET") subRouter.HandleFunc("/api/proxy/{type}", svr.apiProxyByType).Methods("GET") subRouter.HandleFunc("/api/proxy/{type}/{name}", svr.apiProxyByTypeAndName).Methods("GET") subRouter.HandleFunc("/api/traffic/{name}", svr.apiProxyTraffic).Methods("GET") subRouter.HandleFunc("/api/proxies", svr.deleteProxies).Methods("DELETE") // view subRouter.Handle("/favicon.ico", http.FileServer(helper.AssetsFS)).Methods("GET") subRouter.PathPrefix("/static/").Handler( netpkg.MakeHTTPGzipHandler(http.StripPrefix("/static/", http.FileServer(helper.AssetsFS))), ).Methods("GET") subRouter.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/static/", http.StatusMovedPermanently) }) } type serverInfoResp struct { Version string `json:"version"` BindPort int `json:"bindPort"` VhostHTTPPort int `json:"vhostHTTPPort"` VhostHTTPSPort int `json:"vhostHTTPSPort"` TCPMuxHTTPConnectPort int `json:"tcpmuxHTTPConnectPort"` KCPBindPort int `json:"kcpBindPort"` QUICBindPort int `json:"quicBindPort"` SubdomainHost string `json:"subdomainHost"` MaxPoolCount int64 `json:"maxPoolCount"` MaxPortsPerClient int64 `json:"maxPortsPerClient"` HeartBeatTimeout int64 `json:"heartbeatTimeout"` AllowPortsStr string `json:"allowPortsStr,omitempty"` TLSForce bool `json:"tlsForce,omitempty"` TotalTrafficIn int64 `json:"totalTrafficIn"` TotalTrafficOut int64 `json:"totalTrafficOut"` CurConns int64 `json:"curConns"` ClientCounts int64 `json:"clientCounts"` ProxyTypeCounts map[string]int64 `json:"proxyTypeCount"` } // /healthz func (svr *Service) healthz(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) } // /api/serverinfo func (svr *Service) apiServerInfo(w http.ResponseWriter, r *http.Request) { res := GeneralResponse{Code: 200} defer func() { log.Infof("http response [%s]: code [%d]", r.URL.Path, res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() log.Infof("http request: [%s]", r.URL.Path) serverStats := mem.StatsCollector.GetServer() svrResp := serverInfoResp{ Version: version.Full(), BindPort: svr.cfg.BindPort, VhostHTTPPort: svr.cfg.VhostHTTPPort, VhostHTTPSPort: svr.cfg.VhostHTTPSPort, TCPMuxHTTPConnectPort: svr.cfg.TCPMuxHTTPConnectPort, KCPBindPort: svr.cfg.KCPBindPort, QUICBindPort: svr.cfg.QUICBindPort, SubdomainHost: svr.cfg.SubDomainHost, MaxPoolCount: svr.cfg.Transport.MaxPoolCount, MaxPortsPerClient: svr.cfg.MaxPortsPerClient, HeartBeatTimeout: svr.cfg.Transport.HeartbeatTimeout, AllowPortsStr: types.PortsRangeSlice(svr.cfg.AllowPorts).String(), TLSForce: svr.cfg.Transport.TLS.Force, TotalTrafficIn: serverStats.TotalTrafficIn, TotalTrafficOut: serverStats.TotalTrafficOut, CurConns: serverStats.CurConns, ClientCounts: serverStats.ClientCounts, ProxyTypeCounts: serverStats.ProxyTypeCounts, } buf, _ := json.Marshal(&svrResp) res.Msg = string(buf) } type BaseOutConf struct { v1.ProxyBaseConfig } type TCPOutConf struct { BaseOutConf RemotePort int `json:"remotePort"` } type TCPMuxOutConf struct { BaseOutConf v1.DomainConfig Multiplexer string `json:"multiplexer"` RouteByHTTPUser string `json:"routeByHTTPUser"` } type UDPOutConf struct { BaseOutConf RemotePort int `json:"remotePort"` } type HTTPOutConf struct { BaseOutConf v1.DomainConfig Locations []string `json:"locations"` HostHeaderRewrite string `json:"hostHeaderRewrite"` } type HTTPSOutConf struct { BaseOutConf v1.DomainConfig } type STCPOutConf struct { BaseOutConf } type XTCPOutConf struct { BaseOutConf } func getConfByType(proxyType string) any { switch v1.ProxyType(proxyType) { case v1.ProxyTypeTCP: return &TCPOutConf{} case v1.ProxyTypeTCPMUX: return &TCPMuxOutConf{} case v1.ProxyTypeUDP: return &UDPOutConf{} case v1.ProxyTypeHTTP: return &HTTPOutConf{} case v1.ProxyTypeHTTPS: return &HTTPSOutConf{} case v1.ProxyTypeSTCP: return &STCPOutConf{} case v1.ProxyTypeXTCP: return &XTCPOutConf{} default: return nil } } // Get proxy info. type ProxyStatsInfo struct { Name string `json:"name"` Conf any `json:"conf"` ClientVersion string `json:"clientVersion,omitempty"` TodayTrafficIn int64 `json:"todayTrafficIn"` TodayTrafficOut int64 `json:"todayTrafficOut"` CurConns int64 `json:"curConns"` LastStartTime string `json:"lastStartTime"` LastCloseTime string `json:"lastCloseTime"` Status string `json:"status"` } type GetProxyInfoResp struct { Proxies []*ProxyStatsInfo `json:"proxies"` } // /api/proxy/:type func (svr *Service) apiProxyByType(w http.ResponseWriter, r *http.Request) { res := GeneralResponse{Code: 200} params := mux.Vars(r) proxyType := params["type"] defer func() { log.Infof("http response [%s]: code [%d]", r.URL.Path, res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() log.Infof("http request: [%s]", r.URL.Path) proxyInfoResp := GetProxyInfoResp{} proxyInfoResp.Proxies = svr.getProxyStatsByType(proxyType) slices.SortFunc(proxyInfoResp.Proxies, func(a, b *ProxyStatsInfo) int { return cmp.Compare(a.Name, b.Name) }) buf, _ := json.Marshal(&proxyInfoResp) res.Msg = string(buf) } func (svr *Service) getProxyStatsByType(proxyType string) (proxyInfos []*ProxyStatsInfo) { proxyStats := mem.StatsCollector.GetProxiesByType(proxyType) proxyInfos = make([]*ProxyStatsInfo, 0, len(proxyStats)) for _, ps := range proxyStats { proxyInfo := &ProxyStatsInfo{} if pxy, ok := svr.pxyManager.GetByName(ps.Name); ok { content, err := json.Marshal(pxy.GetConfigurer()) if err != nil { log.Warnf("marshal proxy [%s] conf info error: %v", ps.Name, err) continue } proxyInfo.Conf = getConfByType(ps.Type) if err = json.Unmarshal(content, &proxyInfo.Conf); err != nil { log.Warnf("unmarshal proxy [%s] conf info error: %v", ps.Name, err) continue } proxyInfo.Status = "online" if pxy.GetLoginMsg() != nil { proxyInfo.ClientVersion = pxy.GetLoginMsg().Version } } else { proxyInfo.Status = "offline" } proxyInfo.Name = ps.Name proxyInfo.TodayTrafficIn = ps.TodayTrafficIn proxyInfo.TodayTrafficOut = ps.TodayTrafficOut proxyInfo.CurConns = ps.CurConns proxyInfo.LastStartTime = ps.LastStartTime proxyInfo.LastCloseTime = ps.LastCloseTime proxyInfos = append(proxyInfos, proxyInfo) } return } // Get proxy info by name. type GetProxyStatsResp struct { Name string `json:"name"` Conf any `json:"conf"` TodayTrafficIn int64 `json:"todayTrafficIn"` TodayTrafficOut int64 `json:"todayTrafficOut"` CurConns int64 `json:"curConns"` LastStartTime string `json:"lastStartTime"` LastCloseTime string `json:"lastCloseTime"` Status string `json:"status"` } // /api/proxy/:type/:name func (svr *Service) apiProxyByTypeAndName(w http.ResponseWriter, r *http.Request) { res := GeneralResponse{Code: 200} params := mux.Vars(r) proxyType := params["type"] name := params["name"] defer func() { log.Infof("http response [%s]: code [%d]", r.URL.Path, res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() log.Infof("http request: [%s]", r.URL.Path) var proxyStatsResp GetProxyStatsResp proxyStatsResp, res.Code, res.Msg = svr.getProxyStatsByTypeAndName(proxyType, name) if res.Code != 200 { return } buf, _ := json.Marshal(&proxyStatsResp) res.Msg = string(buf) } func (svr *Service) getProxyStatsByTypeAndName(proxyType string, proxyName string) (proxyInfo GetProxyStatsResp, code int, msg string) { proxyInfo.Name = proxyName ps := mem.StatsCollector.GetProxiesByTypeAndName(proxyType, proxyName) if ps == nil { code = 404 msg = "no proxy info found" } else { if pxy, ok := svr.pxyManager.GetByName(proxyName); ok { content, err := json.Marshal(pxy.GetConfigurer()) if err != nil { log.Warnf("marshal proxy [%s] conf info error: %v", ps.Name, err) code = 400 msg = "parse conf error" return } proxyInfo.Conf = getConfByType(ps.Type) if err = json.Unmarshal(content, &proxyInfo.Conf); err != nil { log.Warnf("unmarshal proxy [%s] conf info error: %v", ps.Name, err) code = 400 msg = "parse conf error" return } proxyInfo.Status = "online" } else { proxyInfo.Status = "offline" } proxyInfo.TodayTrafficIn = ps.TodayTrafficIn proxyInfo.TodayTrafficOut = ps.TodayTrafficOut proxyInfo.CurConns = ps.CurConns proxyInfo.LastStartTime = ps.LastStartTime proxyInfo.LastCloseTime = ps.LastCloseTime code = 200 } return } // /api/traffic/:name type GetProxyTrafficResp struct { Name string `json:"name"` TrafficIn []int64 `json:"trafficIn"` TrafficOut []int64 `json:"trafficOut"` } func (svr *Service) apiProxyTraffic(w http.ResponseWriter, r *http.Request) { res := GeneralResponse{Code: 200} params := mux.Vars(r) name := params["name"] defer func() { log.Infof("http response [%s]: code [%d]", r.URL.Path, res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() log.Infof("http request: [%s]", r.URL.Path) trafficResp := GetProxyTrafficResp{} trafficResp.Name = name proxyTrafficInfo := mem.StatsCollector.GetProxyTraffic(name) if proxyTrafficInfo == nil { res.Code = 404 res.Msg = "no proxy info found" return } trafficResp.TrafficIn = proxyTrafficInfo.TrafficIn trafficResp.TrafficOut = proxyTrafficInfo.TrafficOut buf, _ := json.Marshal(&trafficResp) res.Msg = string(buf) } // DELETE /api/proxies?status=offline func (svr *Service) deleteProxies(w http.ResponseWriter, r *http.Request) { res := GeneralResponse{Code: 200} log.Infof("http request: [%s]", r.URL.Path) defer func() { log.Infof("http response [%s]: code [%d]", r.URL.Path, res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() status := r.URL.Query().Get("status") if status != "offline" { res.Code = 400 res.Msg = "status only support offline" return } cleared, total := mem.StatsCollector.ClearOfflineProxies() log.Infof("cleared [%d] offline proxies, total [%d] proxies", cleared, total) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/control.go
server/control.go
// Copyright 2017 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 server import ( "context" "fmt" "net" "runtime/debug" "sync" "sync/atomic" "time" "github.com/samber/lo" "github.com/fatedier/frp/pkg/auth" "github.com/fatedier/frp/pkg/config" v1 "github.com/fatedier/frp/pkg/config/v1" pkgerr "github.com/fatedier/frp/pkg/errors" "github.com/fatedier/frp/pkg/msg" plugin "github.com/fatedier/frp/pkg/plugin/server" "github.com/fatedier/frp/pkg/transport" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/version" "github.com/fatedier/frp/pkg/util/wait" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/server/controller" "github.com/fatedier/frp/server/metrics" "github.com/fatedier/frp/server/proxy" ) type ControlManager struct { // controls indexed by run id ctlsByRunID map[string]*Control mu sync.RWMutex } func NewControlManager() *ControlManager { return &ControlManager{ ctlsByRunID: make(map[string]*Control), } } func (cm *ControlManager) Add(runID string, ctl *Control) (old *Control) { cm.mu.Lock() defer cm.mu.Unlock() var ok bool old, ok = cm.ctlsByRunID[runID] if ok { old.Replaced(ctl) } cm.ctlsByRunID[runID] = ctl return } // we should make sure if it's the same control to prevent delete a new one func (cm *ControlManager) Del(runID string, ctl *Control) { cm.mu.Lock() defer cm.mu.Unlock() if c, ok := cm.ctlsByRunID[runID]; ok && c == ctl { delete(cm.ctlsByRunID, runID) } } func (cm *ControlManager) GetByID(runID string) (ctl *Control, ok bool) { cm.mu.RLock() defer cm.mu.RUnlock() ctl, ok = cm.ctlsByRunID[runID] return } func (cm *ControlManager) Close() error { cm.mu.Lock() defer cm.mu.Unlock() for _, ctl := range cm.ctlsByRunID { ctl.Close() } cm.ctlsByRunID = make(map[string]*Control) return nil } type Control struct { // all resource managers and controllers rc *controller.ResourceController // proxy manager pxyManager *proxy.Manager // plugin manager pluginManager *plugin.Manager // verifies authentication based on selected method authVerifier auth.Verifier // key used for connection encryption encryptionKey []byte // other components can use this to communicate with client msgTransporter transport.MessageTransporter // msgDispatcher is a wrapper for control connection. // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types. msgDispatcher *msg.Dispatcher // login message loginMsg *msg.Login // control connection conn net.Conn // work connections workConnCh chan net.Conn // proxies in one client proxies map[string]proxy.Proxy // pool count poolCount int // ports used, for limitations portsUsedNum int // last time got the Ping message lastPing atomic.Value // A new run id will be generated when a new client login. // If run id got from login message has same run id, it means it's the same client, so we can // replace old controller instantly. runID string mu sync.RWMutex // Server configuration information serverCfg *v1.ServerConfig xl *xlog.Logger ctx context.Context doneCh chan struct{} } // TODO(fatedier): Referencing the implementation of frpc, encapsulate the input parameters as SessionContext. func NewControl( ctx context.Context, rc *controller.ResourceController, pxyManager *proxy.Manager, pluginManager *plugin.Manager, authVerifier auth.Verifier, encryptionKey []byte, ctlConn net.Conn, ctlConnEncrypted bool, loginMsg *msg.Login, serverCfg *v1.ServerConfig, ) (*Control, error) { poolCount := loginMsg.PoolCount if poolCount > int(serverCfg.Transport.MaxPoolCount) { poolCount = int(serverCfg.Transport.MaxPoolCount) } ctl := &Control{ rc: rc, pxyManager: pxyManager, pluginManager: pluginManager, authVerifier: authVerifier, encryptionKey: encryptionKey, conn: ctlConn, loginMsg: loginMsg, workConnCh: make(chan net.Conn, poolCount+10), proxies: make(map[string]proxy.Proxy), poolCount: poolCount, portsUsedNum: 0, runID: loginMsg.RunID, serverCfg: serverCfg, xl: xlog.FromContextSafe(ctx), ctx: ctx, doneCh: make(chan struct{}), } ctl.lastPing.Store(time.Now()) if ctlConnEncrypted { cryptoRW, err := netpkg.NewCryptoReadWriter(ctl.conn, ctl.encryptionKey) if err != nil { return nil, err } ctl.msgDispatcher = msg.NewDispatcher(cryptoRW) } else { ctl.msgDispatcher = msg.NewDispatcher(ctl.conn) } ctl.registerMsgHandlers() ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher) return ctl, nil } // Start send a login success message to client and start working. func (ctl *Control) Start() { loginRespMsg := &msg.LoginResp{ Version: version.Full(), RunID: ctl.runID, Error: "", } _ = msg.WriteMsg(ctl.conn, loginRespMsg) go func() { for i := 0; i < ctl.poolCount; i++ { // ignore error here, that means that this control is closed _ = ctl.msgDispatcher.Send(&msg.ReqWorkConn{}) } }() go ctl.worker() } func (ctl *Control) Close() error { ctl.conn.Close() return nil } func (ctl *Control) Replaced(newCtl *Control) { xl := ctl.xl xl.Infof("replaced by client [%s]", newCtl.runID) ctl.runID = "" ctl.conn.Close() } func (ctl *Control) RegisterWorkConn(conn net.Conn) error { xl := ctl.xl defer func() { if err := recover(); err != nil { xl.Errorf("panic error: %v", err) xl.Errorf(string(debug.Stack())) } }() select { case ctl.workConnCh <- conn: xl.Debugf("new work connection registered") return nil default: xl.Debugf("work connection pool is full, discarding") return fmt.Errorf("work connection pool is full, discarding") } } // When frps get one user connection, we get one work connection from the pool and return it. // If no workConn available in the pool, send message to frpc to get one or more // and wait until it is available. // return an error if wait timeout func (ctl *Control) GetWorkConn() (workConn net.Conn, err error) { xl := ctl.xl defer func() { if err := recover(); err != nil { xl.Errorf("panic error: %v", err) xl.Errorf(string(debug.Stack())) } }() var ok bool // get a work connection from the pool select { case workConn, ok = <-ctl.workConnCh: if !ok { err = pkgerr.ErrCtlClosed return } xl.Debugf("get work connection from pool") default: // no work connections available in the poll, send message to frpc to get more if err := ctl.msgDispatcher.Send(&msg.ReqWorkConn{}); err != nil { return nil, fmt.Errorf("control is already closed") } select { case workConn, ok = <-ctl.workConnCh: if !ok { err = pkgerr.ErrCtlClosed xl.Warnf("no work connections available, %v", err) return } case <-time.After(time.Duration(ctl.serverCfg.UserConnTimeout) * time.Second): err = fmt.Errorf("timeout trying to get work connection") xl.Warnf("%v", err) return } } // When we get a work connection from pool, replace it with a new one. _ = ctl.msgDispatcher.Send(&msg.ReqWorkConn{}) return } func (ctl *Control) heartbeatWorker() { if ctl.serverCfg.Transport.HeartbeatTimeout <= 0 { return } xl := ctl.xl go wait.Until(func() { if time.Since(ctl.lastPing.Load().(time.Time)) > time.Duration(ctl.serverCfg.Transport.HeartbeatTimeout)*time.Second { xl.Warnf("heartbeat timeout") ctl.conn.Close() return } }, time.Second, ctl.doneCh) } // block until Control closed func (ctl *Control) WaitClosed() { <-ctl.doneCh } func (ctl *Control) worker() { xl := ctl.xl go ctl.heartbeatWorker() go ctl.msgDispatcher.Run() <-ctl.msgDispatcher.Done() ctl.conn.Close() ctl.mu.Lock() defer ctl.mu.Unlock() close(ctl.workConnCh) for workConn := range ctl.workConnCh { workConn.Close() } for _, pxy := range ctl.proxies { pxy.Close() ctl.pxyManager.Del(pxy.GetName()) metrics.Server.CloseProxy(pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type) notifyContent := &plugin.CloseProxyContent{ User: plugin.UserInfo{ User: ctl.loginMsg.User, Metas: ctl.loginMsg.Metas, RunID: ctl.loginMsg.RunID, }, CloseProxy: msg.CloseProxy{ ProxyName: pxy.GetName(), }, } go func() { _ = ctl.pluginManager.CloseProxy(notifyContent) }() } metrics.Server.CloseClient() xl.Infof("client exit success") close(ctl.doneCh) } func (ctl *Control) registerMsgHandlers() { ctl.msgDispatcher.RegisterHandler(&msg.NewProxy{}, ctl.handleNewProxy) ctl.msgDispatcher.RegisterHandler(&msg.Ping{}, ctl.handlePing) ctl.msgDispatcher.RegisterHandler(&msg.NatHoleVisitor{}, msg.AsyncHandler(ctl.handleNatHoleVisitor)) ctl.msgDispatcher.RegisterHandler(&msg.NatHoleClient{}, msg.AsyncHandler(ctl.handleNatHoleClient)) ctl.msgDispatcher.RegisterHandler(&msg.NatHoleReport{}, msg.AsyncHandler(ctl.handleNatHoleReport)) ctl.msgDispatcher.RegisterHandler(&msg.CloseProxy{}, ctl.handleCloseProxy) } func (ctl *Control) handleNewProxy(m msg.Message) { xl := ctl.xl inMsg := m.(*msg.NewProxy) content := &plugin.NewProxyContent{ User: plugin.UserInfo{ User: ctl.loginMsg.User, Metas: ctl.loginMsg.Metas, RunID: ctl.loginMsg.RunID, }, NewProxy: *inMsg, } var remoteAddr string retContent, err := ctl.pluginManager.NewProxy(content) if err == nil { inMsg = &retContent.NewProxy remoteAddr, err = ctl.RegisterProxy(inMsg) } // register proxy in this control resp := &msg.NewProxyResp{ ProxyName: inMsg.ProxyName, } if err != nil { xl.Warnf("new proxy [%s] type [%s] error: %v", inMsg.ProxyName, inMsg.ProxyType, err) resp.Error = util.GenerateResponseErrorString(fmt.Sprintf("new proxy [%s] error", inMsg.ProxyName), err, lo.FromPtr(ctl.serverCfg.DetailedErrorsToClient)) } else { resp.RemoteAddr = remoteAddr xl.Infof("new proxy [%s] type [%s] success", inMsg.ProxyName, inMsg.ProxyType) metrics.Server.NewProxy(inMsg.ProxyName, inMsg.ProxyType) } _ = ctl.msgDispatcher.Send(resp) } func (ctl *Control) handlePing(m msg.Message) { xl := ctl.xl inMsg := m.(*msg.Ping) content := &plugin.PingContent{ User: plugin.UserInfo{ User: ctl.loginMsg.User, Metas: ctl.loginMsg.Metas, RunID: ctl.loginMsg.RunID, }, Ping: *inMsg, } retContent, err := ctl.pluginManager.Ping(content) if err == nil { inMsg = &retContent.Ping err = ctl.authVerifier.VerifyPing(inMsg) } if err != nil { xl.Warnf("received invalid ping: %v", err) _ = ctl.msgDispatcher.Send(&msg.Pong{ Error: util.GenerateResponseErrorString("invalid ping", err, lo.FromPtr(ctl.serverCfg.DetailedErrorsToClient)), }) return } ctl.lastPing.Store(time.Now()) xl.Debugf("receive heartbeat") _ = ctl.msgDispatcher.Send(&msg.Pong{}) } func (ctl *Control) handleNatHoleVisitor(m msg.Message) { inMsg := m.(*msg.NatHoleVisitor) ctl.rc.NatHoleController.HandleVisitor(inMsg, ctl.msgTransporter, ctl.loginMsg.User) } func (ctl *Control) handleNatHoleClient(m msg.Message) { inMsg := m.(*msg.NatHoleClient) ctl.rc.NatHoleController.HandleClient(inMsg, ctl.msgTransporter) } func (ctl *Control) handleNatHoleReport(m msg.Message) { inMsg := m.(*msg.NatHoleReport) ctl.rc.NatHoleController.HandleReport(inMsg) } func (ctl *Control) handleCloseProxy(m msg.Message) { xl := ctl.xl inMsg := m.(*msg.CloseProxy) _ = ctl.CloseProxy(inMsg) xl.Infof("close proxy [%s] success", inMsg.ProxyName) } func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (remoteAddr string, err error) { var pxyConf v1.ProxyConfigurer // Load configures from NewProxy message and validate. pxyConf, err = config.NewProxyConfigurerFromMsg(pxyMsg, ctl.serverCfg) if err != nil { return } // User info userInfo := plugin.UserInfo{ User: ctl.loginMsg.User, Metas: ctl.loginMsg.Metas, RunID: ctl.runID, } // NewProxy will return an interface Proxy. // In fact, it creates different proxies based on the proxy type. We just call run() here. pxy, err := proxy.NewProxy(ctl.ctx, &proxy.Options{ UserInfo: userInfo, LoginMsg: ctl.loginMsg, PoolCount: ctl.poolCount, ResourceController: ctl.rc, GetWorkConnFn: ctl.GetWorkConn, Configurer: pxyConf, ServerCfg: ctl.serverCfg, EncryptionKey: ctl.encryptionKey, }) if err != nil { return remoteAddr, err } // Check ports used number in each client if ctl.serverCfg.MaxPortsPerClient > 0 { ctl.mu.Lock() if ctl.portsUsedNum+pxy.GetUsedPortsNum() > int(ctl.serverCfg.MaxPortsPerClient) { ctl.mu.Unlock() err = fmt.Errorf("exceed the max_ports_per_client") return } ctl.portsUsedNum += pxy.GetUsedPortsNum() ctl.mu.Unlock() defer func() { if err != nil { ctl.mu.Lock() ctl.portsUsedNum -= pxy.GetUsedPortsNum() ctl.mu.Unlock() } }() } if ctl.pxyManager.Exist(pxyMsg.ProxyName) { err = fmt.Errorf("proxy [%s] already exists", pxyMsg.ProxyName) return } remoteAddr, err = pxy.Run() if err != nil { return } defer func() { if err != nil { pxy.Close() } }() err = ctl.pxyManager.Add(pxyMsg.ProxyName, pxy) if err != nil { return } ctl.mu.Lock() ctl.proxies[pxy.GetName()] = pxy ctl.mu.Unlock() return } func (ctl *Control) CloseProxy(closeMsg *msg.CloseProxy) (err error) { ctl.mu.Lock() pxy, ok := ctl.proxies[closeMsg.ProxyName] if !ok { ctl.mu.Unlock() return } if ctl.serverCfg.MaxPortsPerClient > 0 { ctl.portsUsedNum -= pxy.GetUsedPortsNum() } pxy.Close() ctl.pxyManager.Del(pxy.GetName()) delete(ctl.proxies, closeMsg.ProxyName) ctl.mu.Unlock() metrics.Server.CloseProxy(pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type) notifyContent := &plugin.CloseProxyContent{ User: plugin.UserInfo{ User: ctl.loginMsg.User, Metas: ctl.loginMsg.Metas, RunID: ctl.loginMsg.RunID, }, CloseProxy: msg.CloseProxy{ ProxyName: pxy.GetName(), }, } go func() { _ = ctl.pluginManager.CloseProxy(notifyContent) }() return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/controller/resource.go
server/controller/resource.go
// Copyright 2019 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 controller import ( "github.com/fatedier/frp/pkg/nathole" plugin "github.com/fatedier/frp/pkg/plugin/server" "github.com/fatedier/frp/pkg/util/tcpmux" "github.com/fatedier/frp/pkg/util/vhost" "github.com/fatedier/frp/server/group" "github.com/fatedier/frp/server/ports" "github.com/fatedier/frp/server/visitor" ) // All resource managers and controllers type ResourceController struct { // Manage all visitor listeners VisitorManager *visitor.Manager // TCP Group Controller TCPGroupCtl *group.TCPGroupCtl // HTTP Group Controller HTTPGroupCtl *group.HTTPGroupController // HTTPS Group Controller HTTPSGroupCtl *group.HTTPSGroupController // TCP Mux Group Controller TCPMuxGroupCtl *group.TCPMuxGroupCtl // Manage all TCP ports TCPPortManager *ports.Manager // Manage all UDP ports UDPPortManager *ports.Manager // For HTTP proxies, forwarding HTTP requests HTTPReverseProxy *vhost.HTTPReverseProxy // For HTTPS proxies, route requests to different clients by hostname and other information VhostHTTPSMuxer *vhost.HTTPSMuxer // Controller for nat hole connections NatHoleController *nathole.Controller // TCPMux HTTP CONNECT multiplexer TCPMuxHTTPConnectMuxer *tcpmux.HTTPConnectTCPMuxer // All server manager plugin PluginManager *plugin.Manager } func (rc *ResourceController) Close() error { if rc.VhostHTTPSMuxer != nil { rc.VhostHTTPSMuxer.Close() } if rc.TCPMuxHTTPConnectMuxer != nil { rc.TCPMuxHTTPConnectMuxer.Close() } return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/visitor/visitor.go
server/visitor/visitor.go
// Copyright 2019 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 visitor import ( "fmt" "io" "net" "slices" "sync" libio "github.com/fatedier/golib/io" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/util" ) type listenerBundle struct { l *netpkg.InternalListener sk string allowUsers []string } // Manager for visitor listeners. type Manager struct { listeners map[string]*listenerBundle mu sync.RWMutex } func NewManager() *Manager { return &Manager{ listeners: make(map[string]*listenerBundle), } } func (vm *Manager) Listen(name string, sk string, allowUsers []string) (*netpkg.InternalListener, error) { vm.mu.Lock() defer vm.mu.Unlock() if _, ok := vm.listeners[name]; ok { return nil, fmt.Errorf("custom listener for [%s] is repeated", name) } l := netpkg.NewInternalListener() vm.listeners[name] = &listenerBundle{ l: l, sk: sk, allowUsers: allowUsers, } return l, nil } func (vm *Manager) NewConn(name string, conn net.Conn, timestamp int64, signKey string, useEncryption bool, useCompression bool, visitorUser string, ) (err error) { vm.mu.RLock() defer vm.mu.RUnlock() if l, ok := vm.listeners[name]; ok { if util.GetAuthKey(l.sk, timestamp) != signKey { err = fmt.Errorf("visitor connection of [%s] auth failed", name) return } if !slices.Contains(l.allowUsers, visitorUser) && !slices.Contains(l.allowUsers, "*") { err = fmt.Errorf("visitor connection of [%s] user [%s] not allowed", name, visitorUser) return } var rwc io.ReadWriteCloser = conn if useEncryption { if rwc, err = libio.WithEncryption(rwc, []byte(l.sk)); err != nil { err = fmt.Errorf("create encryption connection failed: %v", err) return } } if useCompression { rwc = libio.WithCompression(rwc) } err = l.l.PutConn(netpkg.WrapReadWriteCloserToConn(rwc, conn)) } else { err = fmt.Errorf("custom listener for [%s] doesn't exist", name) return } return } func (vm *Manager) CloseListener(name string) { vm.mu.Lock() defer vm.mu.Unlock() delete(vm.listeners, name) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/stcp.go
server/proxy/stcp.go
// Copyright 2019 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 proxy import ( "reflect" v1 "github.com/fatedier/frp/pkg/config/v1" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.STCPProxyConfig{}), NewSTCPProxy) } type STCPProxy struct { *BaseProxy cfg *v1.STCPProxyConfig } func NewSTCPProxy(baseProxy *BaseProxy) Proxy { unwrapped, ok := baseProxy.GetConfigurer().(*v1.STCPProxyConfig) if !ok { return nil } return &STCPProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *STCPProxy) Run() (remoteAddr string, err error) { xl := pxy.xl allowUsers := pxy.cfg.AllowUsers // if allowUsers is empty, only allow same user from proxy if len(allowUsers) == 0 { allowUsers = []string{pxy.GetUserInfo().User} } listener, errRet := pxy.rc.VisitorManager.Listen(pxy.GetName(), pxy.cfg.Secretkey, allowUsers) if errRet != nil { err = errRet return } pxy.listeners = append(pxy.listeners, listener) xl.Infof("stcp proxy custom listen success") pxy.startCommonTCPListenersHandler() return } func (pxy *STCPProxy) Close() { pxy.BaseProxy.Close() pxy.rc.VisitorManager.CloseListener(pxy.GetName()) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/proxy.go
server/proxy/proxy.go
// Copyright 2017 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 proxy import ( "context" "fmt" "io" "net" "reflect" "strconv" "sync" "time" libio "github.com/fatedier/golib/io" "golang.org/x/time/rate" "github.com/fatedier/frp/pkg/config/types" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" plugin "github.com/fatedier/frp/pkg/plugin/server" "github.com/fatedier/frp/pkg/util/limit" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/server/controller" "github.com/fatedier/frp/server/metrics" ) var proxyFactoryRegistry = map[reflect.Type]func(*BaseProxy) Proxy{} func RegisterProxyFactory(proxyConfType reflect.Type, factory func(*BaseProxy) Proxy) { proxyFactoryRegistry[proxyConfType] = factory } type GetWorkConnFn func() (net.Conn, error) type Proxy interface { Context() context.Context Run() (remoteAddr string, err error) GetName() string GetConfigurer() v1.ProxyConfigurer GetWorkConnFromPool(src, dst net.Addr) (workConn net.Conn, err error) GetUsedPortsNum() int GetResourceController() *controller.ResourceController GetUserInfo() plugin.UserInfo GetLimiter() *rate.Limiter GetLoginMsg() *msg.Login Close() } type BaseProxy struct { name string rc *controller.ResourceController listeners []net.Listener usedPortsNum int poolCount int getWorkConnFn GetWorkConnFn serverCfg *v1.ServerConfig encryptionKey []byte limiter *rate.Limiter userInfo plugin.UserInfo loginMsg *msg.Login configurer v1.ProxyConfigurer mu sync.RWMutex xl *xlog.Logger ctx context.Context } func (pxy *BaseProxy) GetName() string { return pxy.name } func (pxy *BaseProxy) Context() context.Context { return pxy.ctx } func (pxy *BaseProxy) GetUsedPortsNum() int { return pxy.usedPortsNum } func (pxy *BaseProxy) GetResourceController() *controller.ResourceController { return pxy.rc } func (pxy *BaseProxy) GetUserInfo() plugin.UserInfo { return pxy.userInfo } func (pxy *BaseProxy) GetLoginMsg() *msg.Login { return pxy.loginMsg } func (pxy *BaseProxy) GetLimiter() *rate.Limiter { return pxy.limiter } func (pxy *BaseProxy) GetConfigurer() v1.ProxyConfigurer { return pxy.configurer } func (pxy *BaseProxy) Close() { xl := xlog.FromContextSafe(pxy.ctx) xl.Infof("proxy closing") for _, l := range pxy.listeners { l.Close() } } // GetWorkConnFromPool try to get a new work connections from pool // for quickly response, we immediately send the StartWorkConn message to frpc after take out one from pool func (pxy *BaseProxy) GetWorkConnFromPool(src, dst net.Addr) (workConn net.Conn, err error) { xl := xlog.FromContextSafe(pxy.ctx) // try all connections from the pool for i := 0; i < pxy.poolCount+1; i++ { if workConn, err = pxy.getWorkConnFn(); err != nil { xl.Warnf("failed to get work connection: %v", err) return } xl.Debugf("get a new work connection: [%s]", workConn.RemoteAddr().String()) xl.Spawn().AppendPrefix(pxy.GetName()) workConn = netpkg.NewContextConn(pxy.ctx, workConn) var ( srcAddr string dstAddr string srcPortStr string dstPortStr string srcPort uint64 dstPort uint64 ) if src != nil { srcAddr, srcPortStr, _ = net.SplitHostPort(src.String()) srcPort, _ = strconv.ParseUint(srcPortStr, 10, 16) } if dst != nil { dstAddr, dstPortStr, _ = net.SplitHostPort(dst.String()) dstPort, _ = strconv.ParseUint(dstPortStr, 10, 16) } err := msg.WriteMsg(workConn, &msg.StartWorkConn{ ProxyName: pxy.GetName(), SrcAddr: srcAddr, SrcPort: uint16(srcPort), DstAddr: dstAddr, DstPort: uint16(dstPort), Error: "", }) if err != nil { xl.Warnf("failed to send message to work connection from pool: %v, times: %d", err, i) workConn.Close() } else { break } } if err != nil { xl.Errorf("try to get work connection failed in the end") return } return } // startCommonTCPListenersHandler start a goroutine handler for each listener. func (pxy *BaseProxy) startCommonTCPListenersHandler() { xl := xlog.FromContextSafe(pxy.ctx) for _, listener := range pxy.listeners { go func(l net.Listener) { var tempDelay time.Duration // how long to sleep on accept failure for { // block // if listener is closed, err returned c, err := l.Accept() if err != nil { if err, ok := err.(interface{ Temporary() bool }); ok && err.Temporary() { if tempDelay == 0 { tempDelay = 5 * time.Millisecond } else { tempDelay *= 2 } if maxTime := 1 * time.Second; tempDelay > maxTime { tempDelay = maxTime } xl.Infof("met temporary error: %s, sleep for %s ...", err, tempDelay) time.Sleep(tempDelay) continue } xl.Warnf("listener is closed: %s", err) return } xl.Infof("get a user connection [%s]", c.RemoteAddr().String()) go pxy.handleUserTCPConnection(c) } }(listener) } } // HandleUserTCPConnection is used for incoming user TCP connections. func (pxy *BaseProxy) handleUserTCPConnection(userConn net.Conn) { xl := xlog.FromContextSafe(pxy.Context()) defer userConn.Close() cfg := pxy.configurer.GetBaseConfig() // server plugin hook rc := pxy.GetResourceController() content := &plugin.NewUserConnContent{ User: pxy.GetUserInfo(), ProxyName: pxy.GetName(), ProxyType: cfg.Type, RemoteAddr: userConn.RemoteAddr().String(), } _, err := rc.PluginManager.NewUserConn(content) if err != nil { xl.Warnf("the user conn [%s] was rejected, err:%v", content.RemoteAddr, err) return } // try all connections from the pool workConn, err := pxy.GetWorkConnFromPool(userConn.RemoteAddr(), userConn.LocalAddr()) if err != nil { return } defer workConn.Close() var local io.ReadWriteCloser = workConn xl.Tracef("handler user tcp connection, use_encryption: %t, use_compression: %t", cfg.Transport.UseEncryption, cfg.Transport.UseCompression) if cfg.Transport.UseEncryption { local, err = libio.WithEncryption(local, pxy.encryptionKey) if err != nil { xl.Errorf("create encryption stream error: %v", err) return } } if cfg.Transport.UseCompression { var recycleFn func() local, recycleFn = libio.WithCompressionFromPool(local) defer recycleFn() } if pxy.GetLimiter() != nil { local = libio.WrapReadWriteCloser(limit.NewReader(local, pxy.GetLimiter()), limit.NewWriter(local, pxy.GetLimiter()), func() error { return local.Close() }) } xl.Debugf("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(), workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String()) name := pxy.GetName() proxyType := cfg.Type metrics.Server.OpenConnection(name, proxyType) inCount, outCount, _ := libio.Join(local, userConn) metrics.Server.CloseConnection(name, proxyType) metrics.Server.AddTrafficIn(name, proxyType, inCount) metrics.Server.AddTrafficOut(name, proxyType, outCount) xl.Debugf("join connections closed") } type Options struct { UserInfo plugin.UserInfo LoginMsg *msg.Login PoolCount int ResourceController *controller.ResourceController GetWorkConnFn GetWorkConnFn Configurer v1.ProxyConfigurer ServerCfg *v1.ServerConfig EncryptionKey []byte } func NewProxy(ctx context.Context, options *Options) (pxy Proxy, err error) { configurer := options.Configurer xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(configurer.GetBaseConfig().Name) var limiter *rate.Limiter limitBytes := configurer.GetBaseConfig().Transport.BandwidthLimit.Bytes() if limitBytes > 0 && configurer.GetBaseConfig().Transport.BandwidthLimitMode == types.BandwidthLimitModeServer { limiter = rate.NewLimiter(rate.Limit(float64(limitBytes)), int(limitBytes)) } basePxy := BaseProxy{ name: configurer.GetBaseConfig().Name, rc: options.ResourceController, listeners: make([]net.Listener, 0), poolCount: options.PoolCount, getWorkConnFn: options.GetWorkConnFn, serverCfg: options.ServerCfg, encryptionKey: options.EncryptionKey, limiter: limiter, xl: xl, ctx: xlog.NewContext(ctx, xl), userInfo: options.UserInfo, loginMsg: options.LoginMsg, configurer: configurer, } factory := proxyFactoryRegistry[reflect.TypeOf(configurer)] if factory == nil { return pxy, fmt.Errorf("proxy type not support") } pxy = factory(&basePxy) if pxy == nil { return nil, fmt.Errorf("proxy not created") } return pxy, nil } type Manager struct { // proxies indexed by proxy name pxys map[string]Proxy mu sync.RWMutex } func NewManager() *Manager { return &Manager{ pxys: make(map[string]Proxy), } } func (pm *Manager) Add(name string, pxy Proxy) error { pm.mu.Lock() defer pm.mu.Unlock() if _, ok := pm.pxys[name]; ok { return fmt.Errorf("proxy name [%s] is already in use", name) } pm.pxys[name] = pxy return nil } func (pm *Manager) Exist(name string) bool { pm.mu.RLock() defer pm.mu.RUnlock() _, ok := pm.pxys[name] return ok } func (pm *Manager) Del(name string) { pm.mu.Lock() defer pm.mu.Unlock() delete(pm.pxys, name) } func (pm *Manager) GetByName(name string) (pxy Proxy, ok bool) { pm.mu.RLock() defer pm.mu.RUnlock() pxy, ok = pm.pxys[name] return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/tcp.go
server/proxy/tcp.go
// Copyright 2019 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 proxy import ( "fmt" "net" "reflect" "strconv" v1 "github.com/fatedier/frp/pkg/config/v1" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.TCPProxyConfig{}), NewTCPProxy) } type TCPProxy struct { *BaseProxy cfg *v1.TCPProxyConfig realBindPort int } func NewTCPProxy(baseProxy *BaseProxy) Proxy { unwrapped, ok := baseProxy.GetConfigurer().(*v1.TCPProxyConfig) if !ok { return nil } baseProxy.usedPortsNum = 1 return &TCPProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *TCPProxy) Run() (remoteAddr string, err error) { xl := pxy.xl if pxy.cfg.LoadBalancer.Group != "" { l, realBindPort, errRet := pxy.rc.TCPGroupCtl.Listen(pxy.name, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, pxy.serverCfg.ProxyBindAddr, pxy.cfg.RemotePort) if errRet != nil { err = errRet return } defer func() { if err != nil { l.Close() } }() pxy.realBindPort = realBindPort pxy.listeners = append(pxy.listeners, l) xl.Infof("tcp proxy listen port [%d] in group [%s]", pxy.cfg.RemotePort, pxy.cfg.LoadBalancer.Group) } else { pxy.realBindPort, err = pxy.rc.TCPPortManager.Acquire(pxy.name, pxy.cfg.RemotePort) if err != nil { return } defer func() { if err != nil { pxy.rc.TCPPortManager.Release(pxy.realBindPort) } }() listener, errRet := net.Listen("tcp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realBindPort))) if errRet != nil { err = errRet return } pxy.listeners = append(pxy.listeners, listener) xl.Infof("tcp proxy listen port [%d]", pxy.cfg.RemotePort) } pxy.cfg.RemotePort = pxy.realBindPort remoteAddr = fmt.Sprintf(":%d", pxy.realBindPort) pxy.startCommonTCPListenersHandler() return } func (pxy *TCPProxy) Close() { pxy.BaseProxy.Close() if pxy.cfg.LoadBalancer.Group == "" { pxy.rc.TCPPortManager.Release(pxy.realBindPort) } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/xtcp.go
server/proxy/xtcp.go
// Copyright 2019 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 proxy import ( "fmt" "reflect" "sync" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.XTCPProxyConfig{}), NewXTCPProxy) } type XTCPProxy struct { *BaseProxy cfg *v1.XTCPProxyConfig closeCh chan struct{} closeOnce sync.Once } func NewXTCPProxy(baseProxy *BaseProxy) Proxy { unwrapped, ok := baseProxy.GetConfigurer().(*v1.XTCPProxyConfig) if !ok { return nil } return &XTCPProxy{ BaseProxy: baseProxy, cfg: unwrapped, closeCh: make(chan struct{}), } } func (pxy *XTCPProxy) Run() (remoteAddr string, err error) { xl := pxy.xl if pxy.rc.NatHoleController == nil { err = fmt.Errorf("xtcp is not supported in frps") return } allowUsers := pxy.cfg.AllowUsers // if allowUsers is empty, only allow same user from proxy if len(allowUsers) == 0 { allowUsers = []string{pxy.GetUserInfo().User} } sidCh, err := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Secretkey, allowUsers) if err != nil { return "", err } go func() { for { select { case <-pxy.closeCh: return case sid := <-sidCh: workConn, errRet := pxy.GetWorkConnFromPool(nil, nil) if errRet != nil { continue } m := &msg.NatHoleSid{ Sid: sid, } errRet = msg.WriteMsg(workConn, m) if errRet != nil { xl.Warnf("write nat hole sid package error, %v", errRet) } workConn.Close() } } }() return } func (pxy *XTCPProxy) Close() { pxy.closeOnce.Do(func() { pxy.BaseProxy.Close() pxy.rc.NatHoleController.CloseClient(pxy.GetName()) close(pxy.closeCh) }) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/https.go
server/proxy/https.go
// Copyright 2019 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 proxy import ( "net" "reflect" "strings" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/vhost" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.HTTPSProxyConfig{}), NewHTTPSProxy) } type HTTPSProxy struct { *BaseProxy cfg *v1.HTTPSProxyConfig } func NewHTTPSProxy(baseProxy *BaseProxy) Proxy { unwrapped, ok := baseProxy.GetConfigurer().(*v1.HTTPSProxyConfig) if !ok { return nil } return &HTTPSProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *HTTPSProxy) Run() (remoteAddr string, err error) { xl := pxy.xl routeConfig := &vhost.RouteConfig{} defer func() { if err != nil { pxy.Close() } }() addrs := make([]string, 0) for _, domain := range pxy.cfg.CustomDomains { if domain == "" { continue } l, err := pxy.listenForDomain(routeConfig, domain) if err != nil { return "", err } pxy.listeners = append(pxy.listeners, l) addrs = append(addrs, util.CanonicalAddr(domain, pxy.serverCfg.VhostHTTPSPort)) xl.Infof("https proxy listen for host [%s] group [%s]", domain, pxy.cfg.LoadBalancer.Group) } if pxy.cfg.SubDomain != "" { domain := pxy.cfg.SubDomain + "." + pxy.serverCfg.SubDomainHost l, err := pxy.listenForDomain(routeConfig, domain) if err != nil { return "", err } pxy.listeners = append(pxy.listeners, l) addrs = append(addrs, util.CanonicalAddr(domain, pxy.serverCfg.VhostHTTPSPort)) xl.Infof("https proxy listen for host [%s] group [%s]", domain, pxy.cfg.LoadBalancer.Group) } pxy.startCommonTCPListenersHandler() remoteAddr = strings.Join(addrs, ",") return } func (pxy *HTTPSProxy) Close() { pxy.BaseProxy.Close() } func (pxy *HTTPSProxy) listenForDomain(routeConfig *vhost.RouteConfig, domain string) (net.Listener, error) { tmpRouteConfig := *routeConfig tmpRouteConfig.Domain = domain if pxy.cfg.LoadBalancer.Group != "" { return pxy.rc.HTTPSGroupCtl.Listen( pxy.ctx, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, tmpRouteConfig, ) } return pxy.rc.VhostHTTPSMuxer.Listen(pxy.ctx, &tmpRouteConfig) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/sudp.go
server/proxy/sudp.go
// Copyright 2019 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 proxy import ( "reflect" v1 "github.com/fatedier/frp/pkg/config/v1" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.SUDPProxyConfig{}), NewSUDPProxy) } type SUDPProxy struct { *BaseProxy cfg *v1.SUDPProxyConfig } func NewSUDPProxy(baseProxy *BaseProxy) Proxy { unwrapped, ok := baseProxy.GetConfigurer().(*v1.SUDPProxyConfig) if !ok { return nil } return &SUDPProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *SUDPProxy) Run() (remoteAddr string, err error) { xl := pxy.xl allowUsers := pxy.cfg.AllowUsers // if allowUsers is empty, only allow same user from proxy if len(allowUsers) == 0 { allowUsers = []string{pxy.GetUserInfo().User} } listener, errRet := pxy.rc.VisitorManager.Listen(pxy.GetName(), pxy.cfg.Secretkey, allowUsers) if errRet != nil { err = errRet return } pxy.listeners = append(pxy.listeners, listener) xl.Infof("sudp proxy custom listen success") pxy.startCommonTCPListenersHandler() return } func (pxy *SUDPProxy) Close() { pxy.BaseProxy.Close() pxy.rc.VisitorManager.CloseListener(pxy.GetName()) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/udp.go
server/proxy/udp.go
// Copyright 2019 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 proxy import ( "context" "fmt" "io" "net" "reflect" "strconv" "time" "github.com/fatedier/golib/errors" libio "github.com/fatedier/golib/io" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/proto/udp" "github.com/fatedier/frp/pkg/util/limit" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/server/metrics" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.UDPProxyConfig{}), NewUDPProxy) } type UDPProxy struct { *BaseProxy cfg *v1.UDPProxyConfig realBindPort int // udpConn is the listener of udp packages udpConn *net.UDPConn // there are always only one workConn at the same time // get another one if it closed workConn net.Conn // sendCh is used for sending packages to workConn sendCh chan *msg.UDPPacket // readCh is used for reading packages from workConn readCh chan *msg.UDPPacket // checkCloseCh is used for watching if workConn is closed checkCloseCh chan int isClosed bool } func NewUDPProxy(baseProxy *BaseProxy) Proxy { unwrapped, ok := baseProxy.GetConfigurer().(*v1.UDPProxyConfig) if !ok { return nil } baseProxy.usedPortsNum = 1 return &UDPProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *UDPProxy) Run() (remoteAddr string, err error) { xl := pxy.xl pxy.realBindPort, err = pxy.rc.UDPPortManager.Acquire(pxy.name, pxy.cfg.RemotePort) if err != nil { return "", fmt.Errorf("acquire port %d error: %v", pxy.cfg.RemotePort, err) } defer func() { if err != nil { pxy.rc.UDPPortManager.Release(pxy.realBindPort) } }() remoteAddr = fmt.Sprintf(":%d", pxy.realBindPort) pxy.cfg.RemotePort = pxy.realBindPort addr, errRet := net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realBindPort))) if errRet != nil { err = errRet return } udpConn, errRet := net.ListenUDP("udp", addr) if errRet != nil { err = errRet xl.Warnf("listen udp port error: %v", err) return } xl.Infof("udp proxy listen port [%d]", pxy.cfg.RemotePort) pxy.udpConn = udpConn pxy.sendCh = make(chan *msg.UDPPacket, 1024) pxy.readCh = make(chan *msg.UDPPacket, 1024) pxy.checkCloseCh = make(chan int) // read message from workConn, if it returns any error, notify proxy to start a new workConn workConnReaderFn := func(conn net.Conn) { for { var ( rawMsg msg.Message errRet error ) xl.Tracef("loop waiting message from udp workConn") // client will send heartbeat in workConn for keeping alive _ = conn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second)) if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil { xl.Warnf("read from workConn for udp error: %v", errRet) _ = conn.Close() // notify proxy to start a new work connection // ignore error here, it means the proxy is closed _ = errors.PanicToError(func() { pxy.checkCloseCh <- 1 }) return } if err := conn.SetReadDeadline(time.Time{}); err != nil { xl.Warnf("set read deadline error: %v", err) } switch m := rawMsg.(type) { case *msg.Ping: xl.Tracef("udp work conn get ping message") continue case *msg.UDPPacket: if errRet := errors.PanicToError(func() { xl.Tracef("get udp message from workConn: %s", m.Content) pxy.readCh <- m metrics.Server.AddTrafficOut( pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type, int64(len(m.Content)), ) }); errRet != nil { conn.Close() xl.Infof("reader goroutine for udp work connection closed") return } } } } // send message to workConn workConnSenderFn := func(conn net.Conn, ctx context.Context) { var errRet error for { select { case udpMsg, ok := <-pxy.sendCh: if !ok { xl.Infof("sender goroutine for udp work connection closed") return } if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil { xl.Infof("sender goroutine for udp work connection closed: %v", errRet) conn.Close() return } xl.Tracef("send message to udp workConn: %s", udpMsg.Content) metrics.Server.AddTrafficIn( pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type, int64(len(udpMsg.Content)), ) continue case <-ctx.Done(): xl.Infof("sender goroutine for udp work connection closed") return } } } go func() { // Sleep a while for waiting control send the NewProxyResp to client. time.Sleep(500 * time.Millisecond) for { workConn, err := pxy.GetWorkConnFromPool(nil, nil) if err != nil { time.Sleep(1 * time.Second) // check if proxy is closed select { case _, ok := <-pxy.checkCloseCh: if !ok { return } default: } continue } // close the old workConn and replace it with a new one if pxy.workConn != nil { pxy.workConn.Close() } var rwc io.ReadWriteCloser = workConn if pxy.cfg.Transport.UseEncryption { rwc, err = libio.WithEncryption(rwc, pxy.encryptionKey) if err != nil { xl.Errorf("create encryption stream error: %v", err) workConn.Close() continue } } if pxy.cfg.Transport.UseCompression { rwc = libio.WithCompression(rwc) } if pxy.GetLimiter() != nil { rwc = libio.WrapReadWriteCloser(limit.NewReader(rwc, pxy.GetLimiter()), limit.NewWriter(rwc, pxy.GetLimiter()), func() error { return rwc.Close() }) } pxy.workConn = netpkg.WrapReadWriteCloserToConn(rwc, workConn) ctx, cancel := context.WithCancel(context.Background()) go workConnReaderFn(pxy.workConn) go workConnSenderFn(pxy.workConn, ctx) _, ok := <-pxy.checkCloseCh cancel() if !ok { return } } }() // Read from user connections and send wrapped udp message to sendCh (forwarded by workConn). // Client will transfor udp message to local udp service and waiting for response for a while. // Response will be wrapped to be forwarded by work connection to server. // Close readCh and sendCh at the end. go func() { udp.ForwardUserConn(udpConn, pxy.readCh, pxy.sendCh, int(pxy.serverCfg.UDPPacketSize)) pxy.Close() }() return remoteAddr, nil } func (pxy *UDPProxy) Close() { pxy.mu.Lock() defer pxy.mu.Unlock() if !pxy.isClosed { pxy.isClosed = true pxy.BaseProxy.Close() if pxy.workConn != nil { pxy.workConn.Close() } pxy.udpConn.Close() // all channels only closed here close(pxy.checkCloseCh) close(pxy.readCh) close(pxy.sendCh) } pxy.rc.UDPPortManager.Release(pxy.realBindPort) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/http.go
server/proxy/http.go
// Copyright 2019 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 proxy import ( "io" "net" "reflect" "strings" libio "github.com/fatedier/golib/io" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/limit" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/vhost" "github.com/fatedier/frp/server/metrics" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.HTTPProxyConfig{}), NewHTTPProxy) } type HTTPProxy struct { *BaseProxy cfg *v1.HTTPProxyConfig closeFuncs []func() } func NewHTTPProxy(baseProxy *BaseProxy) Proxy { unwrapped, ok := baseProxy.GetConfigurer().(*v1.HTTPProxyConfig) if !ok { return nil } return &HTTPProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *HTTPProxy) Run() (remoteAddr string, err error) { xl := pxy.xl routeConfig := vhost.RouteConfig{ RewriteHost: pxy.cfg.HostHeaderRewrite, RouteByHTTPUser: pxy.cfg.RouteByHTTPUser, Headers: pxy.cfg.RequestHeaders.Set, ResponseHeaders: pxy.cfg.ResponseHeaders.Set, Username: pxy.cfg.HTTPUser, Password: pxy.cfg.HTTPPassword, CreateConnFn: pxy.GetRealConn, } locations := pxy.cfg.Locations if len(locations) == 0 { locations = []string{""} } defer func() { if err != nil { pxy.Close() } }() addrs := make([]string, 0) for _, domain := range pxy.cfg.CustomDomains { if domain == "" { continue } routeConfig.Domain = domain for _, location := range locations { routeConfig.Location = location tmpRouteConfig := routeConfig // handle group if pxy.cfg.LoadBalancer.Group != "" { err = pxy.rc.HTTPGroupCtl.Register(pxy.name, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, routeConfig) if err != nil { return } pxy.closeFuncs = append(pxy.closeFuncs, func() { pxy.rc.HTTPGroupCtl.UnRegister(pxy.name, pxy.cfg.LoadBalancer.Group, tmpRouteConfig) }) } else { // no group err = pxy.rc.HTTPReverseProxy.Register(routeConfig) if err != nil { return } pxy.closeFuncs = append(pxy.closeFuncs, func() { pxy.rc.HTTPReverseProxy.UnRegister(tmpRouteConfig) }) } addrs = append(addrs, util.CanonicalAddr(routeConfig.Domain, pxy.serverCfg.VhostHTTPPort)) xl.Infof("http proxy listen for host [%s] location [%s] group [%s], routeByHTTPUser [%s]", routeConfig.Domain, routeConfig.Location, pxy.cfg.LoadBalancer.Group, pxy.cfg.RouteByHTTPUser) } } if pxy.cfg.SubDomain != "" { routeConfig.Domain = pxy.cfg.SubDomain + "." + pxy.serverCfg.SubDomainHost for _, location := range locations { routeConfig.Location = location tmpRouteConfig := routeConfig // handle group if pxy.cfg.LoadBalancer.Group != "" { err = pxy.rc.HTTPGroupCtl.Register(pxy.name, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, routeConfig) if err != nil { return } pxy.closeFuncs = append(pxy.closeFuncs, func() { pxy.rc.HTTPGroupCtl.UnRegister(pxy.name, pxy.cfg.LoadBalancer.Group, tmpRouteConfig) }) } else { err = pxy.rc.HTTPReverseProxy.Register(routeConfig) if err != nil { return } pxy.closeFuncs = append(pxy.closeFuncs, func() { pxy.rc.HTTPReverseProxy.UnRegister(tmpRouteConfig) }) } addrs = append(addrs, util.CanonicalAddr(tmpRouteConfig.Domain, pxy.serverCfg.VhostHTTPPort)) xl.Infof("http proxy listen for host [%s] location [%s] group [%s], routeByHTTPUser [%s]", routeConfig.Domain, routeConfig.Location, pxy.cfg.LoadBalancer.Group, pxy.cfg.RouteByHTTPUser) } } remoteAddr = strings.Join(addrs, ",") return } func (pxy *HTTPProxy) GetRealConn(remoteAddr string) (workConn net.Conn, err error) { xl := pxy.xl rAddr, errRet := net.ResolveTCPAddr("tcp", remoteAddr) if errRet != nil { xl.Warnf("resolve TCP addr [%s] error: %v", remoteAddr, errRet) // we do not return error here since remoteAddr is not necessary for proxies without proxy protocol enabled } tmpConn, errRet := pxy.GetWorkConnFromPool(rAddr, nil) if errRet != nil { err = errRet return } var rwc io.ReadWriteCloser = tmpConn if pxy.cfg.Transport.UseEncryption { rwc, err = libio.WithEncryption(rwc, pxy.encryptionKey) if err != nil { xl.Errorf("create encryption stream error: %v", err) return } } if pxy.cfg.Transport.UseCompression { rwc = libio.WithCompression(rwc) } if pxy.GetLimiter() != nil { rwc = libio.WrapReadWriteCloser(limit.NewReader(rwc, pxy.GetLimiter()), limit.NewWriter(rwc, pxy.GetLimiter()), func() error { return rwc.Close() }) } workConn = netpkg.WrapReadWriteCloserToConn(rwc, tmpConn) workConn = netpkg.WrapStatsConn(workConn, pxy.updateStatsAfterClosedConn) metrics.Server.OpenConnection(pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type) return } func (pxy *HTTPProxy) updateStatsAfterClosedConn(totalRead, totalWrite int64) { name := pxy.GetName() proxyType := pxy.GetConfigurer().GetBaseConfig().Type metrics.Server.CloseConnection(name, proxyType) metrics.Server.AddTrafficIn(name, proxyType, totalWrite) metrics.Server.AddTrafficOut(name, proxyType, totalRead) } func (pxy *HTTPProxy) Close() { pxy.BaseProxy.Close() for _, closeFn := range pxy.closeFuncs { closeFn() } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/proxy/tcpmux.go
server/proxy/tcpmux.go
// Copyright 2020 guylewin, guy@lewin.co.il // // 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 proxy import ( "fmt" "net" "reflect" "strings" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/vhost" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.TCPMuxProxyConfig{}), NewTCPMuxProxy) } type TCPMuxProxy struct { *BaseProxy cfg *v1.TCPMuxProxyConfig } func NewTCPMuxProxy(baseProxy *BaseProxy) Proxy { unwrapped, ok := baseProxy.GetConfigurer().(*v1.TCPMuxProxyConfig) if !ok { return nil } return &TCPMuxProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *TCPMuxProxy) httpConnectListen( domain, routeByHTTPUser, httpUser, httpPwd string, addrs []string) ([]string, error, ) { var l net.Listener var err error routeConfig := &vhost.RouteConfig{ Domain: domain, RouteByHTTPUser: routeByHTTPUser, Username: httpUser, Password: httpPwd, } if pxy.cfg.LoadBalancer.Group != "" { l, err = pxy.rc.TCPMuxGroupCtl.Listen(pxy.ctx, pxy.cfg.Multiplexer, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, *routeConfig) } else { l, err = pxy.rc.TCPMuxHTTPConnectMuxer.Listen(pxy.ctx, routeConfig) } if err != nil { return nil, err } pxy.xl.Infof("tcpmux httpconnect multiplexer listens for host [%s], group [%s] routeByHTTPUser [%s]", domain, pxy.cfg.LoadBalancer.Group, pxy.cfg.RouteByHTTPUser) pxy.listeners = append(pxy.listeners, l) return append(addrs, util.CanonicalAddr(domain, pxy.serverCfg.TCPMuxHTTPConnectPort)), nil } func (pxy *TCPMuxProxy) httpConnectRun() (remoteAddr string, err error) { addrs := make([]string, 0) for _, domain := range pxy.cfg.CustomDomains { if domain == "" { continue } addrs, err = pxy.httpConnectListen(domain, pxy.cfg.RouteByHTTPUser, pxy.cfg.HTTPUser, pxy.cfg.HTTPPassword, addrs) if err != nil { return "", err } } if pxy.cfg.SubDomain != "" { addrs, err = pxy.httpConnectListen(pxy.cfg.SubDomain+"."+pxy.serverCfg.SubDomainHost, pxy.cfg.RouteByHTTPUser, pxy.cfg.HTTPUser, pxy.cfg.HTTPPassword, addrs) if err != nil { return "", err } } pxy.startCommonTCPListenersHandler() remoteAddr = strings.Join(addrs, ",") return remoteAddr, err } func (pxy *TCPMuxProxy) Run() (remoteAddr string, err error) { switch v1.TCPMultiplexerType(pxy.cfg.Multiplexer) { case v1.TCPMultiplexerHTTPConnect: remoteAddr, err = pxy.httpConnectRun() default: err = fmt.Errorf("unknown multiplexer [%s]", pxy.cfg.Multiplexer) } if err != nil { pxy.Close() } return remoteAddr, err } func (pxy *TCPMuxProxy) Close() { pxy.BaseProxy.Close() }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/metrics/metrics.go
server/metrics/metrics.go
package metrics import ( "sync" ) type ServerMetrics interface { NewClient() CloseClient() NewProxy(name string, proxyType string) CloseProxy(name string, proxyType string) OpenConnection(name string, proxyType string) CloseConnection(name string, proxyType string) AddTrafficIn(name string, proxyType string, trafficBytes int64) AddTrafficOut(name string, proxyType string, trafficBytes int64) } var Server ServerMetrics = noopServerMetrics{} var registerMetrics sync.Once func Register(m ServerMetrics) { registerMetrics.Do(func() { Server = m }) } type noopServerMetrics struct{} func (noopServerMetrics) NewClient() {} func (noopServerMetrics) CloseClient() {} func (noopServerMetrics) NewProxy(string, string) {} func (noopServerMetrics) CloseProxy(string, string) {} func (noopServerMetrics) OpenConnection(string, string) {} func (noopServerMetrics) CloseConnection(string, string) {} func (noopServerMetrics) AddTrafficIn(string, string, int64) {} func (noopServerMetrics) AddTrafficOut(string, string, int64) {}
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/group/tcp.go
server/group/tcp.go
// 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 group import ( "net" "strconv" "sync" gerr "github.com/fatedier/golib/errors" "github.com/fatedier/frp/server/ports" ) // TCPGroupCtl manage all TCPGroups type TCPGroupCtl struct { groups map[string]*TCPGroup // portManager is used to manage port portManager *ports.Manager mu sync.Mutex } // NewTCPGroupCtl return a new TcpGroupCtl func NewTCPGroupCtl(portManager *ports.Manager) *TCPGroupCtl { return &TCPGroupCtl{ groups: make(map[string]*TCPGroup), portManager: portManager, } } // Listen is the wrapper for TCPGroup's Listen // If there are no group, we will create one here func (tgc *TCPGroupCtl) Listen(proxyName string, group string, groupKey string, addr string, port int, ) (l net.Listener, realPort int, err error) { tgc.mu.Lock() tcpGroup, ok := tgc.groups[group] if !ok { tcpGroup = NewTCPGroup(tgc) tgc.groups[group] = tcpGroup } tgc.mu.Unlock() return tcpGroup.Listen(proxyName, group, groupKey, addr, port) } // RemoveGroup remove TCPGroup from controller func (tgc *TCPGroupCtl) RemoveGroup(group string) { tgc.mu.Lock() defer tgc.mu.Unlock() delete(tgc.groups, group) } // TCPGroup route connections to different proxies type TCPGroup struct { group string groupKey string addr string port int realPort int acceptCh chan net.Conn tcpLn net.Listener lns []*TCPGroupListener ctl *TCPGroupCtl mu sync.Mutex } // NewTCPGroup return a new TCPGroup func NewTCPGroup(ctl *TCPGroupCtl) *TCPGroup { return &TCPGroup{ lns: make([]*TCPGroupListener, 0), ctl: ctl, acceptCh: make(chan net.Conn), } } // Listen will return a new TCPGroupListener // if TCPGroup already has a listener, just add a new TCPGroupListener to the queues // otherwise, listen on the real address func (tg *TCPGroup) Listen(proxyName string, group string, groupKey string, addr string, port int) (ln *TCPGroupListener, realPort int, err error) { tg.mu.Lock() defer tg.mu.Unlock() if len(tg.lns) == 0 { // the first listener, listen on the real address realPort, err = tg.ctl.portManager.Acquire(proxyName, port) if err != nil { return } tcpLn, errRet := net.Listen("tcp", net.JoinHostPort(addr, strconv.Itoa(port))) if errRet != nil { err = errRet return } ln = newTCPGroupListener(group, tg, tcpLn.Addr()) tg.group = group tg.groupKey = groupKey tg.addr = addr tg.port = port tg.realPort = realPort tg.tcpLn = tcpLn tg.lns = append(tg.lns, ln) if tg.acceptCh == nil { tg.acceptCh = make(chan net.Conn) } go tg.worker() } else { // address and port in the same group must be equal if tg.group != group || tg.addr != addr { err = ErrGroupParamsInvalid return } if tg.port != port { err = ErrGroupDifferentPort return } if tg.groupKey != groupKey { err = ErrGroupAuthFailed return } ln = newTCPGroupListener(group, tg, tg.lns[0].Addr()) realPort = tg.realPort tg.lns = append(tg.lns, ln) } return } // worker is called when the real tcp listener has been created func (tg *TCPGroup) worker() { for { c, err := tg.tcpLn.Accept() if err != nil { return } err = gerr.PanicToError(func() { tg.acceptCh <- c }) if err != nil { return } } } func (tg *TCPGroup) Accept() <-chan net.Conn { return tg.acceptCh } // CloseListener remove the TCPGroupListener from the TCPGroup func (tg *TCPGroup) CloseListener(ln *TCPGroupListener) { tg.mu.Lock() defer tg.mu.Unlock() for i, tmpLn := range tg.lns { if tmpLn == ln { tg.lns = append(tg.lns[:i], tg.lns[i+1:]...) break } } if len(tg.lns) == 0 { close(tg.acceptCh) tg.tcpLn.Close() tg.ctl.portManager.Release(tg.realPort) tg.ctl.RemoveGroup(tg.group) } } // TCPGroupListener type TCPGroupListener struct { groupName string group *TCPGroup addr net.Addr closeCh chan struct{} } func newTCPGroupListener(name string, group *TCPGroup, addr net.Addr) *TCPGroupListener { return &TCPGroupListener{ groupName: name, group: group, addr: addr, closeCh: make(chan struct{}), } } // Accept will accept connections from TCPGroup func (ln *TCPGroupListener) Accept() (c net.Conn, err error) { var ok bool select { case <-ln.closeCh: return nil, ErrListenerClosed case c, ok = <-ln.group.Accept(): if !ok { return nil, ErrListenerClosed } return c, nil } } func (ln *TCPGroupListener) Addr() net.Addr { return ln.addr } // Close close the listener func (ln *TCPGroupListener) Close() (err error) { close(ln.closeCh) // remove self from TcpGroup ln.group.CloseListener(ln) return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/group/group.go
server/group/group.go
// 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 group import ( "errors" ) var ( ErrGroupAuthFailed = errors.New("group auth failed") ErrGroupParamsInvalid = errors.New("group params invalid") ErrListenerClosed = errors.New("group listener closed") ErrGroupDifferentPort = errors.New("group should have same remote port") ErrProxyRepeated = errors.New("group proxy repeated") )
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/group/https.go
server/group/https.go
// Copyright 2025 The frp 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 group import ( "context" "net" "sync" gerr "github.com/fatedier/golib/errors" "github.com/fatedier/frp/pkg/util/vhost" ) type HTTPSGroupController struct { groups map[string]*HTTPSGroup httpsMuxer *vhost.HTTPSMuxer mu sync.Mutex } func NewHTTPSGroupController(httpsMuxer *vhost.HTTPSMuxer) *HTTPSGroupController { return &HTTPSGroupController{ groups: make(map[string]*HTTPSGroup), httpsMuxer: httpsMuxer, } } func (ctl *HTTPSGroupController) Listen( ctx context.Context, group, groupKey string, routeConfig vhost.RouteConfig, ) (l net.Listener, err error) { indexKey := group ctl.mu.Lock() g, ok := ctl.groups[indexKey] if !ok { g = NewHTTPSGroup(ctl) ctl.groups[indexKey] = g } ctl.mu.Unlock() return g.Listen(ctx, group, groupKey, routeConfig) } func (ctl *HTTPSGroupController) RemoveGroup(group string) { ctl.mu.Lock() defer ctl.mu.Unlock() delete(ctl.groups, group) } type HTTPSGroup struct { group string groupKey string domain string acceptCh chan net.Conn httpsLn *vhost.Listener lns []*HTTPSGroupListener ctl *HTTPSGroupController mu sync.Mutex } func NewHTTPSGroup(ctl *HTTPSGroupController) *HTTPSGroup { return &HTTPSGroup{ lns: make([]*HTTPSGroupListener, 0), ctl: ctl, acceptCh: make(chan net.Conn), } } func (g *HTTPSGroup) Listen( ctx context.Context, group, groupKey string, routeConfig vhost.RouteConfig, ) (ln *HTTPSGroupListener, err error) { g.mu.Lock() defer g.mu.Unlock() if len(g.lns) == 0 { // the first listener, listen on the real address httpsLn, errRet := g.ctl.httpsMuxer.Listen(ctx, &routeConfig) if errRet != nil { return nil, errRet } ln = newHTTPSGroupListener(group, g, httpsLn.Addr()) g.group = group g.groupKey = groupKey g.domain = routeConfig.Domain g.httpsLn = httpsLn g.lns = append(g.lns, ln) go g.worker() } else { // route config in the same group must be equal if g.group != group || g.domain != routeConfig.Domain { return nil, ErrGroupParamsInvalid } if g.groupKey != groupKey { return nil, ErrGroupAuthFailed } ln = newHTTPSGroupListener(group, g, g.lns[0].Addr()) g.lns = append(g.lns, ln) } return } func (g *HTTPSGroup) worker() { for { c, err := g.httpsLn.Accept() if err != nil { return } err = gerr.PanicToError(func() { g.acceptCh <- c }) if err != nil { return } } } func (g *HTTPSGroup) Accept() <-chan net.Conn { return g.acceptCh } func (g *HTTPSGroup) CloseListener(ln *HTTPSGroupListener) { g.mu.Lock() defer g.mu.Unlock() for i, tmpLn := range g.lns { if tmpLn == ln { g.lns = append(g.lns[:i], g.lns[i+1:]...) break } } if len(g.lns) == 0 { close(g.acceptCh) if g.httpsLn != nil { g.httpsLn.Close() } g.ctl.RemoveGroup(g.group) } } type HTTPSGroupListener struct { groupName string group *HTTPSGroup addr net.Addr closeCh chan struct{} } func newHTTPSGroupListener(name string, group *HTTPSGroup, addr net.Addr) *HTTPSGroupListener { return &HTTPSGroupListener{ groupName: name, group: group, addr: addr, closeCh: make(chan struct{}), } } func (ln *HTTPSGroupListener) Accept() (c net.Conn, err error) { var ok bool select { case <-ln.closeCh: return nil, ErrListenerClosed case c, ok = <-ln.group.Accept(): if !ok { return nil, ErrListenerClosed } return c, nil } } func (ln *HTTPSGroupListener) Addr() net.Addr { return ln.addr } func (ln *HTTPSGroupListener) Close() (err error) { close(ln.closeCh) // remove self from HTTPSGroup ln.group.CloseListener(ln) return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/group/http.go
server/group/http.go
package group import ( "fmt" "net" "sync" "sync/atomic" "github.com/fatedier/frp/pkg/util/vhost" ) type HTTPGroupController struct { // groups indexed by group name groups map[string]*HTTPGroup // register createConn for each group to vhostRouter. // createConn will get a connection from one proxy of the group vhostRouter *vhost.Routers mu sync.Mutex } func NewHTTPGroupController(vhostRouter *vhost.Routers) *HTTPGroupController { return &HTTPGroupController{ groups: make(map[string]*HTTPGroup), vhostRouter: vhostRouter, } } func (ctl *HTTPGroupController) Register( proxyName, group, groupKey string, routeConfig vhost.RouteConfig, ) (err error) { indexKey := group ctl.mu.Lock() g, ok := ctl.groups[indexKey] if !ok { g = NewHTTPGroup(ctl) ctl.groups[indexKey] = g } ctl.mu.Unlock() return g.Register(proxyName, group, groupKey, routeConfig) } func (ctl *HTTPGroupController) UnRegister(proxyName, group string, _ vhost.RouteConfig) { indexKey := group ctl.mu.Lock() defer ctl.mu.Unlock() g, ok := ctl.groups[indexKey] if !ok { return } isEmpty := g.UnRegister(proxyName) if isEmpty { delete(ctl.groups, indexKey) } } type HTTPGroup struct { group string groupKey string domain string location string routeByHTTPUser string // CreateConnFuncs indexed by proxy name createFuncs map[string]vhost.CreateConnFunc pxyNames []string index uint64 ctl *HTTPGroupController mu sync.RWMutex } func NewHTTPGroup(ctl *HTTPGroupController) *HTTPGroup { return &HTTPGroup{ createFuncs: make(map[string]vhost.CreateConnFunc), pxyNames: make([]string, 0), ctl: ctl, } } func (g *HTTPGroup) Register( proxyName, group, groupKey string, routeConfig vhost.RouteConfig, ) (err error) { g.mu.Lock() defer g.mu.Unlock() if len(g.createFuncs) == 0 { // the first proxy in this group tmp := routeConfig // copy object tmp.CreateConnFn = g.createConn tmp.ChooseEndpointFn = g.chooseEndpoint tmp.CreateConnByEndpointFn = g.createConnByEndpoint err = g.ctl.vhostRouter.Add(routeConfig.Domain, routeConfig.Location, routeConfig.RouteByHTTPUser, &tmp) if err != nil { return } g.group = group g.groupKey = groupKey g.domain = routeConfig.Domain g.location = routeConfig.Location g.routeByHTTPUser = routeConfig.RouteByHTTPUser } else { if g.group != group || g.domain != routeConfig.Domain || g.location != routeConfig.Location || g.routeByHTTPUser != routeConfig.RouteByHTTPUser { err = ErrGroupParamsInvalid return } if g.groupKey != groupKey { err = ErrGroupAuthFailed return } } if _, ok := g.createFuncs[proxyName]; ok { err = ErrProxyRepeated return } g.createFuncs[proxyName] = routeConfig.CreateConnFn g.pxyNames = append(g.pxyNames, proxyName) return nil } func (g *HTTPGroup) UnRegister(proxyName string) (isEmpty bool) { g.mu.Lock() defer g.mu.Unlock() delete(g.createFuncs, proxyName) for i, name := range g.pxyNames { if name == proxyName { g.pxyNames = append(g.pxyNames[:i], g.pxyNames[i+1:]...) break } } if len(g.createFuncs) == 0 { isEmpty = true g.ctl.vhostRouter.Del(g.domain, g.location, g.routeByHTTPUser) } return } func (g *HTTPGroup) createConn(remoteAddr string) (net.Conn, error) { var f vhost.CreateConnFunc newIndex := atomic.AddUint64(&g.index, 1) g.mu.RLock() group := g.group domain := g.domain location := g.location routeByHTTPUser := g.routeByHTTPUser if len(g.pxyNames) > 0 { name := g.pxyNames[int(newIndex)%len(g.pxyNames)] f = g.createFuncs[name] } g.mu.RUnlock() if f == nil { return nil, fmt.Errorf("no CreateConnFunc for http group [%s], domain [%s], location [%s], routeByHTTPUser [%s]", group, domain, location, routeByHTTPUser) } return f(remoteAddr) } func (g *HTTPGroup) chooseEndpoint() (string, error) { newIndex := atomic.AddUint64(&g.index, 1) name := "" g.mu.RLock() group := g.group domain := g.domain location := g.location routeByHTTPUser := g.routeByHTTPUser if len(g.pxyNames) > 0 { name = g.pxyNames[int(newIndex)%len(g.pxyNames)] } g.mu.RUnlock() if name == "" { return "", fmt.Errorf("no healthy endpoint for http group [%s], domain [%s], location [%s], routeByHTTPUser [%s]", group, domain, location, routeByHTTPUser) } return name, nil } func (g *HTTPGroup) createConnByEndpoint(endpoint, remoteAddr string) (net.Conn, error) { var f vhost.CreateConnFunc g.mu.RLock() f = g.createFuncs[endpoint] g.mu.RUnlock() if f == nil { return nil, fmt.Errorf("no CreateConnFunc for endpoint [%s] in group [%s]", endpoint, g.group) } return f(remoteAddr) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/group/tcpmux.go
server/group/tcpmux.go
// Copyright 2020 guylewin, guy@lewin.co.il // // 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 group import ( "context" "fmt" "net" "sync" gerr "github.com/fatedier/golib/errors" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/tcpmux" "github.com/fatedier/frp/pkg/util/vhost" ) // TCPMuxGroupCtl manage all TCPMuxGroups type TCPMuxGroupCtl struct { groups map[string]*TCPMuxGroup // portManager is used to manage port tcpMuxHTTPConnectMuxer *tcpmux.HTTPConnectTCPMuxer mu sync.Mutex } // NewTCPMuxGroupCtl return a new TCPMuxGroupCtl func NewTCPMuxGroupCtl(tcpMuxHTTPConnectMuxer *tcpmux.HTTPConnectTCPMuxer) *TCPMuxGroupCtl { return &TCPMuxGroupCtl{ groups: make(map[string]*TCPMuxGroup), tcpMuxHTTPConnectMuxer: tcpMuxHTTPConnectMuxer, } } // Listen is the wrapper for TCPMuxGroup's Listen // If there are no group, we will create one here func (tmgc *TCPMuxGroupCtl) Listen( ctx context.Context, multiplexer, group, groupKey string, routeConfig vhost.RouteConfig, ) (l net.Listener, err error) { tmgc.mu.Lock() tcpMuxGroup, ok := tmgc.groups[group] if !ok { tcpMuxGroup = NewTCPMuxGroup(tmgc) tmgc.groups[group] = tcpMuxGroup } tmgc.mu.Unlock() switch v1.TCPMultiplexerType(multiplexer) { case v1.TCPMultiplexerHTTPConnect: return tcpMuxGroup.HTTPConnectListen(ctx, group, groupKey, routeConfig) default: err = fmt.Errorf("unknown multiplexer [%s]", multiplexer) return } } // RemoveGroup remove TCPMuxGroup from controller func (tmgc *TCPMuxGroupCtl) RemoveGroup(group string) { tmgc.mu.Lock() defer tmgc.mu.Unlock() delete(tmgc.groups, group) } // TCPMuxGroup route connections to different proxies type TCPMuxGroup struct { group string groupKey string domain string routeByHTTPUser string username string password string acceptCh chan net.Conn tcpMuxLn net.Listener lns []*TCPMuxGroupListener ctl *TCPMuxGroupCtl mu sync.Mutex } // NewTCPMuxGroup return a new TCPMuxGroup func NewTCPMuxGroup(ctl *TCPMuxGroupCtl) *TCPMuxGroup { return &TCPMuxGroup{ lns: make([]*TCPMuxGroupListener, 0), ctl: ctl, acceptCh: make(chan net.Conn), } } // Listen will return a new TCPMuxGroupListener // if TCPMuxGroup already has a listener, just add a new TCPMuxGroupListener to the queues // otherwise, listen on the real address func (tmg *TCPMuxGroup) HTTPConnectListen( ctx context.Context, group, groupKey string, routeConfig vhost.RouteConfig, ) (ln *TCPMuxGroupListener, err error) { tmg.mu.Lock() defer tmg.mu.Unlock() if len(tmg.lns) == 0 { // the first listener, listen on the real address tcpMuxLn, errRet := tmg.ctl.tcpMuxHTTPConnectMuxer.Listen(ctx, &routeConfig) if errRet != nil { return nil, errRet } ln = newTCPMuxGroupListener(group, tmg, tcpMuxLn.Addr()) tmg.group = group tmg.groupKey = groupKey tmg.domain = routeConfig.Domain tmg.routeByHTTPUser = routeConfig.RouteByHTTPUser tmg.username = routeConfig.Username tmg.password = routeConfig.Password tmg.tcpMuxLn = tcpMuxLn tmg.lns = append(tmg.lns, ln) if tmg.acceptCh == nil { tmg.acceptCh = make(chan net.Conn) } go tmg.worker() } else { // route config in the same group must be equal if tmg.group != group || tmg.domain != routeConfig.Domain || tmg.routeByHTTPUser != routeConfig.RouteByHTTPUser || tmg.username != routeConfig.Username || tmg.password != routeConfig.Password { return nil, ErrGroupParamsInvalid } if tmg.groupKey != groupKey { return nil, ErrGroupAuthFailed } ln = newTCPMuxGroupListener(group, tmg, tmg.lns[0].Addr()) tmg.lns = append(tmg.lns, ln) } return } // worker is called when the real TCP listener has been created func (tmg *TCPMuxGroup) worker() { for { c, err := tmg.tcpMuxLn.Accept() if err != nil { return } err = gerr.PanicToError(func() { tmg.acceptCh <- c }) if err != nil { return } } } func (tmg *TCPMuxGroup) Accept() <-chan net.Conn { return tmg.acceptCh } // CloseListener remove the TCPMuxGroupListener from the TCPMuxGroup func (tmg *TCPMuxGroup) CloseListener(ln *TCPMuxGroupListener) { tmg.mu.Lock() defer tmg.mu.Unlock() for i, tmpLn := range tmg.lns { if tmpLn == ln { tmg.lns = append(tmg.lns[:i], tmg.lns[i+1:]...) break } } if len(tmg.lns) == 0 { close(tmg.acceptCh) tmg.tcpMuxLn.Close() tmg.ctl.RemoveGroup(tmg.group) } } // TCPMuxGroupListener type TCPMuxGroupListener struct { groupName string group *TCPMuxGroup addr net.Addr closeCh chan struct{} } func newTCPMuxGroupListener(name string, group *TCPMuxGroup, addr net.Addr) *TCPMuxGroupListener { return &TCPMuxGroupListener{ groupName: name, group: group, addr: addr, closeCh: make(chan struct{}), } } // Accept will accept connections from TCPMuxGroup func (ln *TCPMuxGroupListener) Accept() (c net.Conn, err error) { var ok bool select { case <-ln.closeCh: return nil, ErrListenerClosed case c, ok = <-ln.group.Accept(): if !ok { return nil, ErrListenerClosed } return c, nil } } func (ln *TCPMuxGroupListener) Addr() net.Addr { return ln.addr } // Close close the listener func (ln *TCPMuxGroupListener) Close() (err error) { close(ln.closeCh) // remove self from TcpMuxGroup ln.group.CloseListener(ln) return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/server/ports/ports.go
server/ports/ports.go
package ports import ( "errors" "net" "strconv" "sync" "time" "github.com/fatedier/frp/pkg/config/types" ) const ( MinPort = 1 MaxPort = 65535 MaxPortReservedDuration = time.Duration(24) * time.Hour CleanReservedPortsInterval = time.Hour ) var ( ErrPortAlreadyUsed = errors.New("port already used") ErrPortNotAllowed = errors.New("port not allowed") ErrPortUnAvailable = errors.New("port unavailable") ErrNoAvailablePort = errors.New("no available port") ) type PortCtx struct { ProxyName string Port int Closed bool UpdateTime time.Time } type Manager struct { reservedPorts map[string]*PortCtx usedPorts map[int]*PortCtx freePorts map[int]struct{} bindAddr string netType string mu sync.Mutex } func NewManager(netType string, bindAddr string, allowPorts []types.PortsRange) *Manager { pm := &Manager{ reservedPorts: make(map[string]*PortCtx), usedPorts: make(map[int]*PortCtx), freePorts: make(map[int]struct{}), bindAddr: bindAddr, netType: netType, } if len(allowPorts) > 0 { for _, pair := range allowPorts { if pair.Single > 0 { pm.freePorts[pair.Single] = struct{}{} } else { for i := pair.Start; i <= pair.End; i++ { pm.freePorts[i] = struct{}{} } } } } else { for i := MinPort; i <= MaxPort; i++ { pm.freePorts[i] = struct{}{} } } go pm.cleanReservedPortsWorker() return pm } func (pm *Manager) Acquire(name string, port int) (realPort int, err error) { portCtx := &PortCtx{ ProxyName: name, Closed: false, UpdateTime: time.Now(), } var ok bool pm.mu.Lock() defer func() { if err == nil { portCtx.Port = realPort } pm.mu.Unlock() }() // check reserved ports first if port == 0 { if ctx, ok := pm.reservedPorts[name]; ok { if pm.isPortAvailable(ctx.Port) { realPort = ctx.Port pm.usedPorts[realPort] = portCtx pm.reservedPorts[name] = portCtx delete(pm.freePorts, realPort) return } } } if port == 0 { // get random port count := 0 maxTryTimes := 5 for k := range pm.freePorts { count++ if count > maxTryTimes { break } if pm.isPortAvailable(k) { realPort = k pm.usedPorts[realPort] = portCtx pm.reservedPorts[name] = portCtx delete(pm.freePorts, realPort) break } } if realPort == 0 { err = ErrNoAvailablePort } } else { // specified port if _, ok = pm.freePorts[port]; ok { if pm.isPortAvailable(port) { realPort = port pm.usedPorts[realPort] = portCtx pm.reservedPorts[name] = portCtx delete(pm.freePorts, realPort) } else { err = ErrPortUnAvailable } } else { if _, ok = pm.usedPorts[port]; ok { err = ErrPortAlreadyUsed } else { err = ErrPortNotAllowed } } } return } func (pm *Manager) isPortAvailable(port int) bool { if pm.netType == "udp" { addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(pm.bindAddr, strconv.Itoa(port))) if err != nil { return false } l, err := net.ListenUDP("udp", addr) if err != nil { return false } l.Close() return true } l, err := net.Listen(pm.netType, net.JoinHostPort(pm.bindAddr, strconv.Itoa(port))) if err != nil { return false } l.Close() return true } func (pm *Manager) Release(port int) { pm.mu.Lock() defer pm.mu.Unlock() if ctx, ok := pm.usedPorts[port]; ok { pm.freePorts[port] = struct{}{} delete(pm.usedPorts, port) ctx.Closed = true ctx.UpdateTime = time.Now() } } // Release reserved port if it isn't used in last 24 hours. func (pm *Manager) cleanReservedPortsWorker() { for { time.Sleep(CleanReservedPortsInterval) pm.mu.Lock() for name, ctx := range pm.reservedPorts { if ctx.Closed && time.Since(ctx.UpdateTime) > MaxPortReservedDuration { delete(pm.reservedPorts, name) } } pm.mu.Unlock() } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/service.go
client/service.go
// Copyright 2017 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 client import ( "context" "errors" "fmt" "net" "os" "runtime" "sync" "time" "github.com/fatedier/golib/crypto" "github.com/samber/lo" "github.com/fatedier/frp/client/proxy" "github.com/fatedier/frp/pkg/auth" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/policy/security" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/version" "github.com/fatedier/frp/pkg/util/wait" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/pkg/vnet" ) func init() { crypto.DefaultSalt = "frp" // Disable quic-go's receive buffer warning. os.Setenv("QUIC_GO_DISABLE_RECEIVE_BUFFER_WARNING", "true") // Disable quic-go's ECN support by default. It may cause issues on certain operating systems. if os.Getenv("QUIC_GO_DISABLE_ECN") == "" { os.Setenv("QUIC_GO_DISABLE_ECN", "true") } } type cancelErr struct { Err error } func (e cancelErr) Error() string { return e.Err.Error() } // ServiceOptions contains options for creating a new client service. type ServiceOptions struct { Common *v1.ClientCommonConfig ProxyCfgs []v1.ProxyConfigurer VisitorCfgs []v1.VisitorConfigurer UnsafeFeatures *security.UnsafeFeatures // ConfigFilePath is the path to the configuration file used to initialize. // If it is empty, it means that the configuration file is not used for initialization. // It may be initialized using command line parameters or called directly. ConfigFilePath string // ClientSpec is the client specification that control the client behavior. ClientSpec *msg.ClientSpec // ConnectorCreator is a function that creates a new connector to make connections to the server. // The Connector shields the underlying connection details, whether it is through TCP or QUIC connection, // and regardless of whether multiplexing is used. // // If it is not set, the default frpc connector will be used. // By using a custom Connector, it can be used to implement a VirtualClient, which connects to frps // through a pipe instead of a real physical connection. ConnectorCreator func(context.Context, *v1.ClientCommonConfig) Connector // HandleWorkConnCb is a callback function that is called when a new work connection is created. // // If it is not set, the default frpc implementation will be used. HandleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool } // setServiceOptionsDefault sets the default values for ServiceOptions. func setServiceOptionsDefault(options *ServiceOptions) error { if options.Common != nil { if err := options.Common.Complete(); err != nil { return err } } if options.ConnectorCreator == nil { options.ConnectorCreator = NewConnector } return nil } // Service is the client service that connects to frps and provides proxy services. type Service struct { ctlMu sync.RWMutex // manager control connection with server ctl *Control // Uniq id got from frps, it will be attached to loginMsg. runID string // Auth runtime and encryption materials auth *auth.ClientAuth // web server for admin UI and apis webServer *httppkg.Server vnetController *vnet.Controller cfgMu sync.RWMutex common *v1.ClientCommonConfig proxyCfgs []v1.ProxyConfigurer visitorCfgs []v1.VisitorConfigurer clientSpec *msg.ClientSpec unsafeFeatures *security.UnsafeFeatures // The configuration file used to initialize this client, or an empty // string if no configuration file was used. configFilePath string // service context ctx context.Context // call cancel to stop service cancel context.CancelCauseFunc gracefulShutdownDuration time.Duration connectorCreator func(context.Context, *v1.ClientCommonConfig) Connector handleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool } func NewService(options ServiceOptions) (*Service, error) { if err := setServiceOptionsDefault(&options); err != nil { return nil, err } var webServer *httppkg.Server if options.Common.WebServer.Port > 0 { ws, err := httppkg.NewServer(options.Common.WebServer) if err != nil { return nil, err } webServer = ws } authRuntime, err := auth.BuildClientAuth(&options.Common.Auth) if err != nil { return nil, err } s := &Service{ ctx: context.Background(), auth: authRuntime, webServer: webServer, common: options.Common, configFilePath: options.ConfigFilePath, unsafeFeatures: options.UnsafeFeatures, proxyCfgs: options.ProxyCfgs, visitorCfgs: options.VisitorCfgs, clientSpec: options.ClientSpec, connectorCreator: options.ConnectorCreator, handleWorkConnCb: options.HandleWorkConnCb, } if webServer != nil { webServer.RouteRegister(s.registerRouteHandlers) } if options.Common.VirtualNet.Address != "" { s.vnetController = vnet.NewController(options.Common.VirtualNet) } return s, nil } func (svr *Service) Run(ctx context.Context) error { ctx, cancel := context.WithCancelCause(ctx) svr.ctx = xlog.NewContext(ctx, xlog.FromContextSafe(ctx)) svr.cancel = cancel // set custom DNSServer if svr.common.DNSServer != "" { netpkg.SetDefaultDNSAddress(svr.common.DNSServer) } if svr.vnetController != nil { if err := svr.vnetController.Init(); err != nil { log.Errorf("init virtual network controller error: %v", err) return err } go func() { log.Infof("virtual network controller start...") if err := svr.vnetController.Run(); err != nil { log.Warnf("virtual network controller exit with error: %v", err) } }() } if svr.webServer != nil { go func() { log.Infof("admin server listen on %s", svr.webServer.Address()) if err := svr.webServer.Run(); err != nil { log.Warnf("admin server exit with error: %v", err) } }() } // first login to frps svr.loopLoginUntilSuccess(10*time.Second, lo.FromPtr(svr.common.LoginFailExit)) if svr.ctl == nil { cancelCause := cancelErr{} _ = errors.As(context.Cause(svr.ctx), &cancelCause) return fmt.Errorf("login to the server failed: %v. With loginFailExit enabled, no additional retries will be attempted", cancelCause.Err) } go svr.keepControllerWorking() <-svr.ctx.Done() svr.stop() return nil } func (svr *Service) keepControllerWorking() { <-svr.ctl.Done() // There is a situation where the login is successful but due to certain reasons, // the control immediately exits. It is necessary to limit the frequency of reconnection in this case. // The interval for the first three retries in 1 minute will be very short, and then it will increase exponentially. // The maximum interval is 20 seconds. wait.BackoffUntil(func() (bool, error) { // loopLoginUntilSuccess is another layer of loop that will continuously attempt to // login to the server until successful. svr.loopLoginUntilSuccess(20*time.Second, false) if svr.ctl != nil { <-svr.ctl.Done() return false, errors.New("control is closed and try another loop") } // If the control is nil, it means that the login failed and the service is also closed. return false, nil }, wait.NewFastBackoffManager( wait.FastBackoffOptions{ Duration: time.Second, Factor: 2, Jitter: 0.1, MaxDuration: 20 * time.Second, FastRetryCount: 3, FastRetryDelay: 200 * time.Millisecond, FastRetryWindow: time.Minute, FastRetryJitter: 0.5, }, ), true, svr.ctx.Done()) } // login creates a connection to frps and registers it self as a client // conn: control connection // session: if it's not nil, using tcp mux func (svr *Service) login() (conn net.Conn, connector Connector, err error) { xl := xlog.FromContextSafe(svr.ctx) connector = svr.connectorCreator(svr.ctx, svr.common) if err = connector.Open(); err != nil { return nil, nil, err } defer func() { if err != nil { connector.Close() } }() conn, err = connector.Connect() if err != nil { return } loginMsg := &msg.Login{ Arch: runtime.GOARCH, Os: runtime.GOOS, PoolCount: svr.common.Transport.PoolCount, User: svr.common.User, Version: version.Full(), Timestamp: time.Now().Unix(), RunID: svr.runID, Metas: svr.common.Metadatas, } if svr.clientSpec != nil { loginMsg.ClientSpec = *svr.clientSpec } // Add auth if err = svr.auth.Setter.SetLogin(loginMsg); err != nil { return } if err = msg.WriteMsg(conn, loginMsg); err != nil { return } var loginRespMsg msg.LoginResp _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil { return } _ = conn.SetReadDeadline(time.Time{}) if loginRespMsg.Error != "" { err = fmt.Errorf("%s", loginRespMsg.Error) xl.Errorf("%s", loginRespMsg.Error) return } svr.runID = loginRespMsg.RunID xl.AddPrefix(xlog.LogPrefix{Name: "runID", Value: svr.runID}) xl.Infof("login to server success, get run id [%s]", loginRespMsg.RunID) return } func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginExit bool) { xl := xlog.FromContextSafe(svr.ctx) loginFunc := func() (bool, error) { xl.Infof("try to connect to server...") conn, connector, err := svr.login() if err != nil { xl.Warnf("connect to server error: %v", err) if firstLoginExit { svr.cancel(cancelErr{Err: err}) } return false, err } svr.cfgMu.RLock() proxyCfgs := svr.proxyCfgs visitorCfgs := svr.visitorCfgs svr.cfgMu.RUnlock() connEncrypted := svr.clientSpec == nil || svr.clientSpec.Type != "ssh-tunnel" sessionCtx := &SessionContext{ Common: svr.common, RunID: svr.runID, Conn: conn, ConnEncrypted: connEncrypted, Auth: svr.auth, Connector: connector, VnetController: svr.vnetController, } ctl, err := NewControl(svr.ctx, sessionCtx) if err != nil { conn.Close() xl.Errorf("new control error: %v", err) return false, err } ctl.SetInWorkConnCallback(svr.handleWorkConnCb) ctl.Run(proxyCfgs, visitorCfgs) // close and replace previous control svr.ctlMu.Lock() if svr.ctl != nil { svr.ctl.Close() } svr.ctl = ctl svr.ctlMu.Unlock() return true, nil } // try to reconnect to server until success wait.BackoffUntil(loginFunc, wait.NewFastBackoffManager( wait.FastBackoffOptions{ Duration: time.Second, Factor: 2, Jitter: 0.1, MaxDuration: maxInterval, }), true, svr.ctx.Done()) } func (svr *Service) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error { svr.cfgMu.Lock() svr.proxyCfgs = proxyCfgs svr.visitorCfgs = visitorCfgs svr.cfgMu.Unlock() svr.ctlMu.RLock() ctl := svr.ctl svr.ctlMu.RUnlock() if ctl != nil { return svr.ctl.UpdateAllConfigurer(proxyCfgs, visitorCfgs) } return nil } func (svr *Service) Close() { svr.GracefulClose(time.Duration(0)) } func (svr *Service) GracefulClose(d time.Duration) { svr.gracefulShutdownDuration = d svr.cancel(nil) } func (svr *Service) stop() { svr.ctlMu.Lock() defer svr.ctlMu.Unlock() if svr.ctl != nil { svr.ctl.GracefulClose(svr.gracefulShutdownDuration) svr.ctl = nil } if svr.webServer != nil { svr.webServer.Close() svr.webServer = nil } } func (svr *Service) getProxyStatus(name string) (*proxy.WorkingStatus, bool) { svr.ctlMu.RLock() ctl := svr.ctl svr.ctlMu.RUnlock() if ctl == nil { return nil, false } return ctl.pm.GetProxyStatus(name) } func (svr *Service) StatusExporter() StatusExporter { return &statusExporterImpl{ getProxyStatusFunc: svr.getProxyStatus, } } type StatusExporter interface { GetProxyStatus(name string) (*proxy.WorkingStatus, bool) } type statusExporterImpl struct { getProxyStatusFunc func(name string) (*proxy.WorkingStatus, bool) } func (s *statusExporterImpl) GetProxyStatus(name string) (*proxy.WorkingStatus, bool) { return s.getProxyStatusFunc(name) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/admin_api.go
client/admin_api.go
// Copyright 2017 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 client import ( "cmp" "encoding/json" "fmt" "io" "net" "net/http" "os" "slices" "strconv" "time" "github.com/fatedier/frp/client/proxy" "github.com/fatedier/frp/pkg/config" "github.com/fatedier/frp/pkg/config/v1/validation" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" ) type GeneralResponse struct { Code int Msg string } func (svr *Service) registerRouteHandlers(helper *httppkg.RouterRegisterHelper) { helper.Router.HandleFunc("/healthz", svr.healthz) subRouter := helper.Router.NewRoute().Subrouter() subRouter.Use(helper.AuthMiddleware.Middleware) // api, see admin_api.go subRouter.HandleFunc("/api/reload", svr.apiReload).Methods("GET") subRouter.HandleFunc("/api/stop", svr.apiStop).Methods("POST") subRouter.HandleFunc("/api/status", svr.apiStatus).Methods("GET") subRouter.HandleFunc("/api/config", svr.apiGetConfig).Methods("GET") subRouter.HandleFunc("/api/config", svr.apiPutConfig).Methods("PUT") // view subRouter.Handle("/favicon.ico", http.FileServer(helper.AssetsFS)).Methods("GET") subRouter.PathPrefix("/static/").Handler( netpkg.MakeHTTPGzipHandler(http.StripPrefix("/static/", http.FileServer(helper.AssetsFS))), ).Methods("GET") subRouter.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/static/", http.StatusMovedPermanently) }) } // /healthz func (svr *Service) healthz(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) } // GET /api/reload func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request) { res := GeneralResponse{Code: 200} strictConfigMode := false strictStr := r.URL.Query().Get("strictConfig") if strictStr != "" { strictConfigMode, _ = strconv.ParseBool(strictStr) } log.Infof("api request [/api/reload]") defer func() { log.Infof("api response [/api/reload], code [%d]", res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() cliCfg, proxyCfgs, visitorCfgs, _, err := config.LoadClientConfig(svr.configFilePath, strictConfigMode) if err != nil { res.Code = 400 res.Msg = err.Error() log.Warnf("reload frpc proxy config error: %s", res.Msg) return } if _, err := validation.ValidateAllClientConfig(cliCfg, proxyCfgs, visitorCfgs, svr.unsafeFeatures); err != nil { res.Code = 400 res.Msg = err.Error() log.Warnf("reload frpc proxy config error: %s", res.Msg) return } if err := svr.UpdateAllConfigurer(proxyCfgs, visitorCfgs); err != nil { res.Code = 500 res.Msg = err.Error() log.Warnf("reload frpc proxy config error: %s", res.Msg) return } log.Infof("success reload conf") } // POST /api/stop func (svr *Service) apiStop(w http.ResponseWriter, _ *http.Request) { res := GeneralResponse{Code: 200} log.Infof("api request [/api/stop]") defer func() { log.Infof("api response [/api/stop], code [%d]", res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() go svr.GracefulClose(100 * time.Millisecond) } type StatusResp map[string][]ProxyStatusResp type ProxyStatusResp struct { Name string `json:"name"` Type string `json:"type"` Status string `json:"status"` Err string `json:"err"` LocalAddr string `json:"local_addr"` Plugin string `json:"plugin"` RemoteAddr string `json:"remote_addr"` } func NewProxyStatusResp(status *proxy.WorkingStatus, serverAddr string) ProxyStatusResp { psr := ProxyStatusResp{ Name: status.Name, Type: status.Type, Status: status.Phase, Err: status.Err, } baseCfg := status.Cfg.GetBaseConfig() if baseCfg.LocalPort != 0 { psr.LocalAddr = net.JoinHostPort(baseCfg.LocalIP, strconv.Itoa(baseCfg.LocalPort)) } psr.Plugin = baseCfg.Plugin.Type if status.Err == "" { psr.RemoteAddr = status.RemoteAddr if slices.Contains([]string{"tcp", "udp"}, status.Type) { psr.RemoteAddr = serverAddr + psr.RemoteAddr } } return psr } // GET /api/status func (svr *Service) apiStatus(w http.ResponseWriter, _ *http.Request) { var ( buf []byte res StatusResp = make(map[string][]ProxyStatusResp) ) log.Infof("http request [/api/status]") defer func() { log.Infof("http response [/api/status]") buf, _ = json.Marshal(&res) _, _ = w.Write(buf) }() svr.ctlMu.RLock() ctl := svr.ctl svr.ctlMu.RUnlock() if ctl == nil { return } ps := ctl.pm.GetAllProxyStatus() for _, status := range ps { res[status.Type] = append(res[status.Type], NewProxyStatusResp(status, svr.common.ServerAddr)) } for _, arrs := range res { if len(arrs) <= 1 { continue } slices.SortFunc(arrs, func(a, b ProxyStatusResp) int { return cmp.Compare(a.Name, b.Name) }) } } // GET /api/config func (svr *Service) apiGetConfig(w http.ResponseWriter, _ *http.Request) { res := GeneralResponse{Code: 200} log.Infof("http get request [/api/config]") defer func() { log.Infof("http get response [/api/config], code [%d]", res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() if svr.configFilePath == "" { res.Code = 400 res.Msg = "frpc has no config file path" log.Warnf("%s", res.Msg) return } content, err := os.ReadFile(svr.configFilePath) if err != nil { res.Code = 400 res.Msg = err.Error() log.Warnf("load frpc config file error: %s", res.Msg) return } res.Msg = string(content) } // PUT /api/config func (svr *Service) apiPutConfig(w http.ResponseWriter, r *http.Request) { res := GeneralResponse{Code: 200} log.Infof("http put request [/api/config]") defer func() { log.Infof("http put response [/api/config], code [%d]", res.Code) w.WriteHeader(res.Code) if len(res.Msg) > 0 { _, _ = w.Write([]byte(res.Msg)) } }() // get new config content body, err := io.ReadAll(r.Body) if err != nil { res.Code = 400 res.Msg = fmt.Sprintf("read request body error: %v", err) log.Warnf("%s", res.Msg) return } if len(body) == 0 { res.Code = 400 res.Msg = "body can't be empty" log.Warnf("%s", res.Msg) return } if err := os.WriteFile(svr.configFilePath, body, 0o600); err != nil { res.Code = 500 res.Msg = fmt.Sprintf("write content to frpc config file error: %v", err) log.Warnf("%s", res.Msg) return } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/control.go
client/control.go
// Copyright 2017 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 client import ( "context" "net" "sync/atomic" "time" "github.com/fatedier/frp/client/proxy" "github.com/fatedier/frp/client/visitor" "github.com/fatedier/frp/pkg/auth" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/transport" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/wait" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/pkg/vnet" ) type SessionContext struct { // The client common configuration. Common *v1.ClientCommonConfig // Unique ID obtained from frps. // It should be attached to the login message when reconnecting. RunID string // Underlying control connection. Once conn is closed, the msgDispatcher and the entire Control will exit. Conn net.Conn // Indicates whether the connection is encrypted. ConnEncrypted bool // Auth runtime used for login, heartbeats, and encryption. Auth *auth.ClientAuth // Connector is used to create new connections, which could be real TCP connections or virtual streams. Connector Connector // Virtual net controller VnetController *vnet.Controller } type Control struct { // service context ctx context.Context xl *xlog.Logger // session context sessionCtx *SessionContext // manage all proxies pm *proxy.Manager // manage all visitors vm *visitor.Manager doneCh chan struct{} // of time.Time, last time got the Pong message lastPong atomic.Value // The role of msgTransporter is similar to HTTP2. // It allows multiple messages to be sent simultaneously on the same control connection. // The server's response messages will be dispatched to the corresponding waiting goroutines based on the laneKey and message type. msgTransporter transport.MessageTransporter // msgDispatcher is a wrapper for control connection. // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types. msgDispatcher *msg.Dispatcher } func NewControl(ctx context.Context, sessionCtx *SessionContext) (*Control, error) { // new xlog instance ctl := &Control{ ctx: ctx, xl: xlog.FromContextSafe(ctx), sessionCtx: sessionCtx, doneCh: make(chan struct{}), } ctl.lastPong.Store(time.Now()) if sessionCtx.ConnEncrypted { cryptoRW, err := netpkg.NewCryptoReadWriter(sessionCtx.Conn, sessionCtx.Auth.EncryptionKey()) if err != nil { return nil, err } ctl.msgDispatcher = msg.NewDispatcher(cryptoRW) } else { ctl.msgDispatcher = msg.NewDispatcher(sessionCtx.Conn) } ctl.registerMsgHandlers() ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher) ctl.pm = proxy.NewManager(ctl.ctx, sessionCtx.Common, sessionCtx.Auth.EncryptionKey(), ctl.msgTransporter, sessionCtx.VnetController) ctl.vm = visitor.NewManager(ctl.ctx, sessionCtx.RunID, sessionCtx.Common, ctl.connectServer, ctl.msgTransporter, sessionCtx.VnetController) return ctl, nil } func (ctl *Control) Run(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) { go ctl.worker() // start all proxies ctl.pm.UpdateAll(proxyCfgs) // start all visitors ctl.vm.UpdateAll(visitorCfgs) } func (ctl *Control) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) { ctl.pm.SetInWorkConnCallback(cb) } func (ctl *Control) handleReqWorkConn(_ msg.Message) { xl := ctl.xl workConn, err := ctl.connectServer() if err != nil { xl.Warnf("start new connection to server error: %v", err) return } m := &msg.NewWorkConn{ RunID: ctl.sessionCtx.RunID, } if err = ctl.sessionCtx.Auth.Setter.SetNewWorkConn(m); err != nil { xl.Warnf("error during NewWorkConn authentication: %v", err) workConn.Close() return } if err = msg.WriteMsg(workConn, m); err != nil { xl.Warnf("work connection write to server error: %v", err) workConn.Close() return } var startMsg msg.StartWorkConn if err = msg.ReadMsgInto(workConn, &startMsg); err != nil { xl.Tracef("work connection closed before response StartWorkConn message: %v", err) workConn.Close() return } if startMsg.Error != "" { xl.Errorf("StartWorkConn contains error: %s", startMsg.Error) workConn.Close() return } // dispatch this work connection to related proxy ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg) } func (ctl *Control) handleNewProxyResp(m msg.Message) { xl := ctl.xl inMsg := m.(*msg.NewProxyResp) // Server will return NewProxyResp message to each NewProxy message. // Start a new proxy handler if no error got err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error) if err != nil { xl.Warnf("[%s] start error: %v", inMsg.ProxyName, err) } else { xl.Infof("[%s] start proxy success", inMsg.ProxyName) } } func (ctl *Control) handleNatHoleResp(m msg.Message) { xl := ctl.xl inMsg := m.(*msg.NatHoleResp) // Dispatch the NatHoleResp message to the related proxy. ok := ctl.msgTransporter.DispatchWithType(inMsg, msg.TypeNameNatHoleResp, inMsg.TransactionID) if !ok { xl.Tracef("dispatch NatHoleResp message to related proxy error") } } func (ctl *Control) handlePong(m msg.Message) { xl := ctl.xl inMsg := m.(*msg.Pong) if inMsg.Error != "" { xl.Errorf("pong message contains error: %s", inMsg.Error) ctl.closeSession() return } ctl.lastPong.Store(time.Now()) xl.Debugf("receive heartbeat from server") } // closeSession closes the control connection. func (ctl *Control) closeSession() { ctl.sessionCtx.Conn.Close() ctl.sessionCtx.Connector.Close() } func (ctl *Control) Close() error { return ctl.GracefulClose(0) } func (ctl *Control) GracefulClose(d time.Duration) error { ctl.pm.Close() ctl.vm.Close() time.Sleep(d) ctl.closeSession() return nil } // Done returns a channel that will be closed after all resources are released func (ctl *Control) Done() <-chan struct{} { return ctl.doneCh } // connectServer return a new connection to frps func (ctl *Control) connectServer() (net.Conn, error) { return ctl.sessionCtx.Connector.Connect() } func (ctl *Control) registerMsgHandlers() { ctl.msgDispatcher.RegisterHandler(&msg.ReqWorkConn{}, msg.AsyncHandler(ctl.handleReqWorkConn)) ctl.msgDispatcher.RegisterHandler(&msg.NewProxyResp{}, ctl.handleNewProxyResp) ctl.msgDispatcher.RegisterHandler(&msg.NatHoleResp{}, ctl.handleNatHoleResp) ctl.msgDispatcher.RegisterHandler(&msg.Pong{}, ctl.handlePong) } // heartbeatWorker sends heartbeat to server and check heartbeat timeout. func (ctl *Control) heartbeatWorker() { xl := ctl.xl if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 { // Send heartbeat to server. sendHeartBeat := func() (bool, error) { xl.Debugf("send heartbeat to server") pingMsg := &msg.Ping{} if err := ctl.sessionCtx.Auth.Setter.SetPing(pingMsg); err != nil { xl.Warnf("error during ping authentication: %v, skip sending ping message", err) return false, err } _ = ctl.msgDispatcher.Send(pingMsg) return false, nil } go wait.BackoffUntil(sendHeartBeat, wait.NewFastBackoffManager(wait.FastBackoffOptions{ Duration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second, InitDurationIfFail: time.Second, Factor: 2.0, Jitter: 0.1, MaxDuration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second, }), true, ctl.doneCh, ) } // Check heartbeat timeout. if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 && ctl.sessionCtx.Common.Transport.HeartbeatTimeout > 0 { go wait.Until(func() { if time.Since(ctl.lastPong.Load().(time.Time)) > time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatTimeout)*time.Second { xl.Warnf("heartbeat timeout") ctl.closeSession() return } }, time.Second, ctl.doneCh) } } func (ctl *Control) worker() { xl := ctl.xl go ctl.heartbeatWorker() go ctl.msgDispatcher.Run() <-ctl.msgDispatcher.Done() xl.Debugf("control message dispatcher exited") ctl.closeSession() ctl.pm.Close() ctl.vm.Close() close(ctl.doneCh) } func (ctl *Control) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error { ctl.vm.UpdateAll(visitorCfgs) ctl.pm.UpdateAll(proxyCfgs) return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/connector.go
client/connector.go
// Copyright 2023 The frp 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 client import ( "context" "crypto/tls" "net" "strconv" "strings" "sync" "time" libnet "github.com/fatedier/golib/net" fmux "github.com/hashicorp/yamux" quic "github.com/quic-go/quic-go" "github.com/samber/lo" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/transport" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/xlog" ) // Connector is an interface for establishing connections to the server. type Connector interface { Open() error Connect() (net.Conn, error) Close() error } // defaultConnectorImpl is the default implementation of Connector for normal frpc. type defaultConnectorImpl struct { ctx context.Context cfg *v1.ClientCommonConfig muxSession *fmux.Session quicConn *quic.Conn closeOnce sync.Once } func NewConnector(ctx context.Context, cfg *v1.ClientCommonConfig) Connector { return &defaultConnectorImpl{ ctx: ctx, cfg: cfg, } } // Open opens an underlying connection to the server. // The underlying connection is either a TCP connection or a QUIC connection. // After the underlying connection is established, you can call Connect() to get a stream. // If TCPMux isn't enabled, the underlying connection is nil, you will get a new real TCP connection every time you call Connect(). func (c *defaultConnectorImpl) Open() error { xl := xlog.FromContextSafe(c.ctx) // special for quic if strings.EqualFold(c.cfg.Transport.Protocol, "quic") { var tlsConfig *tls.Config var err error sn := c.cfg.Transport.TLS.ServerName if sn == "" { sn = c.cfg.ServerAddr } if lo.FromPtr(c.cfg.Transport.TLS.Enable) { tlsConfig, err = transport.NewClientTLSConfig( c.cfg.Transport.TLS.CertFile, c.cfg.Transport.TLS.KeyFile, c.cfg.Transport.TLS.TrustedCaFile, sn) } else { tlsConfig, err = transport.NewClientTLSConfig("", "", "", sn) } if err != nil { xl.Warnf("fail to build tls configuration, err: %v", err) return err } tlsConfig.NextProtos = []string{"frp"} conn, err := quic.DialAddr( c.ctx, net.JoinHostPort(c.cfg.ServerAddr, strconv.Itoa(c.cfg.ServerPort)), tlsConfig, &quic.Config{ MaxIdleTimeout: time.Duration(c.cfg.Transport.QUIC.MaxIdleTimeout) * time.Second, MaxIncomingStreams: int64(c.cfg.Transport.QUIC.MaxIncomingStreams), KeepAlivePeriod: time.Duration(c.cfg.Transport.QUIC.KeepalivePeriod) * time.Second, }) if err != nil { return err } c.quicConn = conn return nil } if !lo.FromPtr(c.cfg.Transport.TCPMux) { return nil } conn, err := c.realConnect() if err != nil { return err } fmuxCfg := fmux.DefaultConfig() fmuxCfg.KeepAliveInterval = time.Duration(c.cfg.Transport.TCPMuxKeepaliveInterval) * time.Second // Use trace level for yamux logs fmuxCfg.LogOutput = xlog.NewTraceWriter(xl) fmuxCfg.MaxStreamWindowSize = 6 * 1024 * 1024 session, err := fmux.Client(conn, fmuxCfg) if err != nil { return err } c.muxSession = session return nil } // Connect returns a stream from the underlying connection, or a new TCP connection if TCPMux isn't enabled. func (c *defaultConnectorImpl) Connect() (net.Conn, error) { if c.quicConn != nil { stream, err := c.quicConn.OpenStreamSync(context.Background()) if err != nil { return nil, err } return netpkg.QuicStreamToNetConn(stream, c.quicConn), nil } else if c.muxSession != nil { stream, err := c.muxSession.OpenStream() if err != nil { return nil, err } return stream, nil } return c.realConnect() } func (c *defaultConnectorImpl) realConnect() (net.Conn, error) { xl := xlog.FromContextSafe(c.ctx) var tlsConfig *tls.Config var err error tlsEnable := lo.FromPtr(c.cfg.Transport.TLS.Enable) if c.cfg.Transport.Protocol == "wss" { tlsEnable = true } if tlsEnable { sn := c.cfg.Transport.TLS.ServerName if sn == "" { sn = c.cfg.ServerAddr } tlsConfig, err = transport.NewClientTLSConfig( c.cfg.Transport.TLS.CertFile, c.cfg.Transport.TLS.KeyFile, c.cfg.Transport.TLS.TrustedCaFile, sn) if err != nil { xl.Warnf("fail to build tls configuration, err: %v", err) return nil, err } } proxyType, addr, auth, err := libnet.ParseProxyURL(c.cfg.Transport.ProxyURL) if err != nil { xl.Errorf("fail to parse proxy url") return nil, err } dialOptions := []libnet.DialOption{} protocol := c.cfg.Transport.Protocol switch protocol { case "websocket": protocol = "tcp" dialOptions = append(dialOptions, libnet.WithAfterHook(libnet.AfterHook{Hook: netpkg.DialHookWebsocket(protocol, "")})) dialOptions = append(dialOptions, libnet.WithAfterHook(libnet.AfterHook{ Hook: netpkg.DialHookCustomTLSHeadByte(tlsConfig != nil, lo.FromPtr(c.cfg.Transport.TLS.DisableCustomTLSFirstByte)), })) dialOptions = append(dialOptions, libnet.WithTLSConfig(tlsConfig)) case "wss": protocol = "tcp" dialOptions = append(dialOptions, libnet.WithTLSConfigAndPriority(100, tlsConfig)) // Make sure that if it is wss, the websocket hook is executed after the tls hook. dialOptions = append(dialOptions, libnet.WithAfterHook(libnet.AfterHook{Hook: netpkg.DialHookWebsocket(protocol, tlsConfig.ServerName), Priority: 110})) default: dialOptions = append(dialOptions, libnet.WithAfterHook(libnet.AfterHook{ Hook: netpkg.DialHookCustomTLSHeadByte(tlsConfig != nil, lo.FromPtr(c.cfg.Transport.TLS.DisableCustomTLSFirstByte)), })) dialOptions = append(dialOptions, libnet.WithTLSConfig(tlsConfig)) } if c.cfg.Transport.ConnectServerLocalIP != "" { dialOptions = append(dialOptions, libnet.WithLocalAddr(c.cfg.Transport.ConnectServerLocalIP)) } dialOptions = append(dialOptions, libnet.WithProtocol(protocol), libnet.WithTimeout(time.Duration(c.cfg.Transport.DialServerTimeout)*time.Second), libnet.WithKeepAlive(time.Duration(c.cfg.Transport.DialServerKeepAlive)*time.Second), libnet.WithProxy(proxyType, addr), libnet.WithProxyAuth(auth), ) conn, err := libnet.DialContext( c.ctx, net.JoinHostPort(c.cfg.ServerAddr, strconv.Itoa(c.cfg.ServerPort)), dialOptions..., ) return conn, err } func (c *defaultConnectorImpl) Close() error { c.closeOnce.Do(func() { if c.quicConn != nil { _ = c.quicConn.CloseWithError(0, "") } if c.muxSession != nil { _ = c.muxSession.Close() } }) return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/visitor/stcp.go
client/visitor/stcp.go
// Copyright 2017 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 visitor import ( "fmt" "io" "net" "strconv" "time" libio "github.com/fatedier/golib/io" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/xlog" ) type STCPVisitor struct { *BaseVisitor cfg *v1.STCPVisitorConfig } func (sv *STCPVisitor) Run() (err error) { if sv.cfg.BindPort > 0 { sv.l, err = net.Listen("tcp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort))) if err != nil { return } go sv.worker() } go sv.internalConnWorker() if sv.plugin != nil { sv.plugin.Start() } return } func (sv *STCPVisitor) Close() { sv.BaseVisitor.Close() } func (sv *STCPVisitor) worker() { xl := xlog.FromContextSafe(sv.ctx) for { conn, err := sv.l.Accept() if err != nil { xl.Warnf("stcp local listener closed") return } go sv.handleConn(conn) } } func (sv *STCPVisitor) internalConnWorker() { xl := xlog.FromContextSafe(sv.ctx) for { conn, err := sv.internalLn.Accept() if err != nil { xl.Warnf("stcp internal listener closed") return } go sv.handleConn(conn) } } func (sv *STCPVisitor) handleConn(userConn net.Conn) { xl := xlog.FromContextSafe(sv.ctx) var tunnelErr error defer func() { // If there was an error and connection supports CloseWithError, use it if tunnelErr != nil { if eConn, ok := userConn.(interface{ CloseWithError(error) error }); ok { _ = eConn.CloseWithError(tunnelErr) return } } userConn.Close() }() xl.Debugf("get a new stcp user connection") visitorConn, err := sv.helper.ConnectServer() if err != nil { tunnelErr = err return } defer visitorConn.Close() now := time.Now().Unix() newVisitorConnMsg := &msg.NewVisitorConn{ RunID: sv.helper.RunID(), ProxyName: sv.cfg.ServerName, SignKey: util.GetAuthKey(sv.cfg.SecretKey, now), Timestamp: now, UseEncryption: sv.cfg.Transport.UseEncryption, UseCompression: sv.cfg.Transport.UseCompression, } err = msg.WriteMsg(visitorConn, newVisitorConnMsg) if err != nil { xl.Warnf("send newVisitorConnMsg to server error: %v", err) tunnelErr = err return } var newVisitorConnRespMsg msg.NewVisitorConnResp _ = visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second)) err = msg.ReadMsgInto(visitorConn, &newVisitorConnRespMsg) if err != nil { xl.Warnf("get newVisitorConnRespMsg error: %v", err) tunnelErr = err return } _ = visitorConn.SetReadDeadline(time.Time{}) if newVisitorConnRespMsg.Error != "" { xl.Warnf("start new visitor connection error: %s", newVisitorConnRespMsg.Error) tunnelErr = fmt.Errorf("%s", newVisitorConnRespMsg.Error) return } var remote io.ReadWriteCloser remote = visitorConn if sv.cfg.Transport.UseEncryption { remote, err = libio.WithEncryption(remote, []byte(sv.cfg.SecretKey)) if err != nil { xl.Errorf("create encryption stream error: %v", err) tunnelErr = err return } } if sv.cfg.Transport.UseCompression { var recycleFn func() remote, recycleFn = libio.WithCompressionFromPool(remote) defer recycleFn() } libio.Join(userConn, remote) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/visitor/xtcp.go
client/visitor/xtcp.go
// Copyright 2017 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 visitor import ( "context" "errors" "fmt" "io" "net" "strconv" "sync" "time" libio "github.com/fatedier/golib/io" fmux "github.com/hashicorp/yamux" quic "github.com/quic-go/quic-go" "golang.org/x/time/rate" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/nathole" "github.com/fatedier/frp/pkg/transport" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/xlog" ) var ErrNoTunnelSession = errors.New("no tunnel session") type XTCPVisitor struct { *BaseVisitor session TunnelSession startTunnelCh chan struct{} retryLimiter *rate.Limiter cancel context.CancelFunc cfg *v1.XTCPVisitorConfig } func (sv *XTCPVisitor) Run() (err error) { sv.ctx, sv.cancel = context.WithCancel(sv.ctx) if sv.cfg.Protocol == "kcp" { sv.session = NewKCPTunnelSession() } else { sv.session = NewQUICTunnelSession(sv.clientCfg) } if sv.cfg.BindPort > 0 { sv.l, err = net.Listen("tcp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort))) if err != nil { return } go sv.worker() } go sv.internalConnWorker() go sv.processTunnelStartEvents() if sv.cfg.KeepTunnelOpen { sv.retryLimiter = rate.NewLimiter(rate.Every(time.Hour/time.Duration(sv.cfg.MaxRetriesAnHour)), sv.cfg.MaxRetriesAnHour) go sv.keepTunnelOpenWorker() } if sv.plugin != nil { sv.plugin.Start() } return } func (sv *XTCPVisitor) Close() { sv.mu.Lock() defer sv.mu.Unlock() sv.BaseVisitor.Close() if sv.cancel != nil { sv.cancel() } if sv.session != nil { sv.session.Close() } } func (sv *XTCPVisitor) worker() { xl := xlog.FromContextSafe(sv.ctx) for { conn, err := sv.l.Accept() if err != nil { xl.Warnf("xtcp local listener closed") return } go sv.handleConn(conn) } } func (sv *XTCPVisitor) internalConnWorker() { xl := xlog.FromContextSafe(sv.ctx) for { conn, err := sv.internalLn.Accept() if err != nil { xl.Warnf("xtcp internal listener closed") return } go sv.handleConn(conn) } } func (sv *XTCPVisitor) processTunnelStartEvents() { for { select { case <-sv.ctx.Done(): return case <-sv.startTunnelCh: start := time.Now() sv.makeNatHole() duration := time.Since(start) // avoid too frequently if duration < 10*time.Second { time.Sleep(10*time.Second - duration) } } } } func (sv *XTCPVisitor) keepTunnelOpenWorker() { xl := xlog.FromContextSafe(sv.ctx) ticker := time.NewTicker(time.Duration(sv.cfg.MinRetryInterval) * time.Second) defer ticker.Stop() sv.startTunnelCh <- struct{}{} for { select { case <-sv.ctx.Done(): return case <-ticker.C: xl.Debugf("keepTunnelOpenWorker try to check tunnel...") conn, err := sv.getTunnelConn(sv.ctx) if err != nil { xl.Warnf("keepTunnelOpenWorker get tunnel connection error: %v", err) _ = sv.retryLimiter.Wait(sv.ctx) continue } xl.Debugf("keepTunnelOpenWorker check success") if conn != nil { conn.Close() } } } } func (sv *XTCPVisitor) handleConn(userConn net.Conn) { xl := xlog.FromContextSafe(sv.ctx) isConnTransferred := false var tunnelErr error defer func() { if !isConnTransferred { // If there was an error and connection supports CloseWithError, use it if tunnelErr != nil { if eConn, ok := userConn.(interface{ CloseWithError(error) error }); ok { _ = eConn.CloseWithError(tunnelErr) return } } userConn.Close() } }() xl.Debugf("get a new xtcp user connection") // Open a tunnel connection to the server. If there is already a successful hole-punching connection, // it will be reused. Otherwise, it will block and wait for a successful hole-punching connection until timeout. ctx := sv.ctx if sv.cfg.FallbackTo != "" { timeoutCtx, cancel := context.WithTimeout(ctx, time.Duration(sv.cfg.FallbackTimeoutMs)*time.Millisecond) defer cancel() ctx = timeoutCtx } tunnelConn, err := sv.openTunnel(ctx) if err != nil { xl.Errorf("open tunnel error: %v", err) tunnelErr = err // no fallback, just return if sv.cfg.FallbackTo == "" { return } xl.Debugf("try to transfer connection to visitor: %s", sv.cfg.FallbackTo) if err := sv.helper.TransferConn(sv.cfg.FallbackTo, userConn); err != nil { xl.Errorf("transfer connection to visitor %s error: %v", sv.cfg.FallbackTo, err) return } isConnTransferred = true return } var muxConnRWCloser io.ReadWriteCloser = tunnelConn if sv.cfg.Transport.UseEncryption { muxConnRWCloser, err = libio.WithEncryption(muxConnRWCloser, []byte(sv.cfg.SecretKey)) if err != nil { xl.Errorf("create encryption stream error: %v", err) tunnelErr = err return } } if sv.cfg.Transport.UseCompression { var recycleFn func() muxConnRWCloser, recycleFn = libio.WithCompressionFromPool(muxConnRWCloser) defer recycleFn() } _, _, errs := libio.Join(userConn, muxConnRWCloser) xl.Debugf("join connections closed") if len(errs) > 0 { xl.Tracef("join connections errors: %v", errs) } } // openTunnel will open a tunnel connection to the target server. func (sv *XTCPVisitor) openTunnel(ctx context.Context) (conn net.Conn, err error) { xl := xlog.FromContextSafe(sv.ctx) ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() timer := time.NewTimer(0) defer timer.Stop() for { select { case <-sv.ctx.Done(): return nil, sv.ctx.Err() case <-ctx.Done(): if errors.Is(ctx.Err(), context.DeadlineExceeded) { return nil, fmt.Errorf("open tunnel timeout") } return nil, ctx.Err() case <-timer.C: conn, err = sv.getTunnelConn(ctx) if err != nil { if !errors.Is(err, ErrNoTunnelSession) { xl.Warnf("get tunnel connection error: %v", err) } timer.Reset(500 * time.Millisecond) continue } return conn, nil } } } func (sv *XTCPVisitor) getTunnelConn(ctx context.Context) (net.Conn, error) { conn, err := sv.session.OpenConn(ctx) if err == nil { return conn, nil } sv.session.Close() select { case sv.startTunnelCh <- struct{}{}: default: } return nil, err } // 0. PreCheck // 1. Prepare // 2. ExchangeInfo // 3. MakeNATHole // 4. Create a tunnel session using an underlying UDP connection. func (sv *XTCPVisitor) makeNatHole() { xl := xlog.FromContextSafe(sv.ctx) xl.Tracef("makeNatHole start") if err := nathole.PreCheck(sv.ctx, sv.helper.MsgTransporter(), sv.cfg.ServerName, 5*time.Second); err != nil { xl.Warnf("nathole precheck error: %v", err) return } xl.Tracef("nathole prepare start") // Prepare NAT traversal options var opts nathole.PrepareOptions if sv.cfg.NatTraversal != nil && sv.cfg.NatTraversal.DisableAssistedAddrs { opts.DisableAssistedAddrs = true } prepareResult, err := nathole.Prepare([]string{sv.clientCfg.NatHoleSTUNServer}, opts) if err != nil { xl.Warnf("nathole prepare error: %v", err) return } xl.Infof("nathole prepare success, nat type: %s, behavior: %s, addresses: %v, assistedAddresses: %v", prepareResult.NatType, prepareResult.Behavior, prepareResult.Addrs, prepareResult.AssistedAddrs) listenConn := prepareResult.ListenConn // send NatHoleVisitor to server now := time.Now().Unix() transactionID := nathole.NewTransactionID() natHoleVisitorMsg := &msg.NatHoleVisitor{ TransactionID: transactionID, ProxyName: sv.cfg.ServerName, Protocol: sv.cfg.Protocol, SignKey: util.GetAuthKey(sv.cfg.SecretKey, now), Timestamp: now, MappedAddrs: prepareResult.Addrs, AssistedAddrs: prepareResult.AssistedAddrs, } xl.Tracef("nathole exchange info start") natHoleRespMsg, err := nathole.ExchangeInfo(sv.ctx, sv.helper.MsgTransporter(), transactionID, natHoleVisitorMsg, 5*time.Second) if err != nil { listenConn.Close() xl.Warnf("nathole exchange info error: %v", err) return } xl.Infof("get natHoleRespMsg, sid [%s], protocol [%s], candidate address %v, assisted address %v, detectBehavior: %+v", natHoleRespMsg.Sid, natHoleRespMsg.Protocol, natHoleRespMsg.CandidateAddrs, natHoleRespMsg.AssistedAddrs, natHoleRespMsg.DetectBehavior) newListenConn, raddr, err := nathole.MakeHole(sv.ctx, listenConn, natHoleRespMsg, []byte(sv.cfg.SecretKey)) if err != nil { listenConn.Close() xl.Warnf("make hole error: %v", err) return } listenConn = newListenConn xl.Infof("establishing nat hole connection successful, sid [%s], remoteAddr [%s]", natHoleRespMsg.Sid, raddr) if err := sv.session.Init(listenConn, raddr); err != nil { listenConn.Close() xl.Warnf("init tunnel session error: %v", err) return } } type TunnelSession interface { Init(listenConn *net.UDPConn, raddr *net.UDPAddr) error OpenConn(context.Context) (net.Conn, error) Close() } type KCPTunnelSession struct { session *fmux.Session lConn *net.UDPConn mu sync.RWMutex } func NewKCPTunnelSession() TunnelSession { return &KCPTunnelSession{} } func (ks *KCPTunnelSession) Init(listenConn *net.UDPConn, raddr *net.UDPAddr) error { listenConn.Close() laddr, _ := net.ResolveUDPAddr("udp", listenConn.LocalAddr().String()) lConn, err := net.DialUDP("udp", laddr, raddr) if err != nil { return fmt.Errorf("dial udp error: %v", err) } remote, err := netpkg.NewKCPConnFromUDP(lConn, true, raddr.String()) if err != nil { return fmt.Errorf("create kcp connection from udp connection error: %v", err) } fmuxCfg := fmux.DefaultConfig() fmuxCfg.KeepAliveInterval = 10 * time.Second fmuxCfg.MaxStreamWindowSize = 6 * 1024 * 1024 fmuxCfg.LogOutput = io.Discard session, err := fmux.Client(remote, fmuxCfg) if err != nil { remote.Close() return fmt.Errorf("initial client session error: %v", err) } ks.mu.Lock() ks.session = session ks.lConn = lConn ks.mu.Unlock() return nil } func (ks *KCPTunnelSession) OpenConn(_ context.Context) (net.Conn, error) { ks.mu.RLock() defer ks.mu.RUnlock() session := ks.session if session == nil { return nil, ErrNoTunnelSession } return session.Open() } func (ks *KCPTunnelSession) Close() { ks.mu.Lock() defer ks.mu.Unlock() if ks.session != nil { _ = ks.session.Close() ks.session = nil } if ks.lConn != nil { _ = ks.lConn.Close() ks.lConn = nil } } type QUICTunnelSession struct { session *quic.Conn listenConn *net.UDPConn mu sync.RWMutex clientCfg *v1.ClientCommonConfig } func NewQUICTunnelSession(clientCfg *v1.ClientCommonConfig) TunnelSession { return &QUICTunnelSession{ clientCfg: clientCfg, } } func (qs *QUICTunnelSession) Init(listenConn *net.UDPConn, raddr *net.UDPAddr) error { tlsConfig, err := transport.NewClientTLSConfig("", "", "", raddr.String()) if err != nil { return fmt.Errorf("create tls config error: %v", err) } tlsConfig.NextProtos = []string{"frp"} quicConn, err := quic.Dial(context.Background(), listenConn, raddr, tlsConfig, &quic.Config{ MaxIdleTimeout: time.Duration(qs.clientCfg.Transport.QUIC.MaxIdleTimeout) * time.Second, MaxIncomingStreams: int64(qs.clientCfg.Transport.QUIC.MaxIncomingStreams), KeepAlivePeriod: time.Duration(qs.clientCfg.Transport.QUIC.KeepalivePeriod) * time.Second, }) if err != nil { return fmt.Errorf("dial quic error: %v", err) } qs.mu.Lock() qs.session = quicConn qs.listenConn = listenConn qs.mu.Unlock() return nil } func (qs *QUICTunnelSession) OpenConn(ctx context.Context) (net.Conn, error) { qs.mu.RLock() defer qs.mu.RUnlock() session := qs.session if session == nil { return nil, ErrNoTunnelSession } stream, err := session.OpenStreamSync(ctx) if err != nil { return nil, err } return netpkg.QuicStreamToNetConn(stream, session), nil } func (qs *QUICTunnelSession) Close() { qs.mu.Lock() defer qs.mu.Unlock() if qs.session != nil { _ = qs.session.CloseWithError(0, "") qs.session = nil } if qs.listenConn != nil { _ = qs.listenConn.Close() qs.listenConn = nil } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/visitor/sudp.go
client/visitor/sudp.go
// Copyright 2017 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 visitor import ( "fmt" "io" "net" "strconv" "sync" "time" "github.com/fatedier/golib/errors" libio "github.com/fatedier/golib/io" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/proto/udp" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/xlog" ) type SUDPVisitor struct { *BaseVisitor checkCloseCh chan struct{} // udpConn is the listener of udp packet udpConn *net.UDPConn readCh chan *msg.UDPPacket sendCh chan *msg.UDPPacket cfg *v1.SUDPVisitorConfig } // SUDP Run start listen a udp port func (sv *SUDPVisitor) Run() (err error) { xl := xlog.FromContextSafe(sv.ctx) addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort))) if err != nil { return fmt.Errorf("sudp ResolveUDPAddr error: %v", err) } sv.udpConn, err = net.ListenUDP("udp", addr) if err != nil { return fmt.Errorf("listen udp port %s error: %v", addr.String(), err) } sv.sendCh = make(chan *msg.UDPPacket, 1024) sv.readCh = make(chan *msg.UDPPacket, 1024) xl.Infof("sudp start to work, listen on %s", addr) go sv.dispatcher() go udp.ForwardUserConn(sv.udpConn, sv.readCh, sv.sendCh, int(sv.clientCfg.UDPPacketSize)) return } func (sv *SUDPVisitor) dispatcher() { xl := xlog.FromContextSafe(sv.ctx) var ( visitorConn net.Conn err error firstPacket *msg.UDPPacket ) for { select { case firstPacket = <-sv.sendCh: if firstPacket == nil { xl.Infof("frpc sudp visitor proxy is closed") return } case <-sv.checkCloseCh: xl.Infof("frpc sudp visitor proxy is closed") return } visitorConn, err = sv.getNewVisitorConn() if err != nil { xl.Warnf("newVisitorConn to frps error: %v, try to reconnect", err) continue } // visitorConn always be closed when worker done. sv.worker(visitorConn, firstPacket) select { case <-sv.checkCloseCh: return default: } } } func (sv *SUDPVisitor) worker(workConn net.Conn, firstPacket *msg.UDPPacket) { xl := xlog.FromContextSafe(sv.ctx) xl.Debugf("starting sudp proxy worker") wg := &sync.WaitGroup{} wg.Add(2) closeCh := make(chan struct{}) // udp service -> frpc -> frps -> frpc visitor -> user workConnReaderFn := func(conn net.Conn) { defer func() { conn.Close() close(closeCh) wg.Done() }() for { var ( rawMsg msg.Message errRet error ) // frpc will send heartbeat in workConn to frpc visitor for keeping alive _ = conn.SetReadDeadline(time.Now().Add(60 * time.Second)) if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil { xl.Warnf("read from workconn for user udp conn error: %v", errRet) return } _ = conn.SetReadDeadline(time.Time{}) switch m := rawMsg.(type) { case *msg.Ping: xl.Debugf("frpc visitor get ping message from frpc") continue case *msg.UDPPacket: if errRet := errors.PanicToError(func() { sv.readCh <- m xl.Tracef("frpc visitor get udp packet from workConn: %s", m.Content) }); errRet != nil { xl.Infof("reader goroutine for udp work connection closed") return } } } } // udp service <- frpc <- frps <- frpc visitor <- user workConnSenderFn := func(conn net.Conn) { defer func() { conn.Close() wg.Done() }() var errRet error if firstPacket != nil { if errRet = msg.WriteMsg(conn, firstPacket); errRet != nil { xl.Warnf("sender goroutine for udp work connection closed: %v", errRet) return } xl.Tracef("send udp package to workConn: %s", firstPacket.Content) } for { select { case udpMsg, ok := <-sv.sendCh: if !ok { xl.Infof("sender goroutine for udp work connection closed") return } if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil { xl.Warnf("sender goroutine for udp work connection closed: %v", errRet) return } xl.Tracef("send udp package to workConn: %s", udpMsg.Content) case <-closeCh: return } } } go workConnReaderFn(workConn) go workConnSenderFn(workConn) wg.Wait() xl.Infof("sudp worker is closed") } func (sv *SUDPVisitor) getNewVisitorConn() (net.Conn, error) { xl := xlog.FromContextSafe(sv.ctx) visitorConn, err := sv.helper.ConnectServer() if err != nil { return nil, fmt.Errorf("frpc connect frps error: %v", err) } now := time.Now().Unix() newVisitorConnMsg := &msg.NewVisitorConn{ RunID: sv.helper.RunID(), ProxyName: sv.cfg.ServerName, SignKey: util.GetAuthKey(sv.cfg.SecretKey, now), Timestamp: now, UseEncryption: sv.cfg.Transport.UseEncryption, UseCompression: sv.cfg.Transport.UseCompression, } err = msg.WriteMsg(visitorConn, newVisitorConnMsg) if err != nil { return nil, fmt.Errorf("frpc send newVisitorConnMsg to frps error: %v", err) } var newVisitorConnRespMsg msg.NewVisitorConnResp _ = visitorConn.SetReadDeadline(time.Now().Add(10 * time.Second)) err = msg.ReadMsgInto(visitorConn, &newVisitorConnRespMsg) if err != nil { return nil, fmt.Errorf("frpc read newVisitorConnRespMsg error: %v", err) } _ = visitorConn.SetReadDeadline(time.Time{}) if newVisitorConnRespMsg.Error != "" { return nil, fmt.Errorf("start new visitor connection error: %s", newVisitorConnRespMsg.Error) } var remote io.ReadWriteCloser remote = visitorConn if sv.cfg.Transport.UseEncryption { remote, err = libio.WithEncryption(remote, []byte(sv.cfg.SecretKey)) if err != nil { xl.Errorf("create encryption stream error: %v", err) return nil, err } } if sv.cfg.Transport.UseCompression { remote = libio.WithCompression(remote) } return netpkg.WrapReadWriteCloserToConn(remote, visitorConn), nil } func (sv *SUDPVisitor) Close() { sv.mu.Lock() defer sv.mu.Unlock() select { case <-sv.checkCloseCh: return default: close(sv.checkCloseCh) } sv.BaseVisitor.Close() if sv.udpConn != nil { sv.udpConn.Close() } close(sv.readCh) close(sv.sendCh) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/visitor/visitor_manager.go
client/visitor/visitor_manager.go
// 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 visitor import ( "context" "fmt" "net" "reflect" "sync" "time" "github.com/samber/lo" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/transport" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/pkg/vnet" ) type Manager struct { clientCfg *v1.ClientCommonConfig cfgs map[string]v1.VisitorConfigurer visitors map[string]Visitor helper Helper checkInterval time.Duration keepVisitorsRunningOnce sync.Once mu sync.RWMutex ctx context.Context stopCh chan struct{} } func NewManager( ctx context.Context, runID string, clientCfg *v1.ClientCommonConfig, connectServer func() (net.Conn, error), msgTransporter transport.MessageTransporter, vnetController *vnet.Controller, ) *Manager { m := &Manager{ clientCfg: clientCfg, cfgs: make(map[string]v1.VisitorConfigurer), visitors: make(map[string]Visitor), checkInterval: 10 * time.Second, ctx: ctx, stopCh: make(chan struct{}), } m.helper = &visitorHelperImpl{ connectServerFn: connectServer, msgTransporter: msgTransporter, vnetController: vnetController, transferConnFn: m.TransferConn, runID: runID, } return m } // keepVisitorsRunning checks all visitors' status periodically, if some visitor is not running, start it. // It will only start after Reload is called and a new visitor is added. func (vm *Manager) keepVisitorsRunning() { xl := xlog.FromContextSafe(vm.ctx) ticker := time.NewTicker(vm.checkInterval) defer ticker.Stop() for { select { case <-vm.stopCh: xl.Tracef("gracefully shutdown visitor manager") return case <-ticker.C: vm.mu.Lock() for _, cfg := range vm.cfgs { name := cfg.GetBaseConfig().Name if _, exist := vm.visitors[name]; !exist { xl.Infof("try to start visitor [%s]", name) _ = vm.startVisitor(cfg) } } vm.mu.Unlock() } } } func (vm *Manager) Close() { vm.mu.Lock() defer vm.mu.Unlock() for _, v := range vm.visitors { v.Close() } select { case <-vm.stopCh: default: close(vm.stopCh) } } // Hold lock before calling this function. func (vm *Manager) startVisitor(cfg v1.VisitorConfigurer) (err error) { xl := xlog.FromContextSafe(vm.ctx) name := cfg.GetBaseConfig().Name visitor, err := NewVisitor(vm.ctx, cfg, vm.clientCfg, vm.helper) if err != nil { xl.Warnf("new visitor error: %v", err) return } err = visitor.Run() if err != nil { xl.Warnf("start error: %v", err) } else { vm.visitors[name] = visitor xl.Infof("start visitor success") } return } func (vm *Manager) UpdateAll(cfgs []v1.VisitorConfigurer) { if len(cfgs) > 0 { // Only start keepVisitorsRunning goroutine once and only when there is at least one visitor. vm.keepVisitorsRunningOnce.Do(func() { go vm.keepVisitorsRunning() }) } xl := xlog.FromContextSafe(vm.ctx) cfgsMap := lo.KeyBy(cfgs, func(c v1.VisitorConfigurer) string { return c.GetBaseConfig().Name }) vm.mu.Lock() defer vm.mu.Unlock() delNames := make([]string, 0) for name, oldCfg := range vm.cfgs { del := false cfg, ok := cfgsMap[name] if !ok || !reflect.DeepEqual(oldCfg, cfg) { del = true } if del { delNames = append(delNames, name) delete(vm.cfgs, name) if visitor, ok := vm.visitors[name]; ok { visitor.Close() } delete(vm.visitors, name) } } if len(delNames) > 0 { xl.Infof("visitor removed: %v", delNames) } addNames := make([]string, 0) for _, cfg := range cfgs { name := cfg.GetBaseConfig().Name if _, ok := vm.cfgs[name]; !ok { vm.cfgs[name] = cfg addNames = append(addNames, name) _ = vm.startVisitor(cfg) } } if len(addNames) > 0 { xl.Infof("visitor added: %v", addNames) } } // TransferConn transfers a connection to a visitor. func (vm *Manager) TransferConn(name string, conn net.Conn) error { vm.mu.RLock() defer vm.mu.RUnlock() v, ok := vm.visitors[name] if !ok { return fmt.Errorf("visitor [%s] not found", name) } return v.AcceptConn(conn) } type visitorHelperImpl struct { connectServerFn func() (net.Conn, error) msgTransporter transport.MessageTransporter vnetController *vnet.Controller transferConnFn func(name string, conn net.Conn) error runID string } func (v *visitorHelperImpl) ConnectServer() (net.Conn, error) { return v.connectServerFn() } func (v *visitorHelperImpl) TransferConn(name string, conn net.Conn) error { return v.transferConnFn(name, conn) } func (v *visitorHelperImpl) MsgTransporter() transport.MessageTransporter { return v.msgTransporter } func (v *visitorHelperImpl) VNetController() *vnet.Controller { return v.vnetController } func (v *visitorHelperImpl) RunID() string { return v.runID }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/visitor/visitor.go
client/visitor/visitor.go
// Copyright 2017 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 visitor import ( "context" "net" "sync" v1 "github.com/fatedier/frp/pkg/config/v1" plugin "github.com/fatedier/frp/pkg/plugin/visitor" "github.com/fatedier/frp/pkg/transport" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/pkg/vnet" ) // Helper wraps some functions for visitor to use. type Helper interface { // ConnectServer directly connects to the frp server. ConnectServer() (net.Conn, error) // TransferConn transfers the connection to another visitor. TransferConn(string, net.Conn) error // MsgTransporter returns the message transporter that is used to send and receive messages // to the frp server through the controller. MsgTransporter() transport.MessageTransporter // VNetController returns the vnet controller that is used to manage the virtual network. VNetController() *vnet.Controller // RunID returns the run id of current controller. RunID() string } // Visitor is used for forward traffics from local port tot remote service. type Visitor interface { Run() error AcceptConn(conn net.Conn) error Close() } func NewVisitor( ctx context.Context, cfg v1.VisitorConfigurer, clientCfg *v1.ClientCommonConfig, helper Helper, ) (Visitor, error) { xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(cfg.GetBaseConfig().Name) ctx = xlog.NewContext(ctx, xl) var visitor Visitor baseVisitor := BaseVisitor{ clientCfg: clientCfg, helper: helper, ctx: ctx, internalLn: netpkg.NewInternalListener(), } if cfg.GetBaseConfig().Plugin.Type != "" { p, err := plugin.Create( cfg.GetBaseConfig().Plugin.Type, plugin.PluginContext{ Name: cfg.GetBaseConfig().Name, Ctx: ctx, VnetController: helper.VNetController(), SendConnToVisitor: func(conn net.Conn) { _ = baseVisitor.AcceptConn(conn) }, }, cfg.GetBaseConfig().Plugin.VisitorPluginOptions, ) if err != nil { return nil, err } baseVisitor.plugin = p } switch cfg := cfg.(type) { case *v1.STCPVisitorConfig: visitor = &STCPVisitor{ BaseVisitor: &baseVisitor, cfg: cfg, } case *v1.XTCPVisitorConfig: visitor = &XTCPVisitor{ BaseVisitor: &baseVisitor, cfg: cfg, startTunnelCh: make(chan struct{}), } case *v1.SUDPVisitorConfig: visitor = &SUDPVisitor{ BaseVisitor: &baseVisitor, cfg: cfg, checkCloseCh: make(chan struct{}), } } return visitor, nil } type BaseVisitor struct { clientCfg *v1.ClientCommonConfig helper Helper l net.Listener internalLn *netpkg.InternalListener plugin plugin.Plugin mu sync.RWMutex ctx context.Context } func (v *BaseVisitor) AcceptConn(conn net.Conn) error { return v.internalLn.PutConn(conn) } func (v *BaseVisitor) Close() { if v.l != nil { v.l.Close() } if v.internalLn != nil { v.internalLn.Close() } if v.plugin != nil { v.plugin.Close() } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/proxy/proxy.go
client/proxy/proxy.go
// Copyright 2017 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 proxy import ( "context" "io" "net" "reflect" "strconv" "sync" "time" libio "github.com/fatedier/golib/io" libnet "github.com/fatedier/golib/net" "golang.org/x/time/rate" "github.com/fatedier/frp/pkg/config/types" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" plugin "github.com/fatedier/frp/pkg/plugin/client" "github.com/fatedier/frp/pkg/transport" "github.com/fatedier/frp/pkg/util/limit" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/pkg/vnet" ) var proxyFactoryRegistry = map[reflect.Type]func(*BaseProxy, v1.ProxyConfigurer) Proxy{} func RegisterProxyFactory(proxyConfType reflect.Type, factory func(*BaseProxy, v1.ProxyConfigurer) Proxy) { proxyFactoryRegistry[proxyConfType] = factory } // Proxy defines how to handle work connections for different proxy type. type Proxy interface { Run() error // InWorkConn accept work connections registered to server. InWorkConn(net.Conn, *msg.StartWorkConn) SetInWorkConnCallback(func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) /* continue */ bool) Close() } func NewProxy( ctx context.Context, pxyConf v1.ProxyConfigurer, clientCfg *v1.ClientCommonConfig, encryptionKey []byte, msgTransporter transport.MessageTransporter, vnetController *vnet.Controller, ) (pxy Proxy) { var limiter *rate.Limiter limitBytes := pxyConf.GetBaseConfig().Transport.BandwidthLimit.Bytes() if limitBytes > 0 && pxyConf.GetBaseConfig().Transport.BandwidthLimitMode == types.BandwidthLimitModeClient { limiter = rate.NewLimiter(rate.Limit(float64(limitBytes)), int(limitBytes)) } baseProxy := BaseProxy{ baseCfg: pxyConf.GetBaseConfig(), clientCfg: clientCfg, encryptionKey: encryptionKey, limiter: limiter, msgTransporter: msgTransporter, vnetController: vnetController, xl: xlog.FromContextSafe(ctx), ctx: ctx, } factory := proxyFactoryRegistry[reflect.TypeOf(pxyConf)] if factory == nil { return nil } return factory(&baseProxy, pxyConf) } type BaseProxy struct { baseCfg *v1.ProxyBaseConfig clientCfg *v1.ClientCommonConfig encryptionKey []byte msgTransporter transport.MessageTransporter vnetController *vnet.Controller limiter *rate.Limiter // proxyPlugin is used to handle connections instead of dialing to local service. // It's only validate for TCP protocol now. proxyPlugin plugin.Plugin inWorkConnCallback func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) /* continue */ bool mu sync.RWMutex xl *xlog.Logger ctx context.Context } func (pxy *BaseProxy) Run() error { if pxy.baseCfg.Plugin.Type != "" { p, err := plugin.Create(pxy.baseCfg.Plugin.Type, plugin.PluginContext{ Name: pxy.baseCfg.Name, VnetController: pxy.vnetController, }, pxy.baseCfg.Plugin.ClientPluginOptions) if err != nil { return err } pxy.proxyPlugin = p } return nil } func (pxy *BaseProxy) Close() { if pxy.proxyPlugin != nil { pxy.proxyPlugin.Close() } } func (pxy *BaseProxy) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) { pxy.inWorkConnCallback = cb } func (pxy *BaseProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) { if pxy.inWorkConnCallback != nil { if !pxy.inWorkConnCallback(pxy.baseCfg, conn, m) { return } } pxy.HandleTCPWorkConnection(conn, m, pxy.encryptionKey) } // Common handler for tcp work connections. func (pxy *BaseProxy) HandleTCPWorkConnection(workConn net.Conn, m *msg.StartWorkConn, encKey []byte) { xl := pxy.xl baseCfg := pxy.baseCfg var ( remote io.ReadWriteCloser err error ) remote = workConn if pxy.limiter != nil { remote = libio.WrapReadWriteCloser(limit.NewReader(workConn, pxy.limiter), limit.NewWriter(workConn, pxy.limiter), func() error { return workConn.Close() }) } xl.Tracef("handle tcp work connection, useEncryption: %t, useCompression: %t", baseCfg.Transport.UseEncryption, baseCfg.Transport.UseCompression) if baseCfg.Transport.UseEncryption { remote, err = libio.WithEncryption(remote, encKey) if err != nil { workConn.Close() xl.Errorf("create encryption stream error: %v", err) return } } var compressionResourceRecycleFn func() if baseCfg.Transport.UseCompression { remote, compressionResourceRecycleFn = libio.WithCompressionFromPool(remote) } // check if we need to send proxy protocol info var connInfo plugin.ConnectionInfo if m.SrcAddr != "" && m.SrcPort != 0 { if m.DstAddr == "" { m.DstAddr = "127.0.0.1" } srcAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.SrcAddr, strconv.Itoa(int(m.SrcPort)))) dstAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.DstAddr, strconv.Itoa(int(m.DstPort)))) connInfo.SrcAddr = srcAddr connInfo.DstAddr = dstAddr } if baseCfg.Transport.ProxyProtocolVersion != "" && m.SrcAddr != "" && m.SrcPort != 0 { // Use the common proxy protocol builder function header := netpkg.BuildProxyProtocolHeaderStruct(connInfo.SrcAddr, connInfo.DstAddr, baseCfg.Transport.ProxyProtocolVersion) connInfo.ProxyProtocolHeader = header } connInfo.Conn = remote connInfo.UnderlyingConn = workConn if pxy.proxyPlugin != nil { // if plugin is set, let plugin handle connection first xl.Debugf("handle by plugin: %s", pxy.proxyPlugin.Name()) pxy.proxyPlugin.Handle(pxy.ctx, &connInfo) xl.Debugf("handle by plugin finished") return } localConn, err := libnet.Dial( net.JoinHostPort(baseCfg.LocalIP, strconv.Itoa(baseCfg.LocalPort)), libnet.WithTimeout(10*time.Second), ) if err != nil { workConn.Close() xl.Errorf("connect to local service [%s:%d] error: %v", baseCfg.LocalIP, baseCfg.LocalPort, err) return } xl.Debugf("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(), localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String()) if connInfo.ProxyProtocolHeader != nil { if _, err := connInfo.ProxyProtocolHeader.WriteTo(localConn); err != nil { workConn.Close() xl.Errorf("write proxy protocol header to local conn error: %v", err) return } } _, _, errs := libio.Join(localConn, remote) xl.Debugf("join connections closed") if len(errs) > 0 { xl.Tracef("join connections errors: %v", errs) } if compressionResourceRecycleFn != nil { compressionResourceRecycleFn() } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/proxy/proxy_wrapper.go
client/proxy/proxy_wrapper.go
// Copyright 2023 The frp 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 proxy import ( "context" "fmt" "net" "strconv" "sync" "sync/atomic" "time" "github.com/fatedier/golib/errors" "github.com/fatedier/frp/client/event" "github.com/fatedier/frp/client/health" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/transport" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/pkg/vnet" ) const ( ProxyPhaseNew = "new" ProxyPhaseWaitStart = "wait start" ProxyPhaseStartErr = "start error" ProxyPhaseRunning = "running" ProxyPhaseCheckFailed = "check failed" ProxyPhaseClosed = "closed" ) var ( statusCheckInterval = 3 * time.Second waitResponseTimeout = 20 * time.Second startErrTimeout = 30 * time.Second ) type WorkingStatus struct { Name string `json:"name"` Type string `json:"type"` Phase string `json:"status"` Err string `json:"err"` Cfg v1.ProxyConfigurer `json:"cfg"` // Got from server. RemoteAddr string `json:"remote_addr"` } type Wrapper struct { WorkingStatus // underlying proxy pxy Proxy // if ProxyConf has healcheck config // monitor will watch if it is alive monitor *health.Monitor // event handler handler event.Handler msgTransporter transport.MessageTransporter // vnet controller vnetController *vnet.Controller health uint32 lastSendStartMsg time.Time lastStartErr time.Time closeCh chan struct{} healthNotifyCh chan struct{} mu sync.RWMutex xl *xlog.Logger ctx context.Context } func NewWrapper( ctx context.Context, cfg v1.ProxyConfigurer, clientCfg *v1.ClientCommonConfig, encryptionKey []byte, eventHandler event.Handler, msgTransporter transport.MessageTransporter, vnetController *vnet.Controller, ) *Wrapper { baseInfo := cfg.GetBaseConfig() xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(baseInfo.Name) pw := &Wrapper{ WorkingStatus: WorkingStatus{ Name: baseInfo.Name, Type: baseInfo.Type, Phase: ProxyPhaseNew, Cfg: cfg, }, closeCh: make(chan struct{}), healthNotifyCh: make(chan struct{}), handler: eventHandler, msgTransporter: msgTransporter, vnetController: vnetController, xl: xl, ctx: xlog.NewContext(ctx, xl), } if baseInfo.HealthCheck.Type != "" && baseInfo.LocalPort > 0 { pw.health = 1 // means failed addr := net.JoinHostPort(baseInfo.LocalIP, strconv.Itoa(baseInfo.LocalPort)) pw.monitor = health.NewMonitor(pw.ctx, baseInfo.HealthCheck, addr, pw.statusNormalCallback, pw.statusFailedCallback) xl.Tracef("enable health check monitor") } pw.pxy = NewProxy(pw.ctx, pw.Cfg, clientCfg, encryptionKey, pw.msgTransporter, pw.vnetController) return pw } func (pw *Wrapper) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) { pw.pxy.SetInWorkConnCallback(cb) } func (pw *Wrapper) SetRunningStatus(remoteAddr string, respErr string) error { pw.mu.Lock() defer pw.mu.Unlock() if pw.Phase != ProxyPhaseWaitStart { return fmt.Errorf("status not wait start, ignore start message") } pw.RemoteAddr = remoteAddr if respErr != "" { pw.Phase = ProxyPhaseStartErr pw.Err = respErr pw.lastStartErr = time.Now() return fmt.Errorf("%s", pw.Err) } if err := pw.pxy.Run(); err != nil { pw.close() pw.Phase = ProxyPhaseStartErr pw.Err = err.Error() pw.lastStartErr = time.Now() return err } pw.Phase = ProxyPhaseRunning pw.Err = "" return nil } func (pw *Wrapper) Start() { go pw.checkWorker() if pw.monitor != nil { go pw.monitor.Start() } } func (pw *Wrapper) Stop() { pw.mu.Lock() defer pw.mu.Unlock() close(pw.closeCh) close(pw.healthNotifyCh) pw.pxy.Close() if pw.monitor != nil { pw.monitor.Stop() } pw.Phase = ProxyPhaseClosed pw.close() } func (pw *Wrapper) close() { _ = pw.handler(&event.CloseProxyPayload{ CloseProxyMsg: &msg.CloseProxy{ ProxyName: pw.Name, }, }) } func (pw *Wrapper) checkWorker() { xl := pw.xl if pw.monitor != nil { // let monitor do check request first time.Sleep(500 * time.Millisecond) } for { // check proxy status now := time.Now() if atomic.LoadUint32(&pw.health) == 0 { pw.mu.Lock() if pw.Phase == ProxyPhaseNew || pw.Phase == ProxyPhaseCheckFailed || (pw.Phase == ProxyPhaseWaitStart && now.After(pw.lastSendStartMsg.Add(waitResponseTimeout))) || (pw.Phase == ProxyPhaseStartErr && now.After(pw.lastStartErr.Add(startErrTimeout))) { xl.Tracef("change status from [%s] to [%s]", pw.Phase, ProxyPhaseWaitStart) pw.Phase = ProxyPhaseWaitStart var newProxyMsg msg.NewProxy pw.Cfg.MarshalToMsg(&newProxyMsg) pw.lastSendStartMsg = now _ = pw.handler(&event.StartProxyPayload{ NewProxyMsg: &newProxyMsg, }) } pw.mu.Unlock() } else { pw.mu.Lock() if pw.Phase == ProxyPhaseRunning || pw.Phase == ProxyPhaseWaitStart { pw.close() xl.Tracef("change status from [%s] to [%s]", pw.Phase, ProxyPhaseCheckFailed) pw.Phase = ProxyPhaseCheckFailed } pw.mu.Unlock() } select { case <-pw.closeCh: return case <-time.After(statusCheckInterval): case <-pw.healthNotifyCh: } } } func (pw *Wrapper) statusNormalCallback() { xl := pw.xl atomic.StoreUint32(&pw.health, 0) _ = errors.PanicToError(func() { select { case pw.healthNotifyCh <- struct{}{}: default: } }) xl.Infof("health check success") } func (pw *Wrapper) statusFailedCallback() { xl := pw.xl atomic.StoreUint32(&pw.health, 1) _ = errors.PanicToError(func() { select { case pw.healthNotifyCh <- struct{}{}: default: } }) xl.Infof("health check failed") } func (pw *Wrapper) InWorkConn(workConn net.Conn, m *msg.StartWorkConn) { xl := pw.xl pw.mu.RLock() pxy := pw.pxy pw.mu.RUnlock() if pxy != nil && pw.Phase == ProxyPhaseRunning { xl.Debugf("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String()) go pxy.InWorkConn(workConn, m) } else { workConn.Close() } } func (pw *Wrapper) GetStatus() *WorkingStatus { pw.mu.RLock() defer pw.mu.RUnlock() ps := &WorkingStatus{ Name: pw.Name, Type: pw.Type, Phase: pw.Phase, Err: pw.Err, Cfg: pw.Cfg, RemoteAddr: pw.RemoteAddr, } return ps }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/proxy/xtcp.go
client/proxy/xtcp.go
// Copyright 2023 The frp 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. //go:build !frps package proxy import ( "io" "net" "reflect" "time" fmux "github.com/hashicorp/yamux" "github.com/quic-go/quic-go" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/nathole" "github.com/fatedier/frp/pkg/transport" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.XTCPProxyConfig{}), NewXTCPProxy) } type XTCPProxy struct { *BaseProxy cfg *v1.XTCPProxyConfig } func NewXTCPProxy(baseProxy *BaseProxy, cfg v1.ProxyConfigurer) Proxy { unwrapped, ok := cfg.(*v1.XTCPProxyConfig) if !ok { return nil } return &XTCPProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *XTCPProxy) InWorkConn(conn net.Conn, startWorkConnMsg *msg.StartWorkConn) { xl := pxy.xl defer conn.Close() var natHoleSidMsg msg.NatHoleSid err := msg.ReadMsgInto(conn, &natHoleSidMsg) if err != nil { xl.Errorf("xtcp read from workConn error: %v", err) return } xl.Tracef("nathole prepare start") // Prepare NAT traversal options var opts nathole.PrepareOptions if pxy.cfg.NatTraversal != nil && pxy.cfg.NatTraversal.DisableAssistedAddrs { opts.DisableAssistedAddrs = true } prepareResult, err := nathole.Prepare([]string{pxy.clientCfg.NatHoleSTUNServer}, opts) if err != nil { xl.Warnf("nathole prepare error: %v", err) return } xl.Infof("nathole prepare success, nat type: %s, behavior: %s, addresses: %v, assistedAddresses: %v", prepareResult.NatType, prepareResult.Behavior, prepareResult.Addrs, prepareResult.AssistedAddrs) defer prepareResult.ListenConn.Close() // send NatHoleClient msg to server transactionID := nathole.NewTransactionID() natHoleClientMsg := &msg.NatHoleClient{ TransactionID: transactionID, ProxyName: pxy.cfg.Name, Sid: natHoleSidMsg.Sid, MappedAddrs: prepareResult.Addrs, AssistedAddrs: prepareResult.AssistedAddrs, } xl.Tracef("nathole exchange info start") natHoleRespMsg, err := nathole.ExchangeInfo(pxy.ctx, pxy.msgTransporter, transactionID, natHoleClientMsg, 5*time.Second) if err != nil { xl.Warnf("nathole exchange info error: %v", err) return } xl.Infof("get natHoleRespMsg, sid [%s], protocol [%s], candidate address %v, assisted address %v, detectBehavior: %+v", natHoleRespMsg.Sid, natHoleRespMsg.Protocol, natHoleRespMsg.CandidateAddrs, natHoleRespMsg.AssistedAddrs, natHoleRespMsg.DetectBehavior) listenConn := prepareResult.ListenConn newListenConn, raddr, err := nathole.MakeHole(pxy.ctx, listenConn, natHoleRespMsg, []byte(pxy.cfg.Secretkey)) if err != nil { listenConn.Close() xl.Warnf("make hole error: %v", err) _ = pxy.msgTransporter.Send(&msg.NatHoleReport{ Sid: natHoleRespMsg.Sid, Success: false, }) return } listenConn = newListenConn xl.Infof("establishing nat hole connection successful, sid [%s], remoteAddr [%s]", natHoleRespMsg.Sid, raddr) _ = pxy.msgTransporter.Send(&msg.NatHoleReport{ Sid: natHoleRespMsg.Sid, Success: true, }) if natHoleRespMsg.Protocol == "kcp" { pxy.listenByKCP(listenConn, raddr, startWorkConnMsg) return } // default is quic pxy.listenByQUIC(listenConn, raddr, startWorkConnMsg) } func (pxy *XTCPProxy) listenByKCP(listenConn *net.UDPConn, raddr *net.UDPAddr, startWorkConnMsg *msg.StartWorkConn) { xl := pxy.xl listenConn.Close() laddr, _ := net.ResolveUDPAddr("udp", listenConn.LocalAddr().String()) lConn, err := net.DialUDP("udp", laddr, raddr) if err != nil { xl.Warnf("dial udp error: %v", err) return } defer lConn.Close() remote, err := netpkg.NewKCPConnFromUDP(lConn, true, raddr.String()) if err != nil { xl.Warnf("create kcp connection from udp connection error: %v", err) return } fmuxCfg := fmux.DefaultConfig() fmuxCfg.KeepAliveInterval = 10 * time.Second fmuxCfg.MaxStreamWindowSize = 6 * 1024 * 1024 fmuxCfg.LogOutput = io.Discard session, err := fmux.Server(remote, fmuxCfg) if err != nil { xl.Errorf("create mux session error: %v", err) return } defer session.Close() for { muxConn, err := session.Accept() if err != nil { xl.Errorf("accept connection error: %v", err) return } go pxy.HandleTCPWorkConnection(muxConn, startWorkConnMsg, []byte(pxy.cfg.Secretkey)) } } func (pxy *XTCPProxy) listenByQUIC(listenConn *net.UDPConn, _ *net.UDPAddr, startWorkConnMsg *msg.StartWorkConn) { xl := pxy.xl defer listenConn.Close() tlsConfig, err := transport.NewServerTLSConfig("", "", "") if err != nil { xl.Warnf("create tls config error: %v", err) return } tlsConfig.NextProtos = []string{"frp"} quicListener, err := quic.Listen(listenConn, tlsConfig, &quic.Config{ MaxIdleTimeout: time.Duration(pxy.clientCfg.Transport.QUIC.MaxIdleTimeout) * time.Second, MaxIncomingStreams: int64(pxy.clientCfg.Transport.QUIC.MaxIncomingStreams), KeepAlivePeriod: time.Duration(pxy.clientCfg.Transport.QUIC.KeepalivePeriod) * time.Second, }, ) if err != nil { xl.Warnf("dial quic error: %v", err) return } // only accept one connection from raddr c, err := quicListener.Accept(pxy.ctx) if err != nil { xl.Errorf("quic accept connection error: %v", err) return } for { stream, err := c.AcceptStream(pxy.ctx) if err != nil { xl.Debugf("quic accept stream error: %v", err) _ = c.CloseWithError(0, "") return } go pxy.HandleTCPWorkConnection(netpkg.QuicStreamToNetConn(stream, c), startWorkConnMsg, []byte(pxy.cfg.Secretkey)) } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/proxy/sudp.go
client/proxy/sudp.go
// Copyright 2023 The frp 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. //go:build !frps package proxy import ( "io" "net" "reflect" "strconv" "sync" "time" "github.com/fatedier/golib/errors" libio "github.com/fatedier/golib/io" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/proto/udp" "github.com/fatedier/frp/pkg/util/limit" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.SUDPProxyConfig{}), NewSUDPProxy) } type SUDPProxy struct { *BaseProxy cfg *v1.SUDPProxyConfig localAddr *net.UDPAddr closeCh chan struct{} } func NewSUDPProxy(baseProxy *BaseProxy, cfg v1.ProxyConfigurer) Proxy { unwrapped, ok := cfg.(*v1.SUDPProxyConfig) if !ok { return nil } return &SUDPProxy{ BaseProxy: baseProxy, cfg: unwrapped, closeCh: make(chan struct{}), } } func (pxy *SUDPProxy) Run() (err error) { pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort))) if err != nil { return } return } func (pxy *SUDPProxy) Close() { pxy.mu.Lock() defer pxy.mu.Unlock() select { case <-pxy.closeCh: return default: close(pxy.closeCh) } } func (pxy *SUDPProxy) InWorkConn(conn net.Conn, _ *msg.StartWorkConn) { xl := pxy.xl xl.Infof("incoming a new work connection for sudp proxy, %s", conn.RemoteAddr().String()) var rwc io.ReadWriteCloser = conn var err error if pxy.limiter != nil { rwc = libio.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error { return conn.Close() }) } if pxy.cfg.Transport.UseEncryption { rwc, err = libio.WithEncryption(rwc, pxy.encryptionKey) if err != nil { conn.Close() xl.Errorf("create encryption stream error: %v", err) return } } if pxy.cfg.Transport.UseCompression { rwc = libio.WithCompression(rwc) } conn = netpkg.WrapReadWriteCloserToConn(rwc, conn) workConn := conn readCh := make(chan *msg.UDPPacket, 1024) sendCh := make(chan msg.Message, 1024) isClose := false mu := &sync.Mutex{} closeFn := func() { mu.Lock() defer mu.Unlock() if isClose { return } isClose = true if workConn != nil { workConn.Close() } close(readCh) close(sendCh) } // udp service <- frpc <- frps <- frpc visitor <- user workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) { defer closeFn() for { // first to check sudp proxy is closed or not select { case <-pxy.closeCh: xl.Tracef("frpc sudp proxy is closed") return default: } var udpMsg msg.UDPPacket if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil { xl.Warnf("read from workConn for sudp error: %v", errRet) return } if errRet := errors.PanicToError(func() { readCh <- &udpMsg }); errRet != nil { xl.Warnf("reader goroutine for sudp work connection closed: %v", errRet) return } } } // udp service -> frpc -> frps -> frpc visitor -> user workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) { defer func() { closeFn() xl.Infof("writer goroutine for sudp work connection closed") }() var errRet error for rawMsg := range sendCh { switch m := rawMsg.(type) { case *msg.UDPPacket: xl.Tracef("frpc send udp package to frpc visitor, [udp local: %v, remote: %v], [tcp work conn local: %v, remote: %v]", m.LocalAddr.String(), m.RemoteAddr.String(), conn.LocalAddr().String(), conn.RemoteAddr().String()) case *msg.Ping: xl.Tracef("frpc send ping message to frpc visitor") } if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil { xl.Errorf("sudp work write error: %v", errRet) return } } } heartbeatFn := func(sendCh chan msg.Message) { ticker := time.NewTicker(30 * time.Second) defer func() { ticker.Stop() closeFn() }() var errRet error for { select { case <-ticker.C: if errRet = errors.PanicToError(func() { sendCh <- &msg.Ping{} }); errRet != nil { xl.Warnf("heartbeat goroutine for sudp work connection closed") return } case <-pxy.closeCh: xl.Tracef("frpc sudp proxy is closed") return } } } go workConnSenderFn(workConn, sendCh) go workConnReaderFn(workConn, readCh) go heartbeatFn(sendCh) udp.Forwarder(pxy.localAddr, readCh, sendCh, int(pxy.clientCfg.UDPPacketSize), pxy.cfg.Transport.ProxyProtocolVersion) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/proxy/udp.go
client/proxy/udp.go
// Copyright 2023 The frp 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. //go:build !frps package proxy import ( "io" "net" "reflect" "strconv" "time" "github.com/fatedier/golib/errors" libio "github.com/fatedier/golib/io" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/proto/udp" "github.com/fatedier/frp/pkg/util/limit" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { RegisterProxyFactory(reflect.TypeOf(&v1.UDPProxyConfig{}), NewUDPProxy) } type UDPProxy struct { *BaseProxy cfg *v1.UDPProxyConfig localAddr *net.UDPAddr readCh chan *msg.UDPPacket // include msg.UDPPacket and msg.Ping sendCh chan msg.Message workConn net.Conn closed bool } func NewUDPProxy(baseProxy *BaseProxy, cfg v1.ProxyConfigurer) Proxy { unwrapped, ok := cfg.(*v1.UDPProxyConfig) if !ok { return nil } return &UDPProxy{ BaseProxy: baseProxy, cfg: unwrapped, } } func (pxy *UDPProxy) Run() (err error) { pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort))) if err != nil { return } return } func (pxy *UDPProxy) Close() { pxy.mu.Lock() defer pxy.mu.Unlock() if !pxy.closed { pxy.closed = true if pxy.workConn != nil { pxy.workConn.Close() } if pxy.readCh != nil { close(pxy.readCh) } if pxy.sendCh != nil { close(pxy.sendCh) } } } func (pxy *UDPProxy) InWorkConn(conn net.Conn, _ *msg.StartWorkConn) { xl := pxy.xl xl.Infof("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String()) // close resources related with old workConn pxy.Close() var rwc io.ReadWriteCloser = conn var err error if pxy.limiter != nil { rwc = libio.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error { return conn.Close() }) } if pxy.cfg.Transport.UseEncryption { rwc, err = libio.WithEncryption(rwc, pxy.encryptionKey) if err != nil { conn.Close() xl.Errorf("create encryption stream error: %v", err) return } } if pxy.cfg.Transport.UseCompression { rwc = libio.WithCompression(rwc) } conn = netpkg.WrapReadWriteCloserToConn(rwc, conn) pxy.mu.Lock() pxy.workConn = conn pxy.readCh = make(chan *msg.UDPPacket, 1024) pxy.sendCh = make(chan msg.Message, 1024) pxy.closed = false pxy.mu.Unlock() workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) { for { var udpMsg msg.UDPPacket if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil { xl.Warnf("read from workConn for udp error: %v", errRet) return } if errRet := errors.PanicToError(func() { xl.Tracef("get udp package from workConn: %s", udpMsg.Content) readCh <- &udpMsg }); errRet != nil { xl.Infof("reader goroutine for udp work connection closed: %v", errRet) return } } } workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) { defer func() { xl.Infof("writer goroutine for udp work connection closed") }() var errRet error for rawMsg := range sendCh { switch m := rawMsg.(type) { case *msg.UDPPacket: xl.Tracef("send udp package to workConn: %s", m.Content) case *msg.Ping: xl.Tracef("send ping message to udp workConn") } if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil { xl.Errorf("udp work write error: %v", errRet) return } } } heartbeatFn := func(sendCh chan msg.Message) { var errRet error for { time.Sleep(time.Duration(30) * time.Second) if errRet = errors.PanicToError(func() { sendCh <- &msg.Ping{} }); errRet != nil { xl.Tracef("heartbeat goroutine for udp work connection closed") break } } } go workConnSenderFn(pxy.workConn, pxy.sendCh) go workConnReaderFn(pxy.workConn, pxy.readCh) go heartbeatFn(pxy.sendCh) // Call Forwarder with proxy protocol version (empty string means no proxy protocol) udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh, int(pxy.clientCfg.UDPPacketSize), pxy.cfg.Transport.ProxyProtocolVersion) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/proxy/proxy_manager.go
client/proxy/proxy_manager.go
// Copyright 2023 The frp 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 proxy import ( "context" "fmt" "net" "reflect" "sync" "github.com/samber/lo" "github.com/fatedier/frp/client/event" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/transport" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/pkg/vnet" ) type Manager struct { proxies map[string]*Wrapper msgTransporter transport.MessageTransporter inWorkConnCallback func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool vnetController *vnet.Controller closed bool mu sync.RWMutex encryptionKey []byte clientCfg *v1.ClientCommonConfig ctx context.Context } func NewManager( ctx context.Context, clientCfg *v1.ClientCommonConfig, encryptionKey []byte, msgTransporter transport.MessageTransporter, vnetController *vnet.Controller, ) *Manager { return &Manager{ proxies: make(map[string]*Wrapper), msgTransporter: msgTransporter, vnetController: vnetController, closed: false, encryptionKey: encryptionKey, clientCfg: clientCfg, ctx: ctx, } } func (pm *Manager) StartProxy(name string, remoteAddr string, serverRespErr string) error { pm.mu.RLock() pxy, ok := pm.proxies[name] pm.mu.RUnlock() if !ok { return fmt.Errorf("proxy [%s] not found", name) } err := pxy.SetRunningStatus(remoteAddr, serverRespErr) if err != nil { return err } return nil } func (pm *Manager) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) { pm.inWorkConnCallback = cb } func (pm *Manager) Close() { pm.mu.Lock() defer pm.mu.Unlock() for _, pxy := range pm.proxies { pxy.Stop() } pm.proxies = make(map[string]*Wrapper) } func (pm *Manager) HandleWorkConn(name string, workConn net.Conn, m *msg.StartWorkConn) { pm.mu.RLock() pw, ok := pm.proxies[name] pm.mu.RUnlock() if ok { pw.InWorkConn(workConn, m) } else { workConn.Close() } } func (pm *Manager) HandleEvent(payload any) error { var m msg.Message switch e := payload.(type) { case *event.StartProxyPayload: m = e.NewProxyMsg case *event.CloseProxyPayload: m = e.CloseProxyMsg default: return event.ErrPayloadType } return pm.msgTransporter.Send(m) } func (pm *Manager) GetAllProxyStatus() []*WorkingStatus { ps := make([]*WorkingStatus, 0) pm.mu.RLock() defer pm.mu.RUnlock() for _, pxy := range pm.proxies { ps = append(ps, pxy.GetStatus()) } return ps } func (pm *Manager) GetProxyStatus(name string) (*WorkingStatus, bool) { pm.mu.RLock() defer pm.mu.RUnlock() if pxy, ok := pm.proxies[name]; ok { return pxy.GetStatus(), true } return nil, false } func (pm *Manager) UpdateAll(proxyCfgs []v1.ProxyConfigurer) { xl := xlog.FromContextSafe(pm.ctx) proxyCfgsMap := lo.KeyBy(proxyCfgs, func(c v1.ProxyConfigurer) string { return c.GetBaseConfig().Name }) pm.mu.Lock() defer pm.mu.Unlock() delPxyNames := make([]string, 0) for name, pxy := range pm.proxies { del := false cfg, ok := proxyCfgsMap[name] if !ok || !reflect.DeepEqual(pxy.Cfg, cfg) { del = true } if del { delPxyNames = append(delPxyNames, name) delete(pm.proxies, name) pxy.Stop() } } if len(delPxyNames) > 0 { xl.Infof("proxy removed: %s", delPxyNames) } addPxyNames := make([]string, 0) for _, cfg := range proxyCfgs { name := cfg.GetBaseConfig().Name if _, ok := pm.proxies[name]; !ok { pxy := NewWrapper(pm.ctx, cfg, pm.clientCfg, pm.encryptionKey, pm.HandleEvent, pm.msgTransporter, pm.vnetController) if pm.inWorkConnCallback != nil { pxy.SetInWorkConnCallback(pm.inWorkConnCallback) } pm.proxies[name] = pxy addPxyNames = append(addPxyNames, name) pxy.Start() } } if len(addPxyNames) > 0 { xl.Infof("proxy added: %s", addPxyNames) } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/proxy/general_tcp.go
client/proxy/general_tcp.go
// Copyright 2023 The frp 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 proxy import ( "reflect" v1 "github.com/fatedier/frp/pkg/config/v1" ) func init() { pxyConfs := []v1.ProxyConfigurer{ &v1.TCPProxyConfig{}, &v1.HTTPProxyConfig{}, &v1.HTTPSProxyConfig{}, &v1.STCPProxyConfig{}, &v1.TCPMuxProxyConfig{}, } for _, cfg := range pxyConfs { RegisterProxyFactory(reflect.TypeOf(cfg), NewGeneralTCPProxy) } } // GeneralTCPProxy is a general implementation of Proxy interface for TCP protocol. // If the default GeneralTCPProxy cannot meet the requirements, you can customize // the implementation of the Proxy interface. type GeneralTCPProxy struct { *BaseProxy } func NewGeneralTCPProxy(baseProxy *BaseProxy, _ v1.ProxyConfigurer) Proxy { return &GeneralTCPProxy{ BaseProxy: baseProxy, } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/health/health.go
client/health/health.go
// 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 health import ( "context" "errors" "fmt" "io" "net" "net/http" "strings" "time" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/xlog" ) var ErrHealthCheckType = errors.New("error health check type") type Monitor struct { checkType string interval time.Duration timeout time.Duration maxFailedTimes int // For tcp addr string // For http url string header http.Header failedTimes uint64 statusOK bool statusNormalFn func() statusFailedFn func() ctx context.Context cancel context.CancelFunc } func NewMonitor(ctx context.Context, cfg v1.HealthCheckConfig, addr string, statusNormalFn func(), statusFailedFn func(), ) *Monitor { if cfg.IntervalSeconds <= 0 { cfg.IntervalSeconds = 10 } if cfg.TimeoutSeconds <= 0 { cfg.TimeoutSeconds = 3 } if cfg.MaxFailed <= 0 { cfg.MaxFailed = 1 } newctx, cancel := context.WithCancel(ctx) var url string if cfg.Type == "http" && cfg.Path != "" { s := "http://" + addr if !strings.HasPrefix(cfg.Path, "/") { s += "/" } url = s + cfg.Path } header := make(http.Header) for _, h := range cfg.HTTPHeaders { header.Set(h.Name, h.Value) } return &Monitor{ checkType: cfg.Type, interval: time.Duration(cfg.IntervalSeconds) * time.Second, timeout: time.Duration(cfg.TimeoutSeconds) * time.Second, maxFailedTimes: cfg.MaxFailed, addr: addr, url: url, header: header, statusOK: false, statusNormalFn: statusNormalFn, statusFailedFn: statusFailedFn, ctx: newctx, cancel: cancel, } } func (monitor *Monitor) Start() { go monitor.checkWorker() } func (monitor *Monitor) Stop() { monitor.cancel() } func (monitor *Monitor) checkWorker() { xl := xlog.FromContextSafe(monitor.ctx) for { doCtx, cancel := context.WithDeadline(monitor.ctx, time.Now().Add(monitor.timeout)) err := monitor.doCheck(doCtx) // check if this monitor has been closed select { case <-monitor.ctx.Done(): cancel() return default: cancel() } if err == nil { xl.Tracef("do one health check success") if !monitor.statusOK && monitor.statusNormalFn != nil { xl.Infof("health check status change to success") monitor.statusOK = true monitor.statusNormalFn() } } else { xl.Warnf("do one health check failed: %v", err) monitor.failedTimes++ if monitor.statusOK && int(monitor.failedTimes) >= monitor.maxFailedTimes && monitor.statusFailedFn != nil { xl.Warnf("health check status change to failed") monitor.statusOK = false monitor.statusFailedFn() } } time.Sleep(monitor.interval) } } func (monitor *Monitor) doCheck(ctx context.Context) error { switch monitor.checkType { case "tcp": return monitor.doTCPCheck(ctx) case "http": return monitor.doHTTPCheck(ctx) default: return ErrHealthCheckType } } func (monitor *Monitor) doTCPCheck(ctx context.Context) error { // if tcp address is not specified, always return nil if monitor.addr == "" { return nil } var d net.Dialer conn, err := d.DialContext(ctx, "tcp", monitor.addr) if err != nil { return err } conn.Close() return nil } func (monitor *Monitor) doHTTPCheck(ctx context.Context) error { req, err := http.NewRequestWithContext(ctx, "GET", monitor.url, nil) if err != nil { return err } req.Header = monitor.header req.Host = monitor.header.Get("Host") resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() _, _ = io.Copy(io.Discard, resp.Body) if resp.StatusCode/100 != 2 { return fmt.Errorf("do http health check, StatusCode is [%d] not 2xx", resp.StatusCode) } return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/client/event/event.go
client/event/event.go
package event import ( "errors" "github.com/fatedier/frp/pkg/msg" ) var ErrPayloadType = errors.New("error payload type") type Handler func(payload any) error type StartProxyPayload struct { NewProxyMsg *msg.NewProxy } type CloseProxyPayload struct { CloseProxyMsg *msg.CloseProxy }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/main.go
main.go
package main import ( "bytes" "fmt" "log" "os" "runtime" "runtime/debug" "github.com/docker/docker/client" "github.com/go-errors/errors" "github.com/integrii/flaggy" "github.com/jesseduffield/lazydocker/pkg/app" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/jesseduffield/yaml" "github.com/samber/lo" ) const DEFAULT_VERSION = "unversioned" var ( commit string version = DEFAULT_VERSION date string buildSource = "unknown" configFlag = false debuggingFlag = false composeFiles []string ) func main() { updateBuildInfo() info := fmt.Sprintf( "%s\nDate: %s\nBuildSource: %s\nCommit: %s\nOS: %s\nArch: %s", version, date, buildSource, commit, runtime.GOOS, runtime.GOARCH, ) flaggy.SetName("lazydocker") flaggy.SetDescription("The lazier way to manage everything docker") flaggy.DefaultParser.AdditionalHelpPrepend = "https://github.com/jesseduffield/lazydocker" flaggy.Bool(&configFlag, "c", "config", "Print the current default config") flaggy.Bool(&debuggingFlag, "d", "debug", "a boolean") flaggy.StringSlice(&composeFiles, "f", "file", "Specify alternate compose files") flaggy.SetVersion(info) flaggy.Parse() if configFlag { var buf bytes.Buffer encoder := yaml.NewEncoder(&buf) err := encoder.Encode(config.GetDefaultConfig()) if err != nil { log.Fatal(err.Error()) } fmt.Printf("%v\n", buf.String()) os.Exit(0) } projectDir, err := os.Getwd() if err != nil { log.Fatal(err.Error()) } appConfig, err := config.NewAppConfig("lazydocker", version, commit, date, buildSource, debuggingFlag, composeFiles, projectDir) if err != nil { log.Fatal(err.Error()) } app, err := app.NewApp(appConfig) if err == nil { err = app.Run() } app.Close() if err != nil { if errMessage, known := app.KnownError(err); known { log.Println(errMessage) os.Exit(0) } if client.IsErrConnectionFailed(err) { log.Println(app.Tr.ConnectionFailed) os.Exit(0) } newErr := errors.Wrap(err, 0) stackTrace := newErr.ErrorStack() app.Log.Error(stackTrace) log.Fatalf("%s\n\n%s", app.Tr.ErrorOccurred, stackTrace) } } func updateBuildInfo() { if version == DEFAULT_VERSION { if buildInfo, ok := debug.ReadBuildInfo(); ok { revision, ok := lo.Find(buildInfo.Settings, func(setting debug.BuildSetting) bool { return setting.Key == "vcs.revision" }) if ok { commit = revision.Value // if lazydocker was built from source we'll show the version as the // abbreviated commit hash version = utils.SafeTruncate(revision.Value, 7) } // if version hasn't been set we assume that neither has the date time, ok := lo.Find(buildInfo.Settings, func(setting debug.BuildSetting) bool { return setting.Key == "vcs.time" }) if ok { date = time.Value } } } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/scripts/translations/get_required_translations.go
scripts/translations/get_required_translations.go
package main import ( "fmt" "reflect" "github.com/jesseduffield/lazydocker/pkg/i18n" ) func main() { fmt.Println(getOutstandingTranslations()) } // adapted from https://github.com/a8m/reflect-examples#read-struct-tags func getOutstandingTranslations() string { output := "" for languageCode, translationSet := range i18n.GetTranslationSets() { output += languageCode + ":\n" v := reflect.ValueOf(translationSet) for i := 0; i < v.NumField(); i++ { value := v.Field(i).String() if value == "" { output += v.Type().Field(i).Name + "\n" } } output += "\n" } return output }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/scripts/cheatsheet/main.go
scripts/cheatsheet/main.go
package main import ( "fmt" "log" "os" "github.com/jesseduffield/lazydocker/pkg/cheatsheet" ) func main() { if len(os.Args) < 2 { log.Fatal("Please provide a command: one of 'generate', 'check'") } command := os.Args[1] switch command { case "generate": cheatsheet.Generate() fmt.Printf("\nGenerated cheatsheets in %s\n", cheatsheet.GetKeybindingsDir()) case "check": cheatsheet.Check() default: log.Fatal("\nUnknown command. Expected one of 'generate', 'check'") } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/tasks/tasks.go
pkg/tasks/tasks.go
package tasks import ( "context" "fmt" "time" "github.com/jesseduffield/lazydocker/pkg/i18n" "github.com/sasha-s/go-deadlock" "github.com/sirupsen/logrus" ) type TaskManager struct { currentTask *Task waitingMutex deadlock.Mutex taskIDMutex deadlock.Mutex Log *logrus.Entry Tr *i18n.TranslationSet newTaskId int } type Task struct { ctx context.Context cancel context.CancelFunc stopped bool stopMutex deadlock.Mutex notifyStopped chan struct{} Log *logrus.Entry f func(ctx context.Context) } type TaskFunc func(ctx context.Context) func NewTaskManager(log *logrus.Entry, translationSet *i18n.TranslationSet) *TaskManager { return &TaskManager{Log: log, Tr: translationSet} } // Close closes the task manager, killing whatever task may currently be running func (t *TaskManager) Close() { if t.currentTask == nil { return } c := make(chan struct{}, 1) go func() { t.currentTask.Stop() c <- struct{}{} }() select { case <-c: return case <-time.After(3 * time.Second): fmt.Println(t.Tr.CannotKillChildError) } } func (t *TaskManager) NewTask(f func(ctx context.Context)) error { go func() { t.taskIDMutex.Lock() t.newTaskId++ taskID := t.newTaskId t.taskIDMutex.Unlock() t.waitingMutex.Lock() defer t.waitingMutex.Unlock() t.taskIDMutex.Lock() if taskID < t.newTaskId { t.taskIDMutex.Unlock() return } t.taskIDMutex.Unlock() ctx, cancel := context.WithCancel(context.Background()) notifyStopped := make(chan struct{}) if t.currentTask != nil { t.Log.Info("asking task to stop") t.currentTask.Stop() t.Log.Info("task stopped") } t.currentTask = &Task{ ctx: ctx, cancel: cancel, notifyStopped: notifyStopped, Log: t.Log, f: f, } go func() { f(ctx) t.Log.Info("returned from function, closing notifyStopped") close(notifyStopped) }() }() return nil } func (t *Task) Stop() { t.stopMutex.Lock() defer t.stopMutex.Unlock() if t.stopped { return } t.cancel() t.Log.Info("closed stop channel, waiting for notifyStopped message") <-t.notifyStopped t.Log.Info("received notifystopped message") t.stopped = true } // NewTickerTask is a convenience function for making a new task that repeats some action once per e.g. second // the before function gets called after the lock is obtained, but before the ticker starts. // if you handle a message on the stop channel in f() you need to send a message on the notifyStopped channel because returning is not sufficient. Here, unlike in a regular task, simply returning means we're now going to wait till the next tick to run again. func (t *TaskManager) NewTickerTask(duration time.Duration, before func(ctx context.Context), f func(ctx context.Context, notifyStopped chan struct{})) error { notifyStopped := make(chan struct{}, 10) return t.NewTask(func(ctx context.Context) { if before != nil { before(ctx) } tickChan := time.NewTicker(duration) defer tickChan.Stop() // calling f first so that we're not waiting for the first tick f(ctx, notifyStopped) for { select { case <-notifyStopped: t.Log.Info("exiting ticker task due to notifyStopped channel") return case <-ctx.Done(): t.Log.Info("exiting ticker task due to stopped cahnnel") return case <-tickChan.C: t.Log.Info("running ticker task again") f(ctx, notifyStopped) } } }) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/app/app.go
pkg/app/app.go
package app import ( "io" "strings" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui" "github.com/jesseduffield/lazydocker/pkg/i18n" "github.com/jesseduffield/lazydocker/pkg/log" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/sirupsen/logrus" ) // App struct type App struct { closers []io.Closer Config *config.AppConfig Log *logrus.Entry OSCommand *commands.OSCommand DockerCommand *commands.DockerCommand Gui *gui.Gui Tr *i18n.TranslationSet ErrorChan chan error } // NewApp bootstrap a new application func NewApp(config *config.AppConfig) (*App, error) { app := &App{ closers: []io.Closer{}, Config: config, ErrorChan: make(chan error), } var err error app.Log = log.NewLogger(config, "23432119147a4367abf7c0de2aa99a2d") app.Tr, err = i18n.NewTranslationSetFromConfig(app.Log, config.UserConfig.Gui.Language) if err != nil { return app, err } app.OSCommand = commands.NewOSCommand(app.Log, config) // here is the place to make use of the docker-compose.yml file in the current directory app.DockerCommand, err = commands.NewDockerCommand(app.Log, app.OSCommand, app.Tr, app.Config, app.ErrorChan) if err != nil { return app, err } app.closers = append(app.closers, app.DockerCommand) app.Gui, err = gui.NewGui(app.Log, app.DockerCommand, app.OSCommand, app.Tr, config, app.ErrorChan) if err != nil { return app, err } return app, nil } func (app *App) Run() error { return app.Gui.Run() } func (app *App) Close() error { return utils.CloseMany(app.closers) } type errorMapping struct { originalError string newError string } // KnownError takes an error and tells us whether it's an error that we know about where we can print a nicely formatted version of it rather than panicking with a stack trace func (app *App) KnownError(err error) (string, bool) { errorMessage := err.Error() mappings := []errorMapping{ { originalError: "Got permission denied while trying to connect to the Docker daemon socket", newError: app.Tr.CannotAccessDockerSocketError, }, } for _, mapping := range mappings { if strings.Contains(errorMessage, mapping.originalError) { return mapping.newError, true } } return "", false }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/network.go
pkg/commands/network.go
package commands import ( "context" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" "github.com/sirupsen/logrus" ) // Network : A docker Network type Network struct { Name string Network network.Inspect Client *client.Client OSCommand *OSCommand Log *logrus.Entry DockerCommand LimitedDockerCommand } // RefreshNetworks gets the networks and stores them func (c *DockerCommand) RefreshNetworks() ([]*Network, error) { networks, err := c.Client.NetworkList(context.Background(), network.ListOptions{}) if err != nil { return nil, err } ownNetworks := make([]*Network, len(networks)) for i, nw := range networks { ownNetworks[i] = &Network{ Name: nw.Name, Network: nw, Client: c.Client, OSCommand: c.OSCommand, Log: c.Log, DockerCommand: c, } } return ownNetworks, nil } // PruneNetworks prunes networks func (c *DockerCommand) PruneNetworks() error { _, err := c.Client.NetworksPrune(context.Background(), filters.Args{}) return err } // Remove removes the network func (v *Network) Remove() error { return v.Client.NetworkRemove(context.Background(), v.Name) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/volume.go
pkg/commands/volume.go
package commands import ( "context" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" "github.com/sirupsen/logrus" ) // Volume : A docker Volume type Volume struct { Name string Volume *volume.Volume Client *client.Client OSCommand *OSCommand Log *logrus.Entry DockerCommand LimitedDockerCommand } // RefreshVolumes gets the volumes and stores them func (c *DockerCommand) RefreshVolumes() ([]*Volume, error) { result, err := c.Client.VolumeList(context.Background(), volume.ListOptions{}) if err != nil { return nil, err } volumes := result.Volumes ownVolumes := make([]*Volume, len(volumes)) for i, vol := range volumes { ownVolumes[i] = &Volume{ Name: vol.Name, Volume: vol, Client: c.Client, OSCommand: c.OSCommand, Log: c.Log, DockerCommand: c, } } return ownVolumes, nil } // PruneVolumes prunes volumes func (c *DockerCommand) PruneVolumes() error { _, err := c.Client.VolumesPrune(context.Background(), filters.Args{}) return err } // Remove removes the volume func (v *Volume) Remove(force bool) error { return v.Client.VolumeRemove(context.Background(), v.Name, force) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/dummies.go
pkg/commands/dummies.go
package commands import ( "io" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/i18n" "github.com/sirupsen/logrus" ) // This file exports dummy constructors for use by tests in other packages // NewDummyOSCommand creates a new dummy OSCommand for testing func NewDummyOSCommand() *OSCommand { return NewOSCommand(NewDummyLog(), NewDummyAppConfig()) } // NewDummyAppConfig creates a new dummy AppConfig for testing func NewDummyAppConfig() *config.AppConfig { appConfig := &config.AppConfig{ Name: "lazydocker", Version: "unversioned", Commit: "", BuildDate: "", Debug: false, BuildSource: "", } return appConfig } // NewDummyLog creates a new dummy Log for testing func NewDummyLog() *logrus.Entry { log := logrus.New() log.Out = io.Discard return log.WithField("test", "test") } // NewDummyDockerCommand creates a new dummy DockerCommand for testing func NewDummyDockerCommand() *DockerCommand { return NewDummyDockerCommandWithOSCommand(NewDummyOSCommand()) } // NewDummyDockerCommandWithOSCommand creates a new dummy DockerCommand for testing func NewDummyDockerCommandWithOSCommand(osCommand *OSCommand) *DockerCommand { newAppConfig := NewDummyAppConfig() return &DockerCommand{ Log: NewDummyLog(), OSCommand: osCommand, Tr: i18n.NewTranslationSet(NewDummyLog(), newAppConfig.UserConfig.Gui.Language), Config: newAppConfig, } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/container.go
pkg/commands/container.go
package commands import ( "context" "fmt" "os/exec" "strings" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" "github.com/go-errors/errors" "github.com/jesseduffield/lazydocker/pkg/i18n" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/sasha-s/go-deadlock" "github.com/sirupsen/logrus" "golang.org/x/xerrors" ) // Container : A docker Container type Container struct { Name string ServiceName string ContainerNumber string // might make this an int in the future if need be // OneOff tells us if the container is just a job container or is actually bound to the service OneOff bool ProjectName string ID string Container container.Summary Client *client.Client OSCommand *OSCommand Log *logrus.Entry StatHistory []*RecordedStats Details container.InspectResponse MonitoringStats bool DockerCommand LimitedDockerCommand Tr *i18n.TranslationSet StatsMutex deadlock.Mutex } // Remove removes the container func (c *Container) Remove(options container.RemoveOptions) error { c.Log.Warn(fmt.Sprintf("removing container %s", c.Name)) if err := c.Client.ContainerRemove(context.Background(), c.ID, options); err != nil { if strings.Contains(err.Error(), "Stop the container before attempting removal or force remove") { return ComplexError{ Code: MustStopContainer, Message: err.Error(), frame: xerrors.Caller(1), } } return err } return nil } // Stop stops the container func (c *Container) Stop() error { c.Log.Warn(fmt.Sprintf("stopping container %s", c.Name)) return c.Client.ContainerStop(context.Background(), c.ID, container.StopOptions{}) } // Pause pauses the container func (c *Container) Pause() error { c.Log.Warn(fmt.Sprintf("pausing container %s", c.Name)) return c.Client.ContainerPause(context.Background(), c.ID) } // Unpause unpauses the container func (c *Container) Unpause() error { c.Log.Warn(fmt.Sprintf("unpausing container %s", c.Name)) return c.Client.ContainerUnpause(context.Background(), c.ID) } // Restart restarts the container func (c *Container) Restart() error { c.Log.Warn(fmt.Sprintf("restarting container %s", c.Name)) return c.Client.ContainerRestart(context.Background(), c.ID, container.StopOptions{}) } // Attach attaches the container func (c *Container) Attach() (*exec.Cmd, error) { if !c.DetailsLoaded() { return nil, errors.New(c.Tr.WaitingForContainerInfo) } // verify that we can in fact attach to this container if !c.Details.Config.OpenStdin { return nil, errors.New(c.Tr.UnattachableContainerError) } if c.Container.State == "exited" { return nil, errors.New(c.Tr.CannotAttachStoppedContainerError) } c.Log.Warn(fmt.Sprintf("attaching to container %s", c.Name)) // TODO: use SDK cmd := c.OSCommand.NewCmd("docker", "attach", "--sig-proxy=false", c.ID) return cmd, nil } // Top returns process information func (c *Container) Top(ctx context.Context) (container.TopResponse, error) { detail, err := c.Inspect() if err != nil { return container.TopResponse{}, err } // check container status if !detail.State.Running { return container.TopResponse{}, errors.New("container is not running") } return c.Client.ContainerTop(ctx, c.ID, []string{}) } // PruneContainers prunes containers func (c *DockerCommand) PruneContainers() error { _, err := c.Client.ContainersPrune(context.Background(), filters.Args{}) return err } // Inspect returns details about the container func (c *Container) Inspect() (container.InspectResponse, error) { return c.Client.ContainerInspect(context.Background(), c.ID) } // RenderTop returns details about the container func (c *Container) RenderTop(ctx context.Context) (string, error) { result, err := c.Top(ctx) if err != nil { return "", err } return utils.RenderTable(append([][]string{result.Titles}, result.Processes...)) } // DetailsLoaded tells us whether we have yet loaded the details for a container. // Sometimes it takes some time for a container to have its details loaded // after it starts. func (c *Container) DetailsLoaded() bool { return c.Details.ContainerJSONBase != nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/container_stats_test.go
pkg/commands/container_stats_test.go
package commands import ( "testing" "github.com/stretchr/testify/assert" ) func TestCalculateContainerCPUPercentage(t *testing.T) { container := &ContainerStats{} container.CPUStats.CPUUsage.TotalUsage = 10 container.CPUStats.SystemCPUUsage = 10 container.PrecpuStats.CPUUsage.TotalUsage = 5 container.PrecpuStats.SystemCPUUsage = 2 assert.EqualValues(t, 62.5, container.CalculateContainerCPUPercentage()) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/service.go
pkg/commands/service.go
package commands import ( "context" "os/exec" "github.com/docker/docker/api/types/container" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/sirupsen/logrus" ) // Service : A docker Service type Service struct { Name string ID string OSCommand *OSCommand Log *logrus.Entry Container *Container DockerCommand LimitedDockerCommand } // Remove removes the service's containers func (s *Service) Remove(options container.RemoveOptions) error { return s.Container.Remove(options) } // Stop stops the service's containers func (s *Service) Stop() error { return s.runCommand(s.OSCommand.Config.UserConfig.CommandTemplates.StopService) } // Up up's the service func (s *Service) Up() error { return s.runCommand(s.OSCommand.Config.UserConfig.CommandTemplates.UpService) } // Restart restarts the service func (s *Service) Restart() error { return s.runCommand(s.OSCommand.Config.UserConfig.CommandTemplates.RestartService) } // Start starts the service func (s *Service) Start() error { return s.runCommand(s.OSCommand.Config.UserConfig.CommandTemplates.StartService) } func (s *Service) runCommand(templateCmdStr string) error { command := utils.ApplyTemplate( templateCmdStr, s.DockerCommand.NewCommandObject(CommandObject{Service: s}), ) return s.OSCommand.RunCommand(command) } // Attach attaches to the service func (s *Service) Attach() (*exec.Cmd, error) { return s.Container.Attach() } // ViewLogs attaches to a subprocess viewing the service's logs func (s *Service) ViewLogs() (*exec.Cmd, error) { templateString := s.OSCommand.Config.UserConfig.CommandTemplates.ViewServiceLogs command := utils.ApplyTemplate( templateString, s.DockerCommand.NewCommandObject(CommandObject{Service: s}), ) cmd := s.OSCommand.ExecutableFromString(command) s.OSCommand.PrepareForChildren(cmd) return cmd, nil } // RenderTop renders the process list of the service func (s *Service) RenderTop(ctx context.Context) (string, error) { templateString := s.OSCommand.Config.UserConfig.CommandTemplates.ServiceTop command := utils.ApplyTemplate( templateString, s.DockerCommand.NewCommandObject(CommandObject{Service: s}), ) return s.OSCommand.RunCommandWithOutputContext(ctx, command) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/docker_host_windows.go
pkg/commands/docker_host_windows.go
package commands const ( defaultDockerHost = "npipe:////./pipe/docker_engine" )
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/errors.go
pkg/commands/errors.go
package commands import ( "fmt" "github.com/go-errors/errors" "golang.org/x/xerrors" ) const ( // MustStopContainer tells us that we must stop the container before removing it MustStopContainer = iota ) // WrapError wraps an error for the sake of showing a stack trace at the top level // the go-errors package, for some reason, does not return nil when you try to wrap // a non-error, so we're just doing it here func WrapError(err error) error { if err == nil { return err } return errors.Wrap(err, 0) } // ComplexError an error which carries a code so that calling code has an easier job to do // adapted from https://medium.com/yakka/better-go-error-handling-with-xerrors-1987650e0c79 type ComplexError struct { Message string Code int frame xerrors.Frame } // FormatError is a function func (ce ComplexError) FormatError(p xerrors.Printer) error { p.Printf("%d %s", ce.Code, ce.Message) ce.frame.Format(p) return nil } // Format is a function func (ce ComplexError) Format(f fmt.State, c rune) { xerrors.FormatError(ce, f, c) } func (ce ComplexError) Error() string { return fmt.Sprint(ce) } // HasErrorCode is a function func HasErrorCode(err error, code int) bool { var originalErr ComplexError if xerrors.As(err, &originalErr) { return originalErr.Code == MustStopContainer } return false }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/docker_host_unix.go
pkg/commands/docker_host_unix.go
//go:build !windows package commands const ( defaultDockerHost = "unix:///var/run/docker.sock" )
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/image.go
pkg/commands/image.go
package commands import ( "context" "strings" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "github.com/docker/docker/client" "github.com/fatih/color" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" "github.com/sirupsen/logrus" ) // Image : A docker Image type Image struct { Name string Tag string ID string Image image.Summary Client *client.Client OSCommand *OSCommand Log *logrus.Entry DockerCommand LimitedDockerCommand } // Remove removes the image func (i *Image) Remove(options image.RemoveOptions) error { if _, err := i.Client.ImageRemove(context.Background(), i.ID, options); err != nil { return err } return nil } func getHistoryResponseItemDisplayStrings(layer image.HistoryResponseItem) []string { tag := "" if len(layer.Tags) > 0 { tag = layer.Tags[0] } id := strings.TrimPrefix(layer.ID, "sha256:") if len(id) > 10 { id = id[0:10] } idColor := color.FgWhite if id == "<missing>" { idColor = color.FgBlue } dockerFileCommandPrefix := "/bin/sh -c #(nop) " createdBy := layer.CreatedBy if strings.Contains(layer.CreatedBy, dockerFileCommandPrefix) { createdBy = strings.Trim(strings.TrimPrefix(layer.CreatedBy, dockerFileCommandPrefix), " ") split := strings.Split(createdBy, " ") createdBy = utils.ColoredString(split[0], color.FgYellow) + " " + strings.Join(split[1:], " ") } createdBy = strings.Replace(createdBy, "\t", " ", -1) size := utils.FormatBinaryBytes(int(layer.Size)) sizeColor := color.FgWhite if size == "0B" { sizeColor = color.FgBlue } return []string{ utils.ColoredString(id, idColor), utils.ColoredString(tag, color.FgGreen), utils.ColoredString(size, sizeColor), createdBy, } } // RenderHistory renders the history of the image func (i *Image) RenderHistory() (string, error) { history, err := i.Client.ImageHistory(context.Background(), i.ID) if err != nil { return "", err } tableBody := lo.Map(history, func(layer image.HistoryResponseItem, _ int) []string { return getHistoryResponseItemDisplayStrings(layer) }) headers := [][]string{{"ID", "TAG", "SIZE", "COMMAND"}} table := append(headers, tableBody...) return utils.RenderTable(table) } // RefreshImages returns a slice of docker images func (c *DockerCommand) RefreshImages() ([]*Image, error) { images, err := c.Client.ImageList(context.Background(), image.ListOptions{}) if err != nil { return nil, err } ownImages := make([]*Image, len(images)) for i, img := range images { firstTag := "" tags := img.RepoTags if len(tags) > 0 { firstTag = tags[0] } nameParts := strings.Split(firstTag, ":") tag := "" name := "none" if len(nameParts) > 1 { tag = nameParts[len(nameParts)-1] name = strings.Join(nameParts[:len(nameParts)-1], ":") for prefix, replacement := range c.Config.UserConfig.Replacements.ImageNamePrefixes { if strings.HasPrefix(name, prefix) { name = strings.Replace(name, prefix, replacement, 1) break } } } ownImages[i] = &Image{ ID: img.ID, Name: name, Tag: tag, Image: img, Client: c.Client, OSCommand: c.OSCommand, Log: c.Log, DockerCommand: c, } } return ownImages, nil } // PruneImages prunes images func (c *DockerCommand) PruneImages() error { _, err := c.Client.ImagesPrune(context.Background(), filters.Args{}) return err }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/docker.go
pkg/commands/docker.go
package commands import ( "bufio" "context" "encoding/json" "fmt" "io" ogLog "log" "os" "os/exec" "strings" "sync" "time" cliconfig "github.com/docker/cli/cli/config" ddocker "github.com/docker/cli/cli/context/docker" ctxstore "github.com/docker/cli/cli/context/store" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/imdario/mergo" "github.com/jesseduffield/lazydocker/pkg/commands/ssh" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/i18n" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/sasha-s/go-deadlock" "github.com/sirupsen/logrus" ) const ( dockerHostEnvKey = "DOCKER_HOST" ) // DockerCommand is our main docker interface type DockerCommand struct { Log *logrus.Entry OSCommand *OSCommand Tr *i18n.TranslationSet Config *config.AppConfig Client *client.Client InDockerComposeProject bool ErrorChan chan error ContainerMutex deadlock.Mutex ServiceMutex deadlock.Mutex Closers []io.Closer } var _ io.Closer = &DockerCommand{} // LimitedDockerCommand is a stripped-down DockerCommand with just the methods the container/service/image might need type LimitedDockerCommand interface { NewCommandObject(CommandObject) CommandObject } // CommandObject is what we pass to our template resolvers when we are running a custom command. We do not guarantee that all fields will be populated: just the ones that make sense for the current context type CommandObject struct { DockerCompose string Service *Service Container *Container Image *Image Volume *Volume Network *Network } // NewCommandObject takes a command object and returns a default command object with the passed command object merged in func (c *DockerCommand) NewCommandObject(obj CommandObject) CommandObject { defaultObj := CommandObject{DockerCompose: c.Config.UserConfig.CommandTemplates.DockerCompose} _ = mergo.Merge(&defaultObj, obj) return defaultObj } // NewDockerCommand it runs docker commands func NewDockerCommand(log *logrus.Entry, osCommand *OSCommand, tr *i18n.TranslationSet, config *config.AppConfig, errorChan chan error) (*DockerCommand, error) { dockerHost, err := determineDockerHost() if err != nil { ogLog.Printf("> could not determine host %v", err) } // NOTE: Inject the determined docker host to the environment. This allows the // `SSHHandler.HandleSSHDockerHost()` to create a local unix socket tunneled // over SSH to the specified ssh host. if strings.HasPrefix(dockerHost, "ssh://") { os.Setenv(dockerHostEnvKey, dockerHost) } tunnelCloser, err := ssh.NewSSHHandler(osCommand).HandleSSHDockerHost() if err != nil { ogLog.Fatal(err) } // Retrieve the docker host from the environment which could have been set by // the `SSHHandler.HandleSSHDockerHost()` and override `dockerHost`. dockerHostFromEnv := os.Getenv(dockerHostEnvKey) if dockerHostFromEnv != "" { dockerHost = dockerHostFromEnv } cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation(), client.WithHost(dockerHost)) if err != nil { ogLog.Fatal(err) } dockerCommand := &DockerCommand{ Log: log, OSCommand: osCommand, Tr: tr, Config: config, Client: cli, ErrorChan: errorChan, InDockerComposeProject: true, Closers: []io.Closer{tunnelCloser}, } dockerCommand.setDockerComposeCommand(config) err = osCommand.RunCommand( utils.ApplyTemplate( config.UserConfig.CommandTemplates.CheckDockerComposeConfig, dockerCommand.NewCommandObject(CommandObject{}), ), ) if err != nil { dockerCommand.InDockerComposeProject = false log.Warn(err.Error()) } return dockerCommand, nil } func (c *DockerCommand) setDockerComposeCommand(config *config.AppConfig) { if config.UserConfig.CommandTemplates.DockerCompose != "docker compose" { return } // it's possible that a user is still using docker-compose, so we'll check if 'docker comopose' is available, and if not, we'll fall back to 'docker-compose' err := c.OSCommand.RunCommand("docker compose version") if err != nil { config.UserConfig.CommandTemplates.DockerCompose = "docker-compose" } } func (c *DockerCommand) Close() error { return utils.CloseMany(c.Closers) } func (c *DockerCommand) CreateClientStatMonitor(container *Container) { container.MonitoringStats = true stream, err := c.Client.ContainerStats(context.Background(), container.ID, true) if err != nil { // not creating error panel because if we've disconnected from docker we'll // have already created an error panel c.Log.Error(err) container.MonitoringStats = false return } defer stream.Body.Close() scanner := bufio.NewScanner(stream.Body) for scanner.Scan() { data := scanner.Bytes() var stats ContainerStats _ = json.Unmarshal(data, &stats) recordedStats := &RecordedStats{ ClientStats: stats, DerivedStats: DerivedStats{ CPUPercentage: stats.CalculateContainerCPUPercentage(), MemoryPercentage: stats.CalculateContainerMemoryUsage(), }, RecordedAt: time.Now(), } container.appendStats(recordedStats, c.Config.UserConfig.Stats.MaxDuration) } container.MonitoringStats = false } func (c *DockerCommand) RefreshContainersAndServices(currentServices []*Service, currentContainers []*Container) ([]*Container, []*Service, error) { c.ServiceMutex.Lock() defer c.ServiceMutex.Unlock() containers, err := c.GetContainers(currentContainers) if err != nil { return nil, nil, err } var services []*Service // we only need to get these services once because they won't change in the runtime of the program if currentServices != nil { services = currentServices } else { services, err = c.GetServices() if err != nil { return nil, nil, err } } c.assignContainersToServices(containers, services) return containers, services, nil } func (c *DockerCommand) assignContainersToServices(containers []*Container, services []*Service) { L: for _, service := range services { for _, ctr := range containers { if !ctr.OneOff && ctr.ServiceName == service.Name { service.Container = ctr continue L } } service.Container = nil } } // GetContainers gets the docker containers func (c *DockerCommand) GetContainers(existingContainers []*Container) ([]*Container, error) { c.ContainerMutex.Lock() defer c.ContainerMutex.Unlock() containers, err := c.Client.ContainerList(context.Background(), container.ListOptions{All: true}) if err != nil { return nil, err } ownContainers := make([]*Container, len(containers)) for i, ctr := range containers { var newContainer *Container // check if we already have data stored against the container for _, existingContainer := range existingContainers { if existingContainer.ID == ctr.ID { newContainer = existingContainer break } } // initialise the container if it's completely new if newContainer == nil { newContainer = &Container{ ID: ctr.ID, Client: c.Client, OSCommand: c.OSCommand, Log: c.Log, DockerCommand: c, Tr: c.Tr, } } newContainer.Container = ctr // if the container is made with a name label we will use that if name, ok := ctr.Labels["name"]; ok { newContainer.Name = name } else { if len(ctr.Names) > 0 { newContainer.Name = strings.TrimLeft(ctr.Names[0], "/") } else { newContainer.Name = ctr.ID } } newContainer.ServiceName = ctr.Labels["com.docker.compose.service"] newContainer.ProjectName = ctr.Labels["com.docker.compose.project"] newContainer.ContainerNumber = ctr.Labels["com.docker.compose.container"] newContainer.OneOff = ctr.Labels["com.docker.compose.oneoff"] == "True" ownContainers[i] = newContainer } c.SetContainerDetails(ownContainers) return ownContainers, nil } // GetServices gets services func (c *DockerCommand) GetServices() ([]*Service, error) { if !c.InDockerComposeProject { return nil, nil } composeCommand := c.Config.UserConfig.CommandTemplates.DockerCompose output, err := c.OSCommand.RunCommandWithOutput(fmt.Sprintf("%s config --services", composeCommand)) if err != nil { return nil, err } // output looks like: // service1 // service2 lines := utils.SplitLines(output) services := make([]*Service, len(lines)) for i, str := range lines { services[i] = &Service{ Name: str, ID: str, OSCommand: c.OSCommand, Log: c.Log, DockerCommand: c, } } return services, nil } func (c *DockerCommand) RefreshContainerDetails(containers []*Container) error { c.ContainerMutex.Lock() defer c.ContainerMutex.Unlock() c.SetContainerDetails(containers) return nil } // Attaches the details returned from docker inspect to each of the containers // this contains a bit more info than what you get from the go-docker client func (c *DockerCommand) SetContainerDetails(containers []*Container) { wg := sync.WaitGroup{} for _, ctr := range containers { ctr := ctr wg.Add(1) go func() { details, err := c.Client.ContainerInspect(context.Background(), ctr.ID) if err != nil { c.Log.Error(err) } else { ctr.Details = details } wg.Done() }() } wg.Wait() } // ViewAllLogs attaches to a subprocess viewing all the logs from docker-compose func (c *DockerCommand) ViewAllLogs() (*exec.Cmd, error) { cmd := c.OSCommand.ExecutableFromString( utils.ApplyTemplate( c.OSCommand.Config.UserConfig.CommandTemplates.ViewAllLogs, c.NewCommandObject(CommandObject{}), ), ) c.OSCommand.PrepareForChildren(cmd) return cmd, nil } // DockerComposeConfig returns the result of 'docker-compose config' func (c *DockerCommand) DockerComposeConfig() string { output, err := c.OSCommand.RunCommandWithOutput( utils.ApplyTemplate( c.OSCommand.Config.UserConfig.CommandTemplates.DockerComposeConfig, c.NewCommandObject(CommandObject{}), ), ) if err != nil { output = err.Error() } return output } // determineDockerHost tries to the determine the docker host that we should connect to // in the following order of decreasing precedence: // - value of "DOCKER_HOST" environment variable // - host retrieved from the current context (specified via DOCKER_CONTEXT) // - "default docker host" for the host operating system, otherwise func determineDockerHost() (string, error) { // If the docker host is explicitly set via the "DOCKER_HOST" environment variable, // then its a no-brainer :shrug: if os.Getenv("DOCKER_HOST") != "" { return os.Getenv("DOCKER_HOST"), nil } currentContext := os.Getenv("DOCKER_CONTEXT") if currentContext == "" { cf, err := cliconfig.Load(cliconfig.Dir()) if err != nil { return "", err } currentContext = cf.CurrentContext } // On some systems (windows) `default` is stored in the docker config as the currentContext. if currentContext == "" || currentContext == "default" { // If a docker context is neither specified via the "DOCKER_CONTEXT" environment variable nor via the // $HOME/.docker/config file, then we fall back to connecting to the "default docker host" meant for // the host operating system. return defaultDockerHost, nil } storeConfig := ctxstore.NewConfig( func() interface{} { return &ddocker.EndpointMeta{} }, ctxstore.EndpointTypeGetter(ddocker.DockerEndpoint, func() interface{} { return &ddocker.EndpointMeta{} }), ) st := ctxstore.New(cliconfig.ContextStoreDir(), storeConfig) md, err := st.GetMetadata(currentContext) if err != nil { return "", err } dockerEP, ok := md.Endpoints[ddocker.DockerEndpoint] if !ok { return "", err } dockerEPMeta, ok := dockerEP.(ddocker.EndpointMeta) if !ok { return "", fmt.Errorf("expected docker.EndpointMeta, got %T", dockerEP) } if dockerEPMeta.Host != "" { return dockerEPMeta.Host, nil } // We might end up here, if the context was created with the `host` set to an empty value (i.e. ''). // For example: // ```sh // docker context create foo --docker "host=" // ``` // In such scenario, we mimic the `docker` cli and try to connect to the "default docker host". return defaultDockerHost, nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/container_stats.go
pkg/commands/container_stats.go
package commands import ( "math" "time" ) // RecordedStats contains both the container stats we've received from docker, and our own derived stats from those container stats. When configuring a graph, you're basically specifying the path of a value in this struct type RecordedStats struct { ClientStats ContainerStats DerivedStats DerivedStats RecordedAt time.Time } // DerivedStats contains some useful stats that we've calculated based on the raw container stats that we got back from docker type DerivedStats struct { CPUPercentage float64 MemoryPercentage float64 } // ContainerStats autogenerated at https://mholt.github.io/json-to-go/ type ContainerStats struct { Read time.Time `json:"read"` Preread time.Time `json:"preread"` PidsStats struct { Current int `json:"current"` } `json:"pids_stats"` BlkioStats struct { IoServiceBytesRecursive []struct { Major int `json:"major"` Minor int `json:"minor"` Op string `json:"op"` Value int `json:"value"` } `json:"io_service_bytes_recursive"` IoServicedRecursive []struct { Major int `json:"major"` Minor int `json:"minor"` Op string `json:"op"` Value int `json:"value"` } `json:"io_serviced_recursive"` IoQueueRecursive []interface{} `json:"io_queue_recursive"` IoServiceTimeRecursive []interface{} `json:"io_service_time_recursive"` IoWaitTimeRecursive []interface{} `json:"io_wait_time_recursive"` IoMergedRecursive []interface{} `json:"io_merged_recursive"` IoTimeRecursive []interface{} `json:"io_time_recursive"` SectorsRecursive []interface{} `json:"sectors_recursive"` } `json:"blkio_stats"` NumProcs int `json:"num_procs"` StorageStats struct{} `json:"storage_stats"` CPUStats struct { CPUUsage struct { TotalUsage int64 `json:"total_usage"` PercpuUsage []int64 `json:"percpu_usage"` UsageInKernelmode int64 `json:"usage_in_kernelmode"` UsageInUsermode int64 `json:"usage_in_usermode"` } `json:"cpu_usage"` SystemCPUUsage int64 `json:"system_cpu_usage"` OnlineCpus int `json:"online_cpus"` ThrottlingData struct { Periods int `json:"periods"` ThrottledPeriods int `json:"throttled_periods"` ThrottledTime int `json:"throttled_time"` } `json:"throttling_data"` } `json:"cpu_stats"` PrecpuStats struct { CPUUsage struct { TotalUsage int64 `json:"total_usage"` PercpuUsage []int64 `json:"percpu_usage"` UsageInKernelmode int64 `json:"usage_in_kernelmode"` UsageInUsermode int64 `json:"usage_in_usermode"` } `json:"cpu_usage"` SystemCPUUsage int64 `json:"system_cpu_usage"` OnlineCpus int `json:"online_cpus"` ThrottlingData struct { Periods int `json:"periods"` ThrottledPeriods int `json:"throttled_periods"` ThrottledTime int `json:"throttled_time"` } `json:"throttling_data"` } `json:"precpu_stats"` MemoryStats struct { Usage int `json:"usage"` MaxUsage int `json:"max_usage"` Stats struct { ActiveAnon int `json:"active_anon"` ActiveFile int `json:"active_file"` Cache int `json:"cache"` Dirty int `json:"dirty"` HierarchicalMemoryLimit int64 `json:"hierarchical_memory_limit"` HierarchicalMemswLimit int64 `json:"hierarchical_memsw_limit"` InactiveAnon int `json:"inactive_anon"` InactiveFile int `json:"inactive_file"` MappedFile int `json:"mapped_file"` Pgfault int `json:"pgfault"` Pgmajfault int `json:"pgmajfault"` Pgpgin int `json:"pgpgin"` Pgpgout int `json:"pgpgout"` Rss int `json:"rss"` RssHuge int `json:"rss_huge"` TotalActiveAnon int `json:"total_active_anon"` TotalActiveFile int `json:"total_active_file"` TotalCache int `json:"total_cache"` TotalDirty int `json:"total_dirty"` TotalInactiveAnon int `json:"total_inactive_anon"` TotalInactiveFile int `json:"total_inactive_file"` TotalMappedFile int `json:"total_mapped_file"` TotalPgfault int `json:"total_pgfault"` TotalPgmajfault int `json:"total_pgmajfault"` TotalPgpgin int `json:"total_pgpgin"` TotalPgpgout int `json:"total_pgpgout"` TotalRss int `json:"total_rss"` TotalRssHuge int `json:"total_rss_huge"` TotalUnevictable int `json:"total_unevictable"` TotalWriteback int `json:"total_writeback"` Unevictable int `json:"unevictable"` Writeback int `json:"writeback"` } `json:"stats"` Limit int64 `json:"limit"` } `json:"memory_stats"` Name string `json:"name"` ID string `json:"id"` Networks struct { Eth0 struct { RxBytes int `json:"rx_bytes"` RxPackets int `json:"rx_packets"` RxErrors int `json:"rx_errors"` RxDropped int `json:"rx_dropped"` TxBytes int `json:"tx_bytes"` TxPackets int `json:"tx_packets"` TxErrors int `json:"tx_errors"` TxDropped int `json:"tx_dropped"` } `json:"eth0"` } `json:"networks"` } // CalculateContainerCPUPercentage calculates the cpu usage of the container as a percent of total CPU usage // to calculate CPU usage, we take the increase in CPU time from the container since the last poll, divide that by the total increase in CPU time since the last poll, times by the number of cores, and times by 100 to get a percentage // I'm not entirely sure why we need to multiply by the number of cores, but the numbers work func (s *ContainerStats) CalculateContainerCPUPercentage() float64 { cpuUsageDelta := s.CPUStats.CPUUsage.TotalUsage - s.PrecpuStats.CPUUsage.TotalUsage cpuTotalUsageDelta := s.CPUStats.SystemCPUUsage - s.PrecpuStats.SystemCPUUsage value := float64(cpuUsageDelta*100) / float64(cpuTotalUsageDelta) if math.IsNaN(value) { return 0 } return value } // CalculateContainerMemoryUsage calculates the memory usage of the container as a percent of total available memory func (s *ContainerStats) CalculateContainerMemoryUsage() float64 { value := float64(s.MemoryStats.Usage*100) / float64(s.MemoryStats.Limit) if math.IsNaN(value) { return 0 } return value } func (c *Container) appendStats(stats *RecordedStats, maxDuration time.Duration) { c.StatsMutex.Lock() defer c.StatsMutex.Unlock() c.StatHistory = append(c.StatHistory, stats) c.eraseOldHistory(maxDuration) } // eraseOldHistory removes any history before the user-specified max duration func (c *Container) eraseOldHistory(maxDuration time.Duration) { if maxDuration == 0 { return } for i, stat := range c.StatHistory { if time.Since(stat.RecordedAt) < maxDuration { c.StatHistory = c.StatHistory[i:] return } } } func (c *Container) GetLastStats() (*RecordedStats, bool) { c.StatsMutex.Lock() defer c.StatsMutex.Unlock() history := c.StatHistory if len(history) == 0 { return nil, false } return history[len(history)-1], true }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/os_test.go
pkg/commands/os_test.go
package commands import ( "fmt" "os" "os/exec" "testing" "github.com/stretchr/testify/assert" ) // TestOSCommandRunCommandWithOutput is a function. func TestOSCommandRunCommandWithOutput(t *testing.T) { type scenario struct { command string test func(string, error) } scenarios := []scenario{ { "echo -n '123'", func(output string, err error) { assert.NoError(t, err) assert.EqualValues(t, "123", output) }, }, { "rmdir unexisting-folder", func(output string, err error) { assert.Regexp(t, "rmdir.*unexisting-folder.*", err.Error()) }, }, } for _, s := range scenarios { s.test(NewDummyOSCommand().RunCommandWithOutput(s.command)) } } // TestOSCommandRunCommand is a function. func TestOSCommandRunCommand(t *testing.T) { type scenario struct { command string test func(error) } scenarios := []scenario{ { "rmdir unexisting-folder", func(err error) { assert.Regexp(t, "rmdir.*unexisting-folder.*", err.Error()) }, }, } for _, s := range scenarios { s.test(NewDummyOSCommand().RunCommand(s.command)) } } // TestOSCommandEditFile is a function. func TestOSCommandEditFile(t *testing.T) { type scenario struct { filename string command func(string, ...string) *exec.Cmd getenv func(string) string test func(*exec.Cmd, error) } scenarios := []scenario{ { "test", func(name string, arg ...string) *exec.Cmd { return exec.Command("exit", "1") }, func(env string) string { return "" }, func(cmd *exec.Cmd, err error) { assert.EqualError(t, err, "No editor defined in $VISUAL or $EDITOR") }, }, { "test", func(name string, arg ...string) *exec.Cmd { if name == "which" { return exec.Command("exit", "1") } assert.EqualValues(t, "nano", name) return exec.Command("exit", "0") }, func(env string) string { if env == "VISUAL" { return "nano" } return "" }, func(cmd *exec.Cmd, err error) { assert.NoError(t, err) }, }, { "test", func(name string, arg ...string) *exec.Cmd { if name == "which" { return exec.Command("exit", "1") } assert.EqualValues(t, "emacs", name) return exec.Command("exit", "0") }, func(env string) string { if env == "EDITOR" { return "emacs" } return "" }, func(cmd *exec.Cmd, err error) { assert.NoError(t, err) }, }, { "test", func(name string, arg ...string) *exec.Cmd { if name == "which" { return exec.Command("echo") } assert.EqualValues(t, "vi", name) return exec.Command("exit", "0") }, func(env string) string { return "" }, func(cmd *exec.Cmd, err error) { assert.NoError(t, err) }, }, } for _, s := range scenarios { OSCmd := NewDummyOSCommand() OSCmd.command = s.command OSCmd.getenv = s.getenv s.test(OSCmd.EditFile(s.filename)) } } func TestOSCommandQuote(t *testing.T) { osCommand := NewDummyOSCommand() osCommand.Platform.os = "linux" actual := osCommand.Quote("hello `test`") expected := "\"hello \\`test\\`\"" assert.EqualValues(t, expected, actual) } // TestOSCommandQuoteSingleQuote tests the quote function with ' quotes explicitly for Linux func TestOSCommandQuoteSingleQuote(t *testing.T) { osCommand := NewDummyOSCommand() osCommand.Platform.os = "linux" actual := osCommand.Quote("hello 'test'") expected := `"hello 'test'"` assert.EqualValues(t, expected, actual) } // TestOSCommandQuoteDoubleQuote tests the quote function with " quotes explicitly for Linux func TestOSCommandQuoteDoubleQuote(t *testing.T) { osCommand := NewDummyOSCommand() osCommand.Platform.os = "linux" actual := osCommand.Quote(`hello "test"`) expected := `"hello \"test\""` assert.EqualValues(t, expected, actual) } // TestOSCommandQuoteWindows tests the quote function for Windows func TestOSCommandQuoteWindows(t *testing.T) { osCommand := NewDummyOSCommand() osCommand.Platform.os = "windows" actual := osCommand.Quote(`hello "test" 'test2'`) expected := `\"hello "'"'"test"'"'" 'test2'\"` assert.EqualValues(t, expected, actual) } // TestOSCommandUnquote is a function. func TestOSCommandUnquote(t *testing.T) { osCommand := NewDummyOSCommand() actual := osCommand.Unquote(`hello "test"`) expected := "hello test" assert.EqualValues(t, expected, actual) } // TestOSCommandFileType is a function. func TestOSCommandFileType(t *testing.T) { type scenario struct { path string setup func() test func(string) } scenarios := []scenario{ { "testFile", func() { if _, err := os.Create("testFile"); err != nil { panic(err) } }, func(output string) { assert.EqualValues(t, "file", output) }, }, { "file with spaces", func() { if _, err := os.Create("file with spaces"); err != nil { panic(err) } }, func(output string) { assert.EqualValues(t, "file", output) }, }, { "testDirectory", func() { if err := os.Mkdir("testDirectory", 0o644); err != nil { panic(err) } }, func(output string) { assert.EqualValues(t, "directory", output) }, }, { "nonExistant", func() {}, func(output string) { assert.EqualValues(t, "other", output) }, }, } for _, s := range scenarios { s.setup() s.test(NewDummyOSCommand().FileType(s.path)) _ = os.RemoveAll(s.path) } } func TestOSCommandCreateTempFile(t *testing.T) { type scenario struct { testName string filename string content string test func(string, error) } scenarios := []scenario{ { "valid case", "filename", "content", func(path string, err error) { assert.NoError(t, err) content, err := os.ReadFile(path) assert.NoError(t, err) assert.Equal(t, "content", string(content)) }, }, } for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { s.test(NewDummyOSCommand().CreateTempFile(s.filename, s.content)) }) } } func TestOSCommandExecutableFromStringWithShellLinux(t *testing.T) { osCommand := NewDummyOSCommand() osCommand.Platform.os = "linux" tests := []struct { name string commandStr string want string }{ { "success", "pwd", fmt.Sprintf("%v %v %v", osCommand.Platform.shell, osCommand.Platform.shellArg, "\"pwd\""), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := osCommand.NewCommandStringWithShell(tt.commandStr) assert.Equal(t, tt.want, got) }) } } func TestOSCommandNewCommandStringWithShellWindows(t *testing.T) { osCommand := NewDummyOSCommand() osCommand.Platform.os = "windows" tests := []struct { name string commandStr string want string }{ { "success", "pwd", fmt.Sprintf("%v %v %v", osCommand.Platform.shell, osCommand.Platform.shellArg, "pwd"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := osCommand.NewCommandStringWithShell(tt.commandStr) assert.Equal(t, tt.want, got) }) } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/os_windows.go
pkg/commands/os_windows.go
package commands func getPlatform() *Platform { return &Platform{ os: "windows", shell: "cmd", shellArg: "/c", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/os_default_platform.go
pkg/commands/os_default_platform.go
//go:build !windows // +build !windows package commands import ( "runtime" ) func getPlatform() *Platform { return &Platform{ os: runtime.GOOS, shell: "bash", shellArg: "-c", openCommand: "open {{filename}}", openLinkCommand: "open {{link}}", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/os.go
pkg/commands/os.go
package commands import ( "context" "fmt" "io" "os" "os/exec" "path/filepath" "strings" "sync" "time" "github.com/go-errors/errors" "github.com/jesseduffield/kill" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/mgutz/str" "github.com/sirupsen/logrus" ) // Platform stores the os state type Platform struct { os string shell string shellArg string openCommand string openLinkCommand string } // OSCommand holds all the os commands type OSCommand struct { Log *logrus.Entry Platform *Platform Config *config.AppConfig command func(string, ...string) *exec.Cmd getenv func(string) string } // NewOSCommand os command runner func NewOSCommand(log *logrus.Entry, config *config.AppConfig) *OSCommand { return &OSCommand{ Log: log, Platform: getPlatform(), Config: config, command: exec.Command, getenv: os.Getenv, } } // SetCommand sets the command function used by the struct. // To be used for testing only func (c *OSCommand) SetCommand(cmd func(string, ...string) *exec.Cmd) { c.command = cmd } // RunCommandWithOutput wrapper around commands returning their output and error func (c *OSCommand) RunCommandWithOutput(command string) (string, error) { cmd := c.ExecutableFromString(command) before := time.Now() output, err := sanitisedCommandOutput(cmd.Output()) c.Log.Warn(fmt.Sprintf("'%s': %s", command, time.Since(before))) return output, err } // RunCommandWithOutput wrapper around commands returning their output and error func (c *OSCommand) RunCommandWithOutputContext(ctx context.Context, command string) (string, error) { cmd := c.ExecutableFromStringContext(ctx, command) before := time.Now() output, err := sanitisedCommandOutput(cmd.Output()) c.Log.Warn(fmt.Sprintf("'%s': %s", command, time.Since(before))) return output, err } // RunExecutableWithOutput runs an executable file and returns its output func (c *OSCommand) RunExecutableWithOutput(cmd *exec.Cmd) (string, error) { return sanitisedCommandOutput(cmd.CombinedOutput()) } // RunExecutable runs an executable file and returns an error if there was one func (c *OSCommand) RunExecutable(cmd *exec.Cmd) error { _, err := c.RunExecutableWithOutput(cmd) return err } // ExecutableFromString takes a string like `docker ps -a` and returns an executable command for it func (c *OSCommand) ExecutableFromString(commandStr string) *exec.Cmd { splitCmd := str.ToArgv(commandStr) return c.NewCmd(splitCmd[0], splitCmd[1:]...) } // Same as ExecutableFromString but cancellable via a context func (c *OSCommand) ExecutableFromStringContext(ctx context.Context, commandStr string) *exec.Cmd { splitCmd := str.ToArgv(commandStr) return exec.CommandContext(ctx, splitCmd[0], splitCmd[1:]...) } func (c *OSCommand) NewCmd(cmdName string, commandArgs ...string) *exec.Cmd { cmd := c.command(cmdName, commandArgs...) cmd.Env = os.Environ() return cmd } func (c *OSCommand) NewCommandStringWithShell(commandStr string) string { var quotedCommand string // Windows does not seem to like quotes around the command if c.Platform.os == "windows" { quotedCommand = strings.NewReplacer( "^", "^^", "&", "^&", "|", "^|", "<", "^<", ">", "^>", "%", "^%", ).Replace(commandStr) } else { quotedCommand = c.Quote(commandStr) } return fmt.Sprintf("%s %s %s", c.Platform.shell, c.Platform.shellArg, quotedCommand) } // RunCommand runs a command and just returns the error func (c *OSCommand) RunCommand(command string) error { _, err := c.RunCommandWithOutput(command) return err } // FileType tells us if the file is a file, directory or other func (c *OSCommand) FileType(path string) string { fileInfo, err := os.Stat(path) if err != nil { return "other" } if fileInfo.IsDir() { return "directory" } return "file" } func sanitisedCommandOutput(output []byte, err error) (string, error) { outputString := string(output) if err != nil { // errors like 'exit status 1' are not very useful so we'll create an error // from stderr if we got an ExitError exitError, ok := err.(*exec.ExitError) if ok { return outputString, errors.New(string(exitError.Stderr)) } return "", WrapError(err) } return outputString, nil } // OpenFile opens a file with the given func (c *OSCommand) OpenFile(filename string) error { commandTemplate := c.Config.UserConfig.OS.OpenCommand templateValues := map[string]string{ "filename": c.Quote(filename), } command := utils.ResolvePlaceholderString(commandTemplate, templateValues) err := c.RunCommand(command) return err } // OpenLink opens a file with the given func (c *OSCommand) OpenLink(link string) error { commandTemplate := c.Config.UserConfig.OS.OpenLinkCommand templateValues := map[string]string{ "link": c.Quote(link), } command := utils.ResolvePlaceholderString(commandTemplate, templateValues) err := c.RunCommand(command) return err } // EditFile opens a file in a subprocess using whatever editor is available, // falling back to core.editor, VISUAL, EDITOR, then vi func (c *OSCommand) EditFile(filename string) (*exec.Cmd, error) { editor := c.getenv("VISUAL") if editor == "" { editor = c.getenv("EDITOR") } if editor == "" { if err := c.RunCommand("which vi"); err == nil { editor = "vi" } } if editor == "" { return nil, errors.New("No editor defined in $VISUAL or $EDITOR") } return c.NewCmd(editor, filename), nil } // Quote wraps a message in platform-specific quotation marks func (c *OSCommand) Quote(message string) string { var quote string if c.Platform.os == "windows" { quote = `\"` message = strings.NewReplacer( `"`, `"'"'"`, `\"`, `\\"`, ).Replace(message) } else { quote = `"` message = strings.NewReplacer( `\`, `\\`, `"`, `\"`, `$`, `\$`, "`", "\\`", ).Replace(message) } return quote + message + quote } // Unquote removes wrapping quotations marks if they are present // this is needed for removing quotes from staged filenames with spaces func (c *OSCommand) Unquote(message string) string { return strings.Replace(message, `"`, "", -1) } // AppendLineToFile adds a new line in file func (c *OSCommand) AppendLineToFile(filename, line string) error { f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600) if err != nil { return WrapError(err) } defer f.Close() _, err = f.WriteString("\n" + line) if err != nil { return WrapError(err) } return nil } // CreateTempFile writes a string to a new temp file and returns the file's name func (c *OSCommand) CreateTempFile(filename, content string) (string, error) { tmpfile, err := os.CreateTemp("", filename) if err != nil { c.Log.Error(err) return "", WrapError(err) } if _, err := tmpfile.WriteString(content); err != nil { c.Log.Error(err) return "", WrapError(err) } if err := tmpfile.Close(); err != nil { c.Log.Error(err) return "", WrapError(err) } return tmpfile.Name(), nil } // Remove removes a file or directory at the specified path func (c *OSCommand) Remove(filename string) error { err := os.RemoveAll(filename) return WrapError(err) } // FileExists checks whether a file exists at the specified path func (c *OSCommand) FileExists(path string) (bool, error) { if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { return false, nil } return false, err } return true, nil } // RunPreparedCommand takes a pointer to an exec.Cmd and runs it // this is useful if you need to give your command some environment variables // before running it func (c *OSCommand) RunPreparedCommand(cmd *exec.Cmd) error { out, err := cmd.CombinedOutput() outString := string(out) c.Log.Info(outString) if err != nil { if len(outString) == 0 { return err } return errors.New(outString) } return nil } // GetLazydockerPath returns the path of the currently executed file func (c *OSCommand) GetLazydockerPath() string { ex, err := os.Executable() // get the executable path for docker to use if err != nil { ex = os.Args[0] // fallback to the first call argument if needed } return filepath.ToSlash(ex) } // RunCustomCommand returns the pointer to a custom command func (c *OSCommand) RunCustomCommand(command string) *exec.Cmd { return c.NewCmd(c.Platform.shell, c.Platform.shellArg, command) } // PipeCommands runs a heap of commands and pipes their inputs/outputs together like A | B | C func (c *OSCommand) PipeCommands(commandStrings ...string) error { cmds := make([]*exec.Cmd, len(commandStrings)) for i, str := range commandStrings { cmds[i] = c.ExecutableFromString(str) } for i := 0; i < len(cmds)-1; i++ { stdout, err := cmds[i].StdoutPipe() if err != nil { return err } cmds[i+1].Stdin = stdout } // keeping this here in case I adapt this code for some other purpose in the future // cmds[len(cmds)-1].Stdout = os.Stdout finalErrors := []string{} wg := sync.WaitGroup{} wg.Add(len(cmds)) for _, cmd := range cmds { currentCmd := cmd go func() { stderr, err := currentCmd.StderrPipe() if err != nil { c.Log.Error(err) } if err := currentCmd.Start(); err != nil { c.Log.Error(err) } if b, err := io.ReadAll(stderr); err == nil { if len(b) > 0 { finalErrors = append(finalErrors, string(b)) } } if err := currentCmd.Wait(); err != nil { c.Log.Error(err) } wg.Done() }() } wg.Wait() if len(finalErrors) > 0 { return errors.New(strings.Join(finalErrors, "\n")) } return nil } // Kill kills a process. If the process has Setpgid == true, then we have anticipated that it might spawn its own child processes, so we've given it a process group ID (PGID) equal to its process id (PID) and given its child processes will inherit the PGID, we can kill that group, rather than killing the process itself. func (c *OSCommand) Kill(cmd *exec.Cmd) error { return kill.Kill(cmd) } // PrepareForChildren sets Setpgid to true on the cmd, so that when we run it as a subprocess, we can kill its group rather than the process itself. This is because some commands, like `docker-compose logs` spawn multiple children processes, and killing the parent process isn't sufficient for killing those child processes. We set the group id here, and then in subprocess.go we check if the group id is set and if so, we kill the whole group rather than just the one process. func (c *OSCommand) PrepareForChildren(cmd *exec.Cmd) { kill.PrepareForChildren(cmd) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/project.go
pkg/commands/project.go
package commands type Project struct { Name string }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/ssh/ssh.go
pkg/commands/ssh/ssh.go
package ssh import ( "context" "fmt" "io" "net" "net/url" "os" "os/exec" "path" "time" ) // we only need these two methods from our OSCommand struct, for killing commands type CmdKiller interface { Kill(cmd *exec.Cmd) error PrepareForChildren(cmd *exec.Cmd) } type SSHHandler struct { oSCommand CmdKiller dialContext func(ctx context.Context, network, addr string) (io.Closer, error) startCmd func(*exec.Cmd) error tempDir func(dir string, pattern string) (name string, err error) getenv func(key string) string setenv func(key, value string) error } func NewSSHHandler(oSCommand CmdKiller) *SSHHandler { return &SSHHandler{ oSCommand: oSCommand, dialContext: func(ctx context.Context, network, addr string) (io.Closer, error) { return (&net.Dialer{}).DialContext(ctx, network, addr) }, startCmd: func(cmd *exec.Cmd) error { return cmd.Start() }, tempDir: os.MkdirTemp, getenv: os.Getenv, setenv: os.Setenv, } } // HandleSSHDockerHost overrides the DOCKER_HOST environment variable // to point towards a local unix socket tunneled over SSH to the specified ssh host. func (self *SSHHandler) HandleSSHDockerHost() (io.Closer, error) { const key = "DOCKER_HOST" ctx := context.Background() u, err := url.Parse(self.getenv(key)) if err != nil { // if no or an invalid docker host is specified, continue nominally return noopCloser{}, nil } // if the docker host scheme is "ssh", forward the docker socket before creating the client if u.Scheme == "ssh" { tunnel, err := self.createDockerHostTunnel(ctx, u.Host) if err != nil { return noopCloser{}, fmt.Errorf("tunnel ssh docker host: %w", err) } err = self.setenv(key, tunnel.socketPath) if err != nil { return noopCloser{}, fmt.Errorf("override DOCKER_HOST to tunneled socket: %w", err) } return tunnel, nil } return noopCloser{}, nil } type noopCloser struct{} func (noopCloser) Close() error { return nil } type tunneledDockerHost struct { socketPath string cmd *exec.Cmd oSCommand CmdKiller } var _ io.Closer = (*tunneledDockerHost)(nil) func (t *tunneledDockerHost) Close() error { return t.oSCommand.Kill(t.cmd) } func (self *SSHHandler) createDockerHostTunnel(ctx context.Context, remoteHost string) (*tunneledDockerHost, error) { socketDir, err := self.tempDir("/tmp", "lazydocker-sshtunnel-") if err != nil { return nil, fmt.Errorf("create ssh tunnel tmp file: %w", err) } localSocket := path.Join(socketDir, "dockerhost.sock") cmd, err := self.tunnelSSH(ctx, remoteHost, localSocket) if err != nil { return nil, fmt.Errorf("tunnel docker host over ssh: %w", err) } // set a reasonable timeout, then wait for the socket to dial successfully // before attempting to create a new docker client const socketTunnelTimeout = 8 * time.Second ctx, cancel := context.WithTimeout(ctx, socketTunnelTimeout) defer cancel() err = self.retrySocketDial(ctx, localSocket) if err != nil { return nil, fmt.Errorf("ssh tunneled socket never became available: %w", err) } // construct the new DOCKER_HOST url with the proper scheme newDockerHostURL := url.URL{Scheme: "unix", Path: localSocket} return &tunneledDockerHost{ socketPath: newDockerHostURL.String(), cmd: cmd, oSCommand: self.oSCommand, }, nil } // Attempt to dial the socket until it becomes available. // The retry loop will continue until the parent context is canceled. func (self *SSHHandler) retrySocketDial(ctx context.Context, socketPath string) error { t := time.NewTicker(1 * time.Second) defer t.Stop() for { select { case <-ctx.Done(): return ctx.Err() case <-t.C: } // attempt to dial the socket, exit on success err := self.tryDial(ctx, socketPath) if err != nil { continue } return nil } } // Try to dial the specified unix socket, immediately close the connection if successfully created. func (self *SSHHandler) tryDial(ctx context.Context, socketPath string) error { conn, err := self.dialContext(ctx, "unix", socketPath) if err != nil { return err } defer conn.Close() return nil } func (self *SSHHandler) tunnelSSH(ctx context.Context, host, localSocket string) (*exec.Cmd, error) { cmd := exec.CommandContext(ctx, "ssh", "-L", localSocket+":/var/run/docker.sock", host, "-N") self.oSCommand.PrepareForChildren(cmd) err := self.startCmd(cmd) if err != nil { return nil, err } return cmd, nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/commands/ssh/ssh_test.go
pkg/commands/ssh/ssh_test.go
package ssh import ( "context" "io" "os/exec" "testing" "github.com/stretchr/testify/assert" ) func TestSSHHandlerHandleSSHDockerHost(t *testing.T) { type scenario struct { testName string envVarValue string expectedDialContextCount int expectedStartCmdCount int } scenarios := []scenario{ { testName: "No env var set", envVarValue: "", expectedDialContextCount: 0, expectedStartCmdCount: 0, }, { testName: "Env var set with https scheme", envVarValue: "https://myhost.com", expectedStartCmdCount: 0, expectedDialContextCount: 0, }, { testName: "Env var set with ssh scheme", envVarValue: "ssh://myhost@192.168.5.178", expectedStartCmdCount: 1, expectedDialContextCount: 1, }, } for _, s := range scenarios { s := s t.Run(s.testName, func(t *testing.T) { getenv := func(key string) string { if key != "DOCKER_HOST" { t.Errorf("Expected key to be DOCKER_HOST, got %s", key) } return s.envVarValue } tempDir := func(dir string, pattern string) (string, error) { assert.Equal(t, "/tmp", dir) assert.Equal(t, "lazydocker-sshtunnel-", pattern) return "/tmp/lazydocker-ssh-tunnel-12345", nil } setenv := func(key, value string) error { assert.Equal(t, "DOCKER_HOST", key) assert.Equal(t, "unix:///tmp/lazydocker-ssh-tunnel-12345/dockerhost.sock", value) return nil } startCmdCount := 0 startCmd := func(cmd *exec.Cmd) error { assert.EqualValues(t, []string{"ssh", "-L", "/tmp/lazydocker-ssh-tunnel-12345/dockerhost.sock:/var/run/docker.sock", "192.168.5.178", "-N"}, cmd.Args) startCmdCount++ return nil } dialContextCount := 0 dialContext := func(ctx context.Context, network string, address string) (io.Closer, error) { assert.Equal(t, "unix", network) assert.Equal(t, "/tmp/lazydocker-ssh-tunnel-12345/dockerhost.sock", address) dialContextCount++ return noopCloser{}, nil } handler := &SSHHandler{ oSCommand: &fakeCmdKiller{}, dialContext: dialContext, startCmd: startCmd, tempDir: tempDir, getenv: getenv, setenv: setenv, } _, err := handler.HandleSSHDockerHost() assert.NoError(t, err) assert.Equal(t, s.expectedDialContextCount, dialContextCount) assert.Equal(t, s.expectedStartCmdCount, startCmdCount) }) } } type fakeCmdKiller struct{} func (self *fakeCmdKiller) Kill(cmd *exec.Cmd) error { return nil } func (self *fakeCmdKiller) PrepareForChildren(cmd *exec.Cmd) {}
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/turkish.go
pkg/i18n/turkish.go
package i18n func turkishSet() TranslationSet { return TranslationSet{ PruningStatus: "temizleniyor", RemovingStatus: "kaldırılıyor", RestartingStatus: "yeniden başlatılıyor", StoppingStatus: "durduruluyor", RunningCustomCommandStatus: "özel komut çalıştır", NoViewMachingNewLineFocusedSwitchStatement: "NewLineFocused anahtar deyimi ile eşleşen görünüm yok", ErrorOccurred: "Bir hata oluştu! Lütfen https://github.com/jesseduffield/lazydocker/issues adresinden bir hataya ilişkin konu oluşturun", ConnectionFailed: "Docker bağlantısı başarısız oldu. Docker' ı yeniden başlatmanız gerekebilir", UnattachableContainerError: "Konteyner attaching modunda çalışmayı desteklemiyor. Hizmeti '-it' opsiyonu ile çalıştırmanız veya docker-compose.yml dosyasında `stdin_open: true, tty: true` kullanmanız gerekir.", CannotAttachStoppedContainerError: "Durdurulan konteynera bağlanamazsınız, ilk önce başlatmanız gerekir (aslında başlatmayı r tuşu ile yapabilirsiniz) (evet, senin için bunu otomatik olarak yapabilirim fakat çok tembelim) (hata mesajı ile seninle birebir iletişim kurmam çok daha güzel)", CannotAccessDockerSocketError: "Docker' a şu adresten erişilemiyor : unix:///var/run/docker.sock\n lazydocker' ı root(kök kullanıcı) olarak çalıştır veya şu adresteki adımları takip et : https://docs.docker.com/install/linux/linux-postinstall/", Donate: "Bağış", Confirm: "Onayla", Return: "dönüş", FocusMain: "ana panele odaklan", Navigate: "gezin", Execute: "çalıştır", Close: "kapat", Menu: "menü", MenuTitle: "Menü", Scroll: "kaydır", OpenConfig: "lazydocker ayarlarını aç", EditConfig: "lazzydocker ayarlarını düzenle", Cancel: "iptal", Remove: "kaldır", ForceRemove: "kaldırmaya zorla", RemoveWithVolumes: "alanları ile birlikte kaldır", RemoveService: "konteynerleri kaldır", Stop: "durdur", Restart: "yeniden başlat", Rebuild: "yeniden yapılandır", Recreate: "yeniden oluştur", PreviousContext: "önceki sekme", NextContext: "sonraki sekme", Attach: "bağlan/iliştir", ViewLogs: "kayıt defterini görüntüle", RemoveImage: "imajı kaldır", RemoveVolume: "alanı kaldır", RemoveNetwork: "ağı kaldır", RemoveWithoutPrune: "etkisiz ebeveynleri silmeden kaldır", PruneContainers: "çalışmayan konteynerleri temizle", PruneVolumes: "kullanılmayan alanları temizle", PruneNetworks: "kullanılmayan ağları temizle", PruneImages: "kullanılmayan imajları temizle", ViewRestartOptions: "yeniden başlatma seçeneklerini görüntüle", RunCustomCommand: "önceden tanımlanmış özel komutu çalıştır", GlobalTitle: "Global", MainTitle: "Ana", ProjectTitle: "Proje", ServicesTitle: "Servisler", ContainersTitle: "Konteynerler", StandaloneContainersTitle: "Bağımsız Konteynerler", ImagesTitle: "Imajlar", VolumesTitle: "Alanlar", NetworksTitle: "Ağları", CustomCommandTitle: "Özel Komut:", ErrorTitle: "Hata", LogsTitle: "Kayitlar", ConfigTitle: "Ayarlar", EnvTitle: "Env", DockerComposeConfigTitle: "Docker-Compose Ayar", TopTitle: "Top", StatsTitle: "Durumlar", CreditsTitle: "Hakkinda", ContainerConfigTitle: "Konteyner Ayar", ContainerEnvTitle: "Konteyner Env", NothingToDisplay: "Nothing to display", CannotDisplayEnvVariables: "Something went wrong while displaying environment variables", NoContainers: "Konteynerler yok", NoContainer: "Konteyner yok", NoImages: "Imajlar yok", NoVolumes: "Alanlar yok", NoNetworks: "Ağları yok", ConfirmQuit: "Çıkmak istediğine emin misin?", MustForceToRemoveContainer: "Zorlamadan çalışan bir konteyneri kaldıramazsınız. Zorlamak ister misin?", NotEnoughSpace: "Panelleri oluşturmak için yeterli alan yok", ConfirmPruneImages: "Kullanılmayan tüm görüntüleri temizlemek istediğinize emin misiniz?", ConfirmPruneContainers: "Durdurulan tüm konteynerları temizlemek istediğinizden emin misiniz?", ConfirmPruneVolumes: "Kullanılmayan tüm alanları temizlemek istediğinizden emin misiniz?", ConfirmPruneNetworks: "Kullanılmayan tüm ağları temizlemek istediğinizden emin misiniz?", StopService: "Bu servisin konteynerlerini durdurmak istediğinize emin misiniz?", StopContainer: "Bu konteyneri durdurmak istediğinize emin misiniz?", PressEnterToReturn: "lazydocker' a geri dönmek için enter tuşuna basın ( Bu uyarı, `gui.return Immediately: true` ayarıyla devre dışı bırakılabilir)", DetachFromContainerShortCut: "Varsayılan olarak, kaptan ayırmak için ctrl-p ve ardından ctrl-q tuşlarına basın", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/i18n.go
pkg/i18n/i18n.go
package i18n import ( "strings" "github.com/imdario/mergo" "github.com/cloudfoundry/jibber_jabber" "github.com/go-errors/errors" "github.com/sirupsen/logrus" ) // Localizer will translate a message into the user's language type Localizer struct { Log *logrus.Entry S TranslationSet } func NewTranslationSetFromConfig(log *logrus.Entry, configLanguage string) (*TranslationSet, error) { if configLanguage == "auto" { language := detectLanguage(jibber_jabber.DetectLanguage) return NewTranslationSet(log, language), nil } for key := range GetTranslationSets() { if key == configLanguage { return NewTranslationSet(log, configLanguage), nil } } return NewTranslationSet(log, "en"), errors.New("Language not found: " + configLanguage) } func NewTranslationSet(log *logrus.Entry, language string) *TranslationSet { log.Info("language: " + language) baseSet := englishSet() for languageCode, translationSet := range GetTranslationSets() { if strings.HasPrefix(language, languageCode) { _ = mergo.Merge(&baseSet, translationSet, mergo.WithOverride) } } return &baseSet } // GetTranslationSets gets all the translation sets, keyed by language code func GetTranslationSets() map[string]TranslationSet { return map[string]TranslationSet{ "pl": polishSet(), "nl": dutchSet(), "de": germanSet(), "tr": turkishSet(), "en": englishSet(), "fr": frenchSet(), "zh": chineseSet(), "es": spanishSet(), "pt": portugueseSet(), } } // detectLanguage extracts user language from environment func detectLanguage(langDetector func() (string, error)) string { if userLang, err := langDetector(); err == nil { return userLang } return "C" }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/french.go
pkg/i18n/french.go
package i18n func frenchSet() TranslationSet { return TranslationSet{ PruningStatus: "destruction", RemovingStatus: "suppression", RestartingStatus: "redémarrage", StartingStatus: "démarrage", StoppingStatus: "arrêt", PausingStatus: "mise en pause", RunningCustomCommandStatus: "exécution de la commande personalisée", RunningBulkCommandStatus: "exécution de la commande groupée", NoViewMachingNewLineFocusedSwitchStatement: "Aucune vue correspondant au switch newLineFocused", ErrorOccurred: "Une erreur s'est produite ! Veuillez créer un rapport d'erreur sur https://github.com/jesseduffield/lazydocker/issues", ConnectionFailed: "Erreur lors de la connexion au client Docker. Essayez de redémarrer votre client Docker", UnattachableContainerError: "Le conteneur ne peut pas être attaché. Vous devez exécuter le service avec le drapeau 'it' ou bien utiliser `stdin_open: true, tty: true` dans votre fichier docker-compose.yml", WaitingForContainerInfo: "Le processus ne peut pas continuer avant que Docker ne fournisse plus d'informations. Veuillez réessayer dans quelques instants.", CannotAttachStoppedContainerError: "Vous ne pouvez pas vous attacher à un conteneur arrêté, vous devez le démarrer en amont (ce que vous pouvez faire avec la touche 'r') (oui, je suis trop paresseux pour le faire automatiquement pour vous) (plutôt cool que je puisse communiquer en tête-à-tête avec vous au travers d'un message d'erreur, cependant)", CannotAccessDockerSocketError: "Impossible d'accéder au socket Docker à : unix:///var/run/docker.sock\nLancez lazydocker en tant que root ou alors lisez https://docs.docker.com/install/linux/linux-postinstall/", CannotKillChildError: "Trois secondes se sont écoulées depuis la demande d'arrêt des processus enfants. Il se peut qu'un processus orphelin continue à tourner sur votre système.", Donate: "Donner", Confirm: "Confirmer", Return: "retour", FocusMain: "focus panneau principal", Navigate: "naviguer", Execute: "exécuter", Close: "fermer", Menu: "menu", MenuTitle: "Menu", Scroll: "faire défiler", OpenConfig: "ouvrir la configuration lazydocker", EditConfig: "modifier la configuration lazydocker", Cancel: "annuler", Remove: "supprimer", HideStopped: "cacher/montrer les conteneurs arrêtés", ForceRemove: "forcer la suppression", RemoveWithVolumes: "supprimer avec les volumes", RemoveService: "supprimer les conteneurs", Stop: "arrêter", Pause: "pause", Restart: "redémarrer", Start: "démarrer", Rebuild: "reconstruire", Recreate: "recréer", PreviousContext: "onglet précédent", NextContext: "onglet suivant", Attach: "attacher", ViewLogs: "voir les enregistrements", RemoveImage: "supprimer l'image", RemoveVolume: "supprimer le volume", RemoveNetwork: "supprimer le réseau", RemoveWithoutPrune: "supprimer sans effacer les parents non étiquetés", RemoveWithoutPruneWithForce: "supprimer (forcer) sans effacer les parents non étiquetés", RemoveWithForce: "supprimer (forcer)", PruneContainers: "détruire les conteneurs arrêtés", PruneVolumes: "détruire les volumes non utilisés", PruneNetworks: "détruire les réseaux non utilisés", PruneImages: "détruire les images non utilisées", StopAllContainers: "arrêter tous les conteneurs", RemoveAllContainers: "supprimer tous les conteneurs (forcer)", ViewRestartOptions: "voir les options de redémarrage", ExecShell: "exécuter le shell", RunCustomCommand: "exécuter une commande prédéfinie", ViewBulkCommands: "voir les commandes groupées", OpenInBrowser: "ouvrir dans le navigateur (le premier port est http)", SortContainersByState: "ordonner les conteneurs par état", GlobalTitle: "Global", MainTitle: "Principal", ProjectTitle: "Projet", ServicesTitle: "Services", ContainersTitle: "Conteneurs", StandaloneContainersTitle: "Conteneurs autonomes", ImagesTitle: "Images", VolumesTitle: "Volumes", NetworksTitle: "Réseaux", CustomCommandTitle: "Commande personnalisée :", BulkCommandTitle: "Commande groupée :", ErrorTitle: "Erreur", LogsTitle: "Journaux", ConfigTitle: "Config", EnvTitle: "Env", DockerComposeConfigTitle: "Config Docker-Compose", TopTitle: "Top", StatsTitle: "Statistiques", CreditsTitle: "À propos", ContainerConfigTitle: "Config Conteneur", ContainerEnvTitle: "Env Conteneur", NothingToDisplay: "Rien à afficher", CannotDisplayEnvVariables: "Quelque chose a échoué lors de l'affichage des variables d'environnement", NoContainers: "Aucun conteneur", NoContainer: "Aucun conteneur", NoImages: "Aucune image", NoVolumes: "Aucun volume", NoNetworks: "Aucun réseau", ConfirmQuit: "Êtes-vous certain de vouloir quitter ?", MustForceToRemoveContainer: "Vous ne pouvez pas supprimer un conteneur qui tourne sans le forcer. Voulez-vous le forcer ?", NotEnoughSpace: "Manque d'espace pour afficher les différent panneaux", ConfirmPruneImages: "Êtes-vous certain de vouloir détruire toutes les images non utilisées ?", ConfirmPruneContainers: "Êtes-vous certain de vouloir détruire tous les conteneurs arrêtés ?", ConfirmStopContainers: "Êtes-vous certain de vouloir arrêter tous les conteneurs ?", ConfirmRemoveContainers: "Êtes-vous certain de vouloir supprimer tous les conteneurs ?", ConfirmPruneVolumes: "Êtes-vous certain de vouloir détruire tous les volumes non utilisés ?", ConfirmPruneNetworks: "Êtes-vous certain de vouloir détruire tous les réseaux non utilisés ?", StopService: "Êtes-vous certain de vouloir arrêter le conteneur de ce service ?", StopContainer: "Êtes-vous certain de vouloir arrêter ce conteneur ?", PressEnterToReturn: "Appuyez sur Entrée pour revenir à lazydocker (ce message peut être désactivé dans vos configurations en appliquant `gui.returnImmediately: true`)", DetachFromContainerShortCut: "Par défaut, pour se détacher du conteneur appuyez sur CTRL-P puis CTRL-Q", No: "non", Yes: "oui", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/dutch.go
pkg/i18n/dutch.go
package i18n func dutchSet() TranslationSet { return TranslationSet{ PruningStatus: "vernietigen", RemovingStatus: "verwijderen", RestartingStatus: "herstarten", StoppingStatus: "stoppen", RunningCustomCommandStatus: "Aangepast commando draaien", NoViewMachingNewLineFocusedSwitchStatement: "No view matching newLineFocused switch statement", ErrorOccurred: "Er is iets fout gegaan! Zou je hier een issue aan willen maken: https://github.com/jesseduffield/lazydocker/issues", ConnectionFailed: "connectie naar de docker client mislukt. Het zou kunnen dat je de docker client moet herstarten", UnattachableContainerError: "Container heeft geen ondersteuning voor vastmaken. Je zou de service met het '-it' argument kunnen draaien of stop dit in je `stdin_open: true, tty: true` docker-compose.yml", CannotAttachStoppedContainerError: "Je kan niet een vastgemaakte container stoppen, je moet het eerst starten (dit kan je doen met de 'r' toets) (ja ik ben te leu om dat voor je te doen automatisch)", CannotAccessDockerSocketError: "Kan de docker socket niet bereiken: unix:///var/run/docker.sock\nDraai lazydocker als root of lees https://docs.docker.com/install/linux/linux-postinstall/", Donate: "Doneer", Confirm: "Bevestigen", Return: "terug", FocusMain: "focus hoofdpaneel", Navigate: "navigeer", Execute: "voer uit", Close: "sluit", Menu: "menu", MenuTitle: "Menu", Scroll: "scroll", OpenConfig: "open de lazydocker configuratie", EditConfig: "verander de lazydocker configuratie", Cancel: "annuleren", Remove: "verwijder", HideStopped: "verberg gestopte containers", ForceRemove: "geforceerd verwijderen", RemoveWithVolumes: "verwijder met volumes", RemoveService: "verwijder containers", Stop: "stop", Restart: "herstart", Rebuild: "herbouw", Recreate: "hercreëer", PreviousContext: "vorige tab", NextContext: "volgende tab", Attach: "verbinden", ViewLogs: "bekijk logs", RemoveImage: "verwijder image", RemoveVolume: "verwijder volume", RemoveNetwork: "verwijder network", RemoveWithoutPrune: "verwijder zonder de ongelabeld ouders te verwijderen", PruneContainers: "vernietig bestaande containers", PruneVolumes: "vernietig ongebruikte volumes", PruneNetworks: "vernietig ongebruikte networks", PruneImages: "vernietig ongebruikte images", ViewRestartOptions: "bekijk herstart opties", RunCustomCommand: "draai een vooraf bedacht aangepaste opdracht", GlobalTitle: "Globaal", MainTitle: "Hoofd", ProjectTitle: "Project", ServicesTitle: "Diensten", ContainersTitle: "Containers", StandaloneContainersTitle: "Alleenstaande Containers", ImagesTitle: "Images", VolumesTitle: "Volumes", NetworksTitle: "Networks", CustomCommandTitle: "Aangepast commando:", ErrorTitle: "Fout", LogsTitle: "Logs", ConfigTitle: "Config", EnvTitle: "Env", DockerComposeConfigTitle: "Docker-Compose Configuratie", TopTitle: "Top", StatsTitle: "Stats", CreditsTitle: "Over", ContainerConfigTitle: "Container Configuratie", ContainerEnvTitle: "Container Env", NothingToDisplay: "Nothing to display", CannotDisplayEnvVariables: "Something went wrong while displaying environment variables", NoContainers: "Geen containers", NoContainer: "Geen container", NoImages: "Geen images", NoVolumes: "Geen volumes", NoNetworks: "Geen networks", ConfirmQuit: "Weet je zeker dat je weg wil gaan?", MustForceToRemoveContainer: "Je kan geen draaiende container verwijderen tenzij je het forceert, Wil je het forceren?", NotEnoughSpace: "Niet genoeg ruimte om de panelen te renderen", ConfirmPruneImages: "Weet je zeker dat je alle niet gebruikte images wil vernietigen?", ConfirmPruneContainers: "Weet je zeker dat je alle niet gestopte containers wil vernietigen?", ConfirmPruneVolumes: "Weet je zeker dat je alle niet gebruikte volumes wil vernietigen?", ConfirmPruneNetworks: "Weet je zeker dat je alle niet gebruikte networks wil vernietigen?", StopService: "Weet je zeker dat je deze service zijn containers wil stoppen?", StopContainer: "Weet je zeker dat je deze container wil stoppen?", PressEnterToReturn: "Druk op enter om terug te gaan naar lazydocker (Deze popup kan uit gezet worden door in de config dit neer te zetten `gui.returnImmediately: true`)", DetachFromContainerShortCut: "Als u wilt loskoppelen van de container, drukt u standaard op ctrl-p en vervolgens op ctrl-q", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/chinese.go
pkg/i18n/chinese.go
package i18n func chineseSet() TranslationSet { return TranslationSet{ PruningStatus: "修剪中", RemovingStatus: "移除中", RestartingStatus: "重启中", StartingStatus: "启动中", StoppingStatus: "停止中", UppingServiceStatus: "升级服务中", UppingProjectStatus: "升级项目中", DowningStatus: "下架中", PausingStatus: "暂停中", RunningCustomCommandStatus: "正在运行自定义命令", RunningBulkCommandStatus: "正在运行批量命令", NoViewMachingNewLineFocusedSwitchStatement: "没有匹配 newLineFocused switch 语句的视图", ErrorOccurred: "发生错误!请在 https://github.com/jesseduffield/lazydocker/issues 上创建一个问题", ConnectionFailed: "无法连接到 Docker 客户端。您可能需要重新启动 Docker 客户端", UnattachableContainerError: "容器不支持 attaching。您必须使用“-it”标志运行服务,或者在docker-compose.yml文件中使用`stdin_open: true,tty: true`", WaitingForContainerInfo: "在 Docker 给我们更多关于容器的信息之前,无法继续。请几分钟后重试。", CannotAttachStoppedContainerError: "您不能 attach 到已停止的容器,您需要先启动它(您可以用 'r' 键来执行此操作)(是的,我懒得为您自动执行此操作)(很酷的是,我可以通过错误消息与您进行一对一的通讯)", CannotAccessDockerSocketError: "无法访问 Docker 套接字:unix:///var/run/docker.sock\n请以 root 用户身份运行 lazydocker 或阅读https://docs.docker.com/install/linux/linux-postinstall/", CannotKillChildError: "等待三秒钟以停止子进程。可能有一个孤儿进程在您的系统上继续运行。", Donate: "捐赠", Confirm: "确认", Return: "返回", FocusMain: "聚焦主面板", LcFilter: "过滤列表", Navigate: "导航", Execute: "执行", Close: "关闭", Quit: "退出", Menu: "菜单", MenuTitle: "菜单", Scroll: "滚动", OpenConfig: "打开lazydocker配置", EditConfig: "编辑lazydocker配置", Cancel: "取消", Remove: "移除", HideStopped: "隐藏/显示已停止的容器", ForceRemove: "强制移除", RemoveWithVolumes: "移除并删除卷", RemoveService: "移除容器", UpService: "启动服务", Stop: "停止", Pause: "暂停", Restart: "重新启动", Down: "关闭项目", DownWithVolumes: "关闭包括卷的项目", Start: "启动项目", Rebuild: "重建", Recreate: "重新创建", PreviousContext: "上一个选项卡", NextContext: "下一个选项卡", // Attach: "连接/附加", ViewLogs: "查看日志", UpProject: "创建并启动容器", DownProject: "停止并移除容器", RemoveImage: "移除镜像", RemoveVolume: "移除卷", RemoveNetwork: "移除网络", RemoveWithoutPrune: "移除但不删除未标记的父级", RemoveWithoutPruneWithForce: "移除(强制)但不删除未标记的父级", RemoveWithForce: "移除(强制)", PruneContainers: "删除退出的容器", PruneVolumes: "删除未使用的卷", PruneNetworks: "删除未使用的网络", PruneImages: "删除未使用的镜像", StopAllContainers: "停止所有容器", RemoveAllContainers: "删除所有容器(强制)", ViewRestartOptions: "查看重启选项", ExecShell: "执行shell", RunCustomCommand: "运行预定义的自定义命令", ViewBulkCommands: "查看批量命令", FilterList: "过滤列表", OpenInBrowser: "在浏览器中打开(第一个端口为http)", SortContainersByState: "按状态排序容器", GlobalTitle: "全局", MainTitle: "主要", ProjectTitle: "项目", ServicesTitle: "服务", ContainersTitle: "容器", StandaloneContainersTitle: "独立容器", ImagesTitle: "镜像", VolumesTitle: "卷", NetworksTitle: "网络", CustomCommandTitle: "自定义命令:", BulkCommandTitle: "批量命令:", ErrorTitle: "错误", LogsTitle: "日志", ConfigTitle: "配置", EnvTitle: "环境变量", DockerComposeConfigTitle: "Docker-Compose配置", TopTitle: "系统资源管理", StatsTitle: "统计信息", CreditsTitle: "关于我们", ContainerConfigTitle: "容器配置", ContainerEnvTitle: "容器环境变量", NothingToDisplay: "无内容显示", NoContainerForService: "没有日志可以展示;该服务未关联任何容器", CannotDisplayEnvVariables: "展示环境变量时出现问题", NoContainers: "没有容器", NoContainer: "没有容器", NoImages: "没有镜像", NoVolumes: "没有卷", NoNetworks: "没有网络", NoServices: "没有服务", ConfirmQuit: "您确定要退出吗?", ConfirmUpProject: "您确定要“up”的docker compose项目吗?", MustForceToRemoveContainer: "您无法删除正在运行的容器,除非您强制执行。您想强制执行吗?", NotEnoughSpace: "空间不足,无法渲染面板", ConfirmPruneImages: "您确定要删除所有未使用的镜像吗?", ConfirmPruneContainers: "您确定要删除所有停止的容器吗?", ConfirmStopContainers: "您确定要停止所有容器吗?", ConfirmRemoveContainers: "您确定要删除所有容器吗?", ConfirmPruneVolumes: "您确定要删除所有未使用的卷吗?", ConfirmPruneNetworks: "您确定要删除所有未使用的网络吗?", StopService: "您确定要停止此服务的容器吗?", StopContainer: "您确定要停止此容器吗?", PressEnterToReturn: "按 enter 返回 lazydocker(您可以在配置文件中设置 `gui.returnImmediately: true` 来禁用此提示)", No: "否", Yes: "是", LcNextScreenMode: "下一个屏幕模式(正常/半屏/全屏)", LcPrevScreenMode: "上一个屏幕模式", FilterPrompt: "筛选", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/spanish.go
pkg/i18n/spanish.go
package i18n func spanishSet() TranslationSet { return TranslationSet{ PruningStatus: "limpiando", RemovingStatus: "eliminando", RestartingStatus: "reiniciando", StartingStatus: "iniciando", StoppingStatus: "terminando", UppingServiceStatus: "levantando servicio", UppingProjectStatus: "levantando proyecto", DowningStatus: "dando de baja", PausingStatus: "pausando", RunningCustomCommandStatus: "ejecutando comando personalizado", RunningBulkCommandStatus: "ejecutando comando masivo", ErrorOccurred: "¡Hubo un error! Por favor crea un issue en https://github.com/jesseduffield/lazydocker/issues", ConnectionFailed: "Falló la conexión con el docker client. Quizá necesitas reiniciar tu docker client", UnattachableContainerError: "Container does not support attaching. You must either run the service with the '-it' flag or use `stdin_open: true, tty: true` in the docker-compose.yml file", WaitingForContainerInfo: "No podemos proceder hasta que docker nos de más información sobre el contenedor. Inténtalo otra vez en unos segundos.", CannotAccessDockerSocketError: "No es posible acceder al docker socket en: unix:///var/run/docker.sock\nEjecuta lazydocker como root o lee https://docs.docker.com/install/linux/linux-postinstall/", CannotKillChildError: "Esperamos tres segundos a que el proceso hijo se detenga. Debe de haber un proceso huérfano que continua activo en tu sistema.", Donate: "Donar", Confirm: "Confirmar", Return: "regresar", FocusMain: "enfocar panel principal", LcFilter: "filtrar lista", Navigate: "navegar", Execute: "ejecutar", Close: "cerrar", Quit: "salir", Menu: "menú", MenuTitle: "Menú", OpenConfig: "abrir configuración de lazydocker", EditConfig: "editar configuración de lazydocker", Cancel: "cancelar", Remove: "borrar", HideStopped: "esconder/mostrar contenedores parados", ForceRemove: "borrar(forzado)", RemoveWithVolumes: "borrar con volúmenes", RemoveService: "borrar contenedores", UpService: "levantar servicio", Stop: "parar", Pause: "pausa", Restart: "reiniciar", Down: "bajar proyecto", DownWithVolumes: "bajar proyecto con volúmenes", Start: "iniciar", Rebuild: "recompilar", Recreate: "recrear", PreviousContext: "anterior pestaña", NextContext: "siguiente pestaña", ViewLogs: "ver logs", UpProject: "levantar proyecto", DownProject: "dar de baja el proyecto", RemoveImage: "limpiar imagen", RemoveVolume: "limpiar volúmen", RemoveNetwork: "limpiar red", RemoveWithoutPrune: "limpiar sin borrar padres sin etiqueta", RemoveWithoutPruneWithForce: "limpiar (forzado) sin borrar padres sin etiqueta", RemoveWithForce: "limpiar (forzado)", PruneContainers: "limpiar contenedores finalizados", PruneVolumes: "limpiar volúmenes sin usar", PruneNetworks: "limpiar redes sin usar", PruneImages: "limpiar imágenes sin usar", StopAllContainers: "detener todos los contenedores", RemoveAllContainers: "borrar todos los contenedores (forzado)", ViewRestartOptions: "ver opciones de reinicio", ExecShell: "ejecutar shell", RunCustomCommand: "ejecutar comando personalizado", ViewBulkCommands: "ver comandos masivos", FilterList: "filtar list", OpenInBrowser: "abrir en navegador (first port is http)", SortContainersByState: "ordenar contenedores por estado", GlobalTitle: "Global", MainTitle: "Inicio", ProjectTitle: "Proyecto", ServicesTitle: "Servicios", ContainersTitle: "Contenedores", StandaloneContainersTitle: "Contenedores independientes", ImagesTitle: "Imágenes", VolumesTitle: "Volúmenes", NetworksTitle: "Redes", CustomCommandTitle: "Comando personalizado:", BulkCommandTitle: "Comando masivo:", ErrorTitle: "Error", LogsTitle: "Logs", ConfigTitle: "Configuración", EnvTitle: "Variables de entorno", DockerComposeConfigTitle: "Docker-Compose Config", TopTitle: "Top", StatsTitle: "Estadísticas", CreditsTitle: "Acerca", ContainerConfigTitle: "Configuración", ContainerEnvTitle: "Variables de entorno", NothingToDisplay: "Nada que mostrar", NoContainerForService: "No hay logs que mostrar; el servicio no está asociado con un contenedor", CannotDisplayEnvVariables: "Algo salió mal mientras se mostraban las variables de entorno", NoContainers: "Sin contenedores", NoContainer: "Sin contenedor", NoImages: "Sin imágenes", NoVolumes: "Sin volúmenes", NoNetworks: "Sin redes", NoServices: "Sin servicios", ConfirmQuit: "¿Realmente quieres salir?", ConfirmUpProject: "¿Realmente quieres levantar tu proyecto docker compose?", MustForceToRemoveContainer: "No puedes borrar un contenedor en ejecución a menos de que lo fuerces, ¿quieres hacerlo?", NotEnoughSpace: "No hay suficiente espacio para renderizar los paneles", ConfirmPruneImages: "¿Realmente quieres limpiar todas tus imágenes?", ConfirmPruneContainers: "¿Realmente quieres limpiar todos los contenedores finalizados?", ConfirmStopContainers: "¿Realmente quieres detener todos los contenedores?", ConfirmRemoveContainers: "¿Realmente quieres borrar todos los contenedores?", ConfirmPruneVolumes: "¿Realmente quieres limpiar todos los vólumenes sin usar?", ConfirmPruneNetworks: "¿Realmente quieres limpiar todas las redes sin usar?", StopService: "¿Realmente quieres detener los contenedores de este servicio?", StopContainer: "¿Realmente quieres detener este contenedor?", PressEnterToReturn: "Presionar [enter] para volver a lazydocker (este mensaje puede ser desactivado en tu configuración poniendo `gui.returnImmediately: true`)", No: "no", Yes: "sí", FilterPrompt: "filtrar", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/portuguese.go
pkg/i18n/portuguese.go
package i18n func portugueseSet() TranslationSet { return TranslationSet{ PruningStatus: "destruindo", RemovingStatus: "removendo", RestartingStatus: "reiniciando", StartingStatus: "iniciando", StoppingStatus: "parando", UppingServiceStatus: "subindo serviço", UppingProjectStatus: "subindo projeto", DowningStatus: "derrubando", PausingStatus: "pausando", RunningCustomCommandStatus: "executando comando personalizado", RunningBulkCommandStatus: "executando comando em massa", NoViewMachingNewLineFocusedSwitchStatement: "No view matching newLineFocused switch statement", ErrorOccurred: "Um erro ocorreu! Por favor, crie uma issue em https://github.com/jesseduffield/lazydocker/issues", ConnectionFailed: "Falha na conexão com o cliente Docker. Você pode precisar reiniciar o seu cliente Docker", UnattachableContainerError: "O contêiner não suporta anexação. Você deve executar o serviço com a flag '-it' ou usar `stdin_open: true, tty: true` no arquivo docker-compose.yml", WaitingForContainerInfo: "Não é possível prosseguir até que o Docker forneça mais informações sobre o contêiner. Por favor, tente novamente em alguns momentos.", CannotAttachStoppedContainerError: "Você não pode anexar a um contêiner parado, você precisa iniciá-lo primeiro (o que você pode fazer com a tecla 'r') (sim, sou preguiçoso demais para fazer isso automaticamente para você) (aliás, bem legal que eu posso me comunicar diretamente com você na forma de uma mensagem de erro)", CannotAccessDockerSocketError: "Não é possível acessar o sôquete docker em: unix:///var/run/docker.sock\nExecute o lazydocker como root ou leia https://docs.docker.com/install/linux/linux-postinstall/", CannotKillChildError: "Três segundos foram esperarados para que os processos filhos parassem. Pode haver um processo órfão que continua em execução em seu sistema.", Donate: "Doar", Confirm: "Confirmar", Return: "retornar", FocusMain: "focar no painel principal", LcFilter: "filtrar lista", Navigate: "navegar", Execute: "executar", Close: "fechar", Quit: "sair", Menu: "menu", MenuTitle: "Menu", Scroll: "rolar", OpenConfig: "abrir configuração do lazydocker", EditConfig: "editar configuração do lazydocker", Cancel: "cancelar", Remove: "remover", HideStopped: "ocultar/mostrar contêineres parados", ForceRemove: "forçar remoção", RemoveWithVolumes: "remover com volumes", RemoveService: "remover contêineres", UpService: "subir serviço", Stop: "parar", Pause: "pausar", Restart: "reiniciar", Down: "derrubar projeto", DownWithVolumes: "derrubar projetos com volumes", Start: "iniciar", Rebuild: "reconstuir", Recreate: "recriar", PreviousContext: "aba anterior", NextContext: "próxima aba", Attach: "anexar", ViewLogs: "ver logs", UpProject: "subir projeto", DownProject: "derrubar projeto", RemoveImage: "remover imagem", RemoveVolume: "remover volume", RemoveNetwork: "remover rede", RemoveWithoutPrune: "remover sem deletar pais não etiquetados", RemoveWithoutPruneWithForce: "remover (forçado) sem deletar pais não etiquetados", RemoveWithForce: "remover (forçado)", PruneContainers: "destruir contêineres encerrados", PruneVolumes: "destruir volumes não utilizados", PruneNetworks: "destruir redes não utilizadas", PruneImages: "destruir imagens não utilizadas", StopAllContainers: "parar todos os contêineres", RemoveAllContainers: "remover todos os contêineres (forçado)", ViewRestartOptions: "ver opções de reinício", ExecShell: "executar shell", RunCustomCommand: "executar comando personalizado predefinido", ViewBulkCommands: "ver comandos em massa", FilterList: "filtrar lista", OpenInBrowser: "abrir no navegador (primeira porta é http)", SortContainersByState: "ordenar contêineres por estado", GlobalTitle: "Global", MainTitle: "Principal", ProjectTitle: "Projeto", ServicesTitle: "Serviços", ContainersTitle: "Contêineres", StandaloneContainersTitle: "Contêineres Avulsos", ImagesTitle: "Imagens", VolumesTitle: "Volumes", NetworksTitle: "Redes", CustomCommandTitle: "Comando Personalizado:", BulkCommandTitle: "Comando em Massa:", ErrorTitle: "Erro", LogsTitle: "Registros", ConfigTitle: "Config", EnvTitle: "Env", DockerComposeConfigTitle: "Docker-Compose Config", TopTitle: "Topo", StatsTitle: "Estatísticas", CreditsTitle: "Sobre", ContainerConfigTitle: "Configuração do Contêiner", ContainerEnvTitle: "Contêiner Env", NothingToDisplay: "Nada a exibir", NoContainerForService: "Nenhum log para exibir; o serviço não está associado a nenhum contêiner", CannotDisplayEnvVariables: "Algo deu errado ao exibir as variáveis de ambiente", NoContainers: "Sem contêineres", NoContainer: "Sem contêiner", NoImages: "Sem imagens", NoVolumes: "Sem volumes", NoNetworks: "Sem redes", NoServices: "Sem serviços", ConfirmQuit: "Tem certeza que deseja sair?", ConfirmUpProject: "Tem certeza que deseja 'iniciar' seu projeto docker compose?", MustForceToRemoveContainer: "Você não pode remover um contêiner em execução a menos que o force. Deseja forçar?", NotEnoughSpace: "Sem espaço suficiente para renderizar os painéis", ConfirmPruneImages: "Tem certeza que deseja eliminar todas as imagens não utilizadas?", ConfirmPruneContainers: "Tem certeza que deseja destruir todos os contêineres parados?", ConfirmStopContainers: "Tem certeza que deseja parar todos os contêineres?", ConfirmRemoveContainers: "Tem certeza que deseja remover todos os contêineres?", ConfirmPruneVolumes: "Tem certeza que deseja destruir todos os volumes não utilizados?", ConfirmPruneNetworks: "Tem certeza que deseja destruir todas as redes não utilizadas?", StopService: "Tem certeza que deseja parar os contêineres deste serviço?", StopContainer: "Tem certeza que deseja parar este contêiner?", PressEnterToReturn: "Pressione enter para retornar ao lazydocker (este prompt pode ser desativado em sua configuração definindo `gui.returnImmediately: true`)", DetachFromContainerShortCut: "Por padrão, para desanexar do contêiner, pressione ctrl-p e depois ctrl-q", No: "não", Yes: "sim", LcNextScreenMode: "modo de tela seguinte (normal/meia/tela cheia)", LcPrevScreenMode: "modo de tela anterior", FilterPrompt: "filtro", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/english.go
pkg/i18n/english.go
package i18n // TranslationSet is a set of localised strings for a given language type TranslationSet struct { NotEnoughSpace string ProjectTitle string MainTitle string GlobalTitle string Navigate string Menu string MenuTitle string Execute string Scroll string Close string Quit string ErrorTitle string NoViewMachingNewLineFocusedSwitchStatement string OpenConfig string EditConfig string ConfirmQuit string ConfirmUpProject string ErrorOccurred string ConnectionFailed string UnattachableContainerError string WaitingForContainerInfo string CannotAttachStoppedContainerError string CannotAccessDockerSocketError string CannotKillChildError string Donate string Cancel string CustomCommandTitle string BulkCommandTitle string Remove string HideStopped string ForceRemove string RemoveWithVolumes string MustForceToRemoveContainer string Confirm string Return string FocusMain string LcFilter string StopContainer string RestartingStatus string StartingStatus string StoppingStatus string UppingProjectStatus string UppingServiceStatus string PausingStatus string RemovingStatus string DowningStatus string RunningCustomCommandStatus string RunningBulkCommandStatus string RemoveService string UpService string Stop string Pause string Restart string Down string DownWithVolumes string Start string Rebuild string Recreate string PreviousContext string NextContext string Attach string ViewLogs string UpProject string DownProject string ServicesTitle string ContainersTitle string StandaloneContainersTitle string TopTitle string ImagesTitle string VolumesTitle string NetworksTitle string NoContainers string NoContainer string NoImages string NoVolumes string NoNetworks string NoServices string RemoveImage string RemoveVolume string RemoveNetwork string RemoveWithoutPrune string RemoveWithoutPruneWithForce string RemoveWithForce string PruneImages string PruneContainers string PruneVolumes string PruneNetworks string ConfirmPruneContainers string ConfirmStopContainers string ConfirmRemoveContainers string ConfirmPruneImages string ConfirmPruneVolumes string ConfirmPruneNetworks string PruningStatus string StopService string PressEnterToReturn string DetachFromContainerShortCut string StopAllContainers string RemoveAllContainers string ViewRestartOptions string ExecShell string RunCustomCommand string ViewBulkCommands string FilterList string OpenInBrowser string SortContainersByState string LogsTitle string ConfigTitle string EnvTitle string DockerComposeConfigTitle string StatsTitle string CreditsTitle string ContainerConfigTitle string ContainerEnvTitle string NothingToDisplay string NoContainerForService string CannotDisplayEnvVariables string No string Yes string LcNextScreenMode string LcPrevScreenMode string FilterPrompt string FocusProjects string FocusServices string FocusContainers string FocusImages string FocusVolumes string FocusNetworks string } func englishSet() TranslationSet { return TranslationSet{ PruningStatus: "pruning", RemovingStatus: "removing", RestartingStatus: "restarting", StartingStatus: "starting", StoppingStatus: "stopping", UppingServiceStatus: "upping service", UppingProjectStatus: "upping project", DowningStatus: "downing", PausingStatus: "pausing", RunningCustomCommandStatus: "running custom command", RunningBulkCommandStatus: "running bulk command", NoViewMachingNewLineFocusedSwitchStatement: "No view matching newLineFocused switch statement", ErrorOccurred: "An error occurred! Please create an issue at https://github.com/jesseduffield/lazydocker/issues", ConnectionFailed: "connection to docker client failed. You may need to restart the docker client", UnattachableContainerError: "Container does not support attaching. You must either run the service with the '-it' flag or use `stdin_open: true, tty: true` in the docker-compose.yml file", WaitingForContainerInfo: "Cannot proceed until docker gives us more information about the container. Please retry in a few moments.", CannotAttachStoppedContainerError: "You cannot attach to a stopped container, you need to start it first (which you can actually do with the 'r' key) (yes I'm too lazy to do this automatically for you) (pretty cool that I get to communicate one-on-one with you in the form of an error message though)", CannotAccessDockerSocketError: "Can't access docker socket at: unix:///var/run/docker.sock\nRun lazydocker as root or read https://docs.docker.com/install/linux/linux-postinstall/", CannotKillChildError: "Waited three seconds for child process to stop. There may be an orphan process that continues to run on your system.", Donate: "Donate", Confirm: "Confirm", Return: "return", FocusMain: "focus main panel", LcFilter: "filter list", Navigate: "navigate", Execute: "execute", Close: "close", Quit: "quit", Menu: "menu", MenuTitle: "Menu", Scroll: "scroll", OpenConfig: "open lazydocker config", EditConfig: "edit lazydocker config", Cancel: "cancel", Remove: "remove", HideStopped: "hide/show stopped containers", ForceRemove: "force remove", RemoveWithVolumes: "remove with volumes", RemoveService: "remove containers", UpService: "up service", Stop: "stop", Pause: "pause", Restart: "restart", Down: "down project", DownWithVolumes: "down project with volumes", Start: "start", Rebuild: "rebuild", Recreate: "recreate", PreviousContext: "previous tab", NextContext: "next tab", Attach: "attach", ViewLogs: "view logs", UpProject: "up project", DownProject: "down project", RemoveImage: "remove image", RemoveVolume: "remove volume", RemoveNetwork: "remove network", RemoveWithoutPrune: "remove without deleting untagged parents", RemoveWithoutPruneWithForce: "remove (forced) without deleting untagged parents", RemoveWithForce: "remove (forced)", PruneContainers: "prune exited containers", PruneVolumes: "prune unused volumes", PruneNetworks: "prune unused networks", PruneImages: "prune unused images", StopAllContainers: "stop all containers", RemoveAllContainers: "remove all containers (forced)", ViewRestartOptions: "view restart options", ExecShell: "exec shell", RunCustomCommand: "run predefined custom command", ViewBulkCommands: "view bulk commands", FilterList: "filter list", OpenInBrowser: "open in browser (first port is http)", SortContainersByState: "sort containers by state", GlobalTitle: "Global", MainTitle: "Main", ProjectTitle: "Project", ServicesTitle: "Services", ContainersTitle: "Containers", StandaloneContainersTitle: "Standalone Containers", ImagesTitle: "Images", VolumesTitle: "Volumes", NetworksTitle: "Networks", CustomCommandTitle: "Custom Command:", BulkCommandTitle: "Bulk Command:", ErrorTitle: "Error", LogsTitle: "Logs", ConfigTitle: "Config", EnvTitle: "Env", DockerComposeConfigTitle: "Docker-Compose Config", TopTitle: "Top", StatsTitle: "Stats", CreditsTitle: "About", ContainerConfigTitle: "Container Config", ContainerEnvTitle: "Container Env", NothingToDisplay: "Nothing to display", NoContainerForService: "No logs to show; service is not associated with a container", CannotDisplayEnvVariables: "Something went wrong while displaying environment variables", NoContainers: "No containers", NoContainer: "No container", NoImages: "No images", NoVolumes: "No volumes", NoNetworks: "No networks", NoServices: "No services", ConfirmQuit: "Are you sure you want to quit?", ConfirmUpProject: "Are you sure you want to 'up' your docker compose project?", MustForceToRemoveContainer: "You cannot remove a running container unless you force it. Do you want to force it?", NotEnoughSpace: "Not enough space to render panels", ConfirmPruneImages: "Are you sure you want to prune all unused images?", ConfirmPruneContainers: "Are you sure you want to prune all stopped containers?", ConfirmStopContainers: "Are you sure you want to stop all containers?", ConfirmRemoveContainers: "Are you sure you want to remove all containers?", ConfirmPruneVolumes: "Are you sure you want to prune all unused volumes?", ConfirmPruneNetworks: "Are you sure you want to prune all unused networks?", StopService: "Are you sure you want to stop this service's containers?", StopContainer: "Are you sure you want to stop this container?", PressEnterToReturn: "Press enter to return to lazydocker (this prompt can be disabled in your config by setting `gui.returnImmediately: true`)", DetachFromContainerShortCut: "By default, to detach from the container press ctrl-p then ctrl-q", No: "no", Yes: "yes", LcNextScreenMode: "next screen mode (normal/half/fullscreen)", LcPrevScreenMode: "prev screen mode", FilterPrompt: "filter", FocusProjects: "focus projects panel", FocusServices: "focus services panel", FocusContainers: "focus containers panel", FocusImages: "focus images panel", FocusVolumes: "focus volumes panel", FocusNetworks: "focus networks panel", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/polish.go
pkg/i18n/polish.go
package i18n func polishSet() TranslationSet { return TranslationSet{ PruningStatus: "czyszczenie", RemovingStatus: "usuwanie", RestartingStatus: "restartowanie", StoppingStatus: "zatrzymywanie", RunningCustomCommandStatus: "uruchamianie własnej komendty", NoViewMachingNewLineFocusedSwitchStatement: "Żaden widok nie odpowiada instrukcji przełączenia newLineFocused", ErrorOccurred: "Wystąpił błąd! Proszę go zgłosić na https://github.com/jesseduffield/lazydocker/issues", ConnectionFailed: "Błąd połączenia z Dockerem. Być może należy go zrestartować.", UnattachableContainerError: "Kontener nie obsługuje przyczepiania (attach). Musisz albo użyć flag '-it', albo `stdin_open: true, tty: true` w pliku docker-compose.yml.", CannotAttachStoppedContainerError: "Nie można przyczepić się do zatrzymanego kontenera, należy go najpierw uruchomić (co można wykonać wciskając przycisk 'r')", CannotAccessDockerSocketError: "Nie udało się uzyskać dostępu do unix:///var/run/docker.sock\nUruchom program jako root lub przeczytaj https://docs.docker.com/install/linux/linux-postinstall/", Donate: "Dotacja", Confirm: "Potwierdź", Return: "powrót", FocusMain: "skup na głównym panelu", Navigate: "nawigowanie", Execute: "wykonaj", Close: "zamknij", Menu: "menu", MenuTitle: "Menu", Scroll: "przewiń", OpenConfig: "otwórz konfigurację", EditConfig: "edytuj konfigurację", Cancel: "anuluj", Remove: "usuń", ForceRemove: "usuń siłą", RemoveWithVolumes: "usuń z wolumenami", RemoveService: "usuń kontenery", Stop: "zatrzymaj", Restart: "restartuj", Rebuild: "przebuduj", Recreate: "odtwórz", PreviousContext: "poprzednia zakładka", NextContext: "następna zakładka", Attach: "przyczep", ViewLogs: "pokaż logi", RemoveImage: "usuń obraz", RemoveVolume: "usuń wolumen", RemoveNetwork: "usuń sieci", RemoveWithoutPrune: "usuń bez kasowania nieoznaczonych rodziców", PruneContainers: "wyczyść kontenery", PruneVolumes: "wyczyść nieużywane wolumeny", PruneNetworks: "wyczyść nieużywane sieci", PruneImages: "wyczyść nieużywane obrazy", ViewRestartOptions: "pokaż opcje restartu", RunCustomCommand: "wykonaj predefiniowaną własną komende", GlobalTitle: "Globalne", MainTitle: "Główne", ProjectTitle: "Projekt", ServicesTitle: "Serwisy", ContainersTitle: "Kontenery", StandaloneContainersTitle: "Kontenery samodzielne", ImagesTitle: "Obrazy", VolumesTitle: "Wolumeny", NetworksTitle: "Sieci", CustomCommandTitle: "Własna komenda:", ErrorTitle: "Błąd", LogsTitle: "Logi", ConfigTitle: "Konfiguracja", EnvTitle: "Env", DockerComposeConfigTitle: "Konfiguracja docker-compose", TopTitle: "Top", StatsTitle: "Staty", CreditsTitle: "O", ContainerConfigTitle: "Konfiguracja kontenera", ContainerEnvTitle: "Container Env", NothingToDisplay: "Nothing to display", CannotDisplayEnvVariables: "Something went wrong while displaying environment variables", NoContainers: "Brak kontenerów", NoContainer: "Brak kontenera", NoImages: "Brak obrazów", NoVolumes: "Brak wolumenów", NoNetworks: "Brak sieci", ConfirmQuit: "Na pewno chcesz wyjść?", MustForceToRemoveContainer: "Nie możesz usunąć uruchomionego kontenera dopóki nie zrobisz tego siłą. Chcesz wykonać to z siłą?", NotEnoughSpace: "Niedostateczna ilość miejsca do wyświetlenia paneli", ConfirmPruneImages: "Na pewno wyczyścić wszystkie nieużywane obrazy?", ConfirmPruneContainers: "Na pewno wyczyścić wszystkie nieuruchomione kontenery?", ConfirmPruneVolumes: "Na pewno wyczyścić wszystkie nieużywane wolumeny?", ConfirmPruneNetworks: "Na pewno wyczyścić wszystkie nieużywane sieci?", StopService: "Na pewno zatrzymać kontenery tego serwisu?", StopContainer: "Na pewno zatrzymać ten kontener?", PressEnterToReturn: "Wciśnij enter aby powrócić do lazydockera (ten komunikat może być wyłączony w konfiguracji poprzez ustawienie `gui.returnImmediately: true`)", DetachFromContainerShortCut: "Domyślnie, aby odłączyć się od kontenera, naciśnij ctrl-p, a następnie ctrl-q", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/i18n/german.go
pkg/i18n/german.go
package i18n func germanSet() TranslationSet { return TranslationSet{ PruningStatus: "zerstören", RemovingStatus: "entfernen", RestartingStatus: "neustarten", StoppingStatus: "anhalten", RunningCustomCommandStatus: "führt benutzerdefinierten Befehl aus", NoViewMachingNewLineFocusedSwitchStatement: "No view matching newLineFocused switch statement", ErrorOccurred: "Es ist ein Fehler aufgetreten! Bitte erstelle ein Issue hier: https://github.com/jesseduffield/lazydocker/issues", ConnectionFailed: "Verbindung zum Docker Client fehlgeschlagen. Du musst ggf. den Docker Client neustarten.", UnattachableContainerError: "Der Container bietet keine Unterstützung für das Anbinden. Du musst den Dienst entweder mit der '-it' Flagge benutzen oder `stdin_open: true, tty: true` in der docker-compose.yml Datei setzen.", CannotAttachStoppedContainerError: "Du kannst keinen angehaltenen Container anbinden. Du musst ihn erst starten (was du tun kannst, indem du 'r' drückst), (ja, ich bin zu faul um das zu automatisieren) (aber ist schon cool, dass ich so eine Konversation durch eine Fehlermeldung mit dir führen kann)", CannotAccessDockerSocketError: "Kann nicht auf den Socket zugreifen: unix:///var/run/docker.sock\nFühre lazydocker als root aus oder lese https://docs.docker.com/install/linux/linux-postinstall/", Donate: "Spenden", Confirm: "Bestätigen", Return: "zurück", FocusMain: "fokussieren aufs Hauptpanel", Navigate: "navigieren", Execute: "ausführen", Close: "schließen", Menu: "menü", MenuTitle: "Menü", Scroll: "scrollen", OpenConfig: "öffne lazydocker Konfiguration", EditConfig: "bearbeite lazydocker Konfiguration", Cancel: "abbrechen", Remove: "entfernen", ForceRemove: "Entfernen erzwingen", RemoveWithVolumes: "entferne mit Volumes", RemoveService: "entferne Container", Stop: "anhalten", Restart: "neustarten", Rebuild: "neubauen", Recreate: "neuerstellen", PreviousContext: "vorheriges Tab", NextContext: "nächstes Tab", Attach: "anbinden", ViewLogs: "zeige Protokolle", RemoveImage: "entferne Image", RemoveVolume: "entferne Volume", RemoveNetwork: "entferne Netzwerk", RemoveWithoutPrune: "entfernen, ohne die unmarkierten Eltern zu entfernen", PruneContainers: "entferne verlassene Container", PruneVolumes: "entferne unbenutzte Volumes", PruneNetworks: "entferne unbenutzte Netzwerk", PruneImages: "entferne unbenutzte Images", ViewRestartOptions: "zeige Neustartoptionen", RunCustomCommand: "führe vordefinierten benutzerdefinierten Befehl aus", GlobalTitle: "Global", MainTitle: "Haupt", ProjectTitle: "Projekt", ServicesTitle: "Dienste", ContainersTitle: "Container", StandaloneContainersTitle: "Alleinstehende Container", ImagesTitle: "Images", VolumesTitle: "Volumes", NetworksTitle: "Netzwerk", CustomCommandTitle: "Benutzerdefinierter Befehl", ErrorTitle: "Fehler", LogsTitle: "Protokoll", ConfigTitle: "Konfiguration", EnvTitle: "Env", DockerComposeConfigTitle: "Docker-Compose Konfiguration", TopTitle: "Top", StatsTitle: "Statistiken", CreditsTitle: "Über Uns", ContainerConfigTitle: "Container Konfiguration", ContainerEnvTitle: "Container Env", NothingToDisplay: "Nothing to display", CannotDisplayEnvVariables: "Something went wrong while displaying environment variables", NoContainers: "Keine Container", NoContainer: "Kein Container", NoImages: "Keine Images", NoVolumes: "Keine Volumes", NoNetworks: "Keine Netzwerk", ConfirmQuit: "Bist du dir sicher, dass du verlassen möchtest?", MustForceToRemoveContainer: "Du kannst keinen Container entfernen, der noch ausgeführt wird außer du erzwingst es. Möchtest du es erzwingen?", NotEnoughSpace: "Nicht genug Platz um die Panel darzustellen", ConfirmPruneImages: "Bist du dir sicher, dass du alle unbenutzten Images entfernen möchtest?", ConfirmPruneContainers: "Bist du dir sicher, dass du alle angehaltenen Container entfernen möchtes?", ConfirmPruneVolumes: "Bist du dir sicher, dass du alle unbenutzen Volumes entfernen möchtest?", ConfirmPruneNetworks: "Bist du dir sicher, dass du alle unbenutzen Netzwerk entfernen möchtest?", StopService: "Bist du dir sicher, dass du den Dienst dieses Containers anhalten möchtest?", StopContainer: "Bist du dir sicher, dass du den Container anhalten möchtest?", PressEnterToReturn: "Drücke Eingabe um zu lazydocker zurückzukehren. (Diese Nachfrage kann in Deiner Konfiguration deaktiviert werden, indem du folgenden Wert setzt: `gui.returnImmediately: true`)", DetachFromContainerShortCut: "Um sich vom Container zu trennen, drücken Sie standardmäßig ctrl-p ​​und dann ctrl-q", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/utils/utils.go
pkg/utils/utils.go
package utils import ( "bytes" "encoding/json" "fmt" "html/template" "io" "math" "regexp" "sort" "strings" "time" "github.com/go-errors/errors" "github.com/jesseduffield/gocui" "github.com/mattn/go-runewidth" // "github.com/jesseduffield/yaml" "github.com/fatih/color" "github.com/goccy/go-yaml" "github.com/goccy/go-yaml/lexer" "github.com/goccy/go-yaml/printer" ) // SplitLines takes a multiline string and splits it on newlines // currently we are also stripping \r's which may have adverse effects for // windows users (but no issues have been raised yet) func SplitLines(multilineString string) []string { multilineString = strings.Replace(multilineString, "\r", "", -1) if multilineString == "" || multilineString == "\n" { return make([]string, 0) } lines := strings.Split(multilineString, "\n") if lines[len(lines)-1] == "" { return lines[:len(lines)-1] } return lines } // WithPadding pads a string as much as you want func WithPadding(str string, padding int) string { uncoloredStr := Decolorise(str) if padding < runewidth.StringWidth(uncoloredStr) { return str } return str + strings.Repeat(" ", padding-runewidth.StringWidth(uncoloredStr)) } // ColoredString takes a string and a colour attribute and returns a colored // string with that attribute func ColoredString(str string, colorAttribute color.Attribute) string { // fatih/color does not have a color.Default attribute, so unless we fork that repo the only way for us to express that we don't want to color a string different to the terminal's default is to not call the function in the first place, but that's annoying when you want a streamlined code path. Because I'm too lazy to fork the repo right now, we'll just assume that by FgWhite you really mean Default, for the sake of supporting users with light themed terminals. if colorAttribute == color.FgWhite { return str } colour := color.New(colorAttribute) return ColoredStringDirect(str, colour) } // ColoredYamlString takes an YAML formatted string and returns a colored string // with colors hardcoded as: // keys: cyan // Booleans: magenta // Numbers: yellow // Strings: green func ColoredYamlString(str string) string { format := func(attr color.Attribute) string { return fmt.Sprintf("%s[%dm", "\x1b", attr) } tokens := lexer.Tokenize(str) var p printer.Printer p.Bool = func() *printer.Property { return &printer.Property{ Prefix: format(color.FgMagenta), Suffix: format(color.Reset), } } p.Number = func() *printer.Property { return &printer.Property{ Prefix: format(color.FgYellow), Suffix: format(color.Reset), } } p.MapKey = func() *printer.Property { return &printer.Property{ Prefix: format(color.FgCyan), Suffix: format(color.Reset), } } p.String = func() *printer.Property { return &printer.Property{ Prefix: format(color.FgGreen), Suffix: format(color.Reset), } } return p.PrintTokens(tokens) } // MultiColoredString takes a string and an array of colour attributes and returns a colored // string with those attributes func MultiColoredString(str string, colorAttribute ...color.Attribute) string { colour := color.New(colorAttribute...) return ColoredStringDirect(str, colour) } // ColoredStringDirect used for aggregating a few color attributes rather than // just sending a single one func ColoredStringDirect(str string, colour *color.Color) string { return colour.SprintFunc()(fmt.Sprint(str)) } // NormalizeLinefeeds - Removes all Windows and Mac style line feeds func NormalizeLinefeeds(str string) string { str = strings.Replace(str, "\r\n", "\n", -1) str = strings.Replace(str, "\r", "", -1) return str } // Loader dumps a string to be displayed as a loader func Loader() string { characters := "|/-\\" now := time.Now() nanos := now.UnixNano() index := nanos / 50000000 % int64(len(characters)) return characters[index : index+1] } // ResolvePlaceholderString populates a template with values func ResolvePlaceholderString(str string, arguments map[string]string) string { for key, value := range arguments { str = strings.Replace(str, "{{"+key+"}}", value, -1) } return str } // Max returns the maximum of two integers func Max(x, y int) int { if x > y { return x } return y } // RenderTable takes an array of string arrays and returns a table containing the values func RenderTable(rows [][]string) (string, error) { if len(rows) == 0 { return "", nil } if !displayArraysAligned(rows) { return "", errors.New("Each item must return the same number of strings to display") } columnPadWidths := getPadWidths(rows) paddedDisplayRows := getPaddedDisplayStrings(rows, columnPadWidths) return strings.Join(paddedDisplayRows, "\n"), nil } // Decolorise strips a string of color func Decolorise(str string) string { re := regexp.MustCompile(`\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mK]`) return re.ReplaceAllString(str, "") } func getPadWidths(rows [][]string) []int { if len(rows[0]) <= 1 { return []int{} } columnPadWidths := make([]int, len(rows[0])-1) for i := range columnPadWidths { for _, cells := range rows { uncoloredCell := Decolorise(cells[i]) if runewidth.StringWidth(uncoloredCell) > columnPadWidths[i] { columnPadWidths[i] = runewidth.StringWidth(uncoloredCell) } } } return columnPadWidths } func getPaddedDisplayStrings(rows [][]string, columnPadWidths []int) []string { paddedDisplayRows := make([]string, len(rows)) for i, cells := range rows { for j, columnPadWidth := range columnPadWidths { paddedDisplayRows[i] += WithPadding(cells[j], columnPadWidth) + " " } paddedDisplayRows[i] += cells[len(columnPadWidths)] } return paddedDisplayRows } // displayArraysAligned returns true if every string array returned from our // list of displayables has the same length func displayArraysAligned(stringArrays [][]string) bool { for _, strings := range stringArrays { if len(strings) != len(stringArrays[0]) { return false } } return true } func FormatBinaryBytes(b int) string { n := float64(b) units := []string{"B", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} for _, unit := range units { if n > math.Pow(2, 10) { n /= math.Pow(2, 10) } else { val := fmt.Sprintf("%.2f%s", n, unit) if val == "0.00B" { return "0B" } return val } } return "a lot" } func FormatDecimalBytes(b int) string { n := float64(b) units := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} for _, unit := range units { if n > math.Pow(10, 3) { n /= math.Pow(10, 3) } else { val := fmt.Sprintf("%.2f%s", n, unit) if val == "0.00B" { return "0B" } return val } } return "a lot" } func ApplyTemplate(str string, object interface{}) string { var buf bytes.Buffer _ = template.Must(template.New("").Parse(str)).Execute(&buf, object) return buf.String() } // GetGocuiAttribute gets the gocui color attribute from the string func GetGocuiAttribute(key string) gocui.Attribute { colorMap := map[string]gocui.Attribute{ "default": gocui.ColorDefault, "black": gocui.ColorBlack, "red": gocui.ColorRed, "green": gocui.ColorGreen, "yellow": gocui.ColorYellow, "blue": gocui.ColorBlue, "magenta": gocui.ColorMagenta, "cyan": gocui.ColorCyan, "white": gocui.ColorWhite, "bold": gocui.AttrBold, "reverse": gocui.AttrReverse, "underline": gocui.AttrUnderline, } value, present := colorMap[key] if present { return value } return gocui.ColorDefault } // GetColorAttribute gets the color attribute from the string func GetColorAttribute(key string) color.Attribute { colorMap := map[string]color.Attribute{ "default": color.FgWhite, "black": color.FgBlack, "red": color.FgRed, "green": color.FgGreen, "yellow": color.FgYellow, "blue": color.FgBlue, "magenta": color.FgMagenta, "cyan": color.FgCyan, "white": color.FgWhite, "bold": color.Bold, "underline": color.Underline, } value, present := colorMap[key] if present { return value } return color.FgWhite } // WithShortSha returns a command but with a shorter SHA. in the terminal we're all used to 10 character SHAs but under the hood they're actually 64 characters long. No need including all the characters when we're just displaying a command func WithShortSha(str string) string { split := strings.Split(str, " ") for i, word := range split { // good enough proxy for now if len(word) == 64 { split[i] = word[0:10] } } return strings.Join(split, " ") } // FormatMapItem is for displaying items in a map func FormatMapItem(padding int, k string, v interface{}) string { return fmt.Sprintf("%s%s %v\n", strings.Repeat(" ", padding), ColoredString(k+":", color.FgYellow), fmt.Sprintf("%v", v)) } // FormatMap is for displaying a map func FormatMap(padding int, m map[string]string) string { if len(m) == 0 { return "none\n" } output := "\n" keys := make([]string, 0, len(m)) for key := range m { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { output += FormatMapItem(padding, key, m[key]) } return output } type multiErr []error func (m multiErr) Error() string { var b bytes.Buffer b.WriteString("encountered multiple errors:") for _, err := range m { b.WriteString("\n\t... " + err.Error()) } return b.String() } func CloseMany(closers []io.Closer) error { errs := make([]error, 0, len(closers)) for _, c := range closers { err := c.Close() if err != nil { errs = append(errs, err) } } if len(errs) > 0 { return multiErr(errs) } return nil } func SafeTruncate(str string, limit int) string { if len(str) > limit { return str[0:limit] } else { return str } } func IsValidHexValue(v string) bool { if len(v) != 4 && len(v) != 7 { return false } if v[0] != '#' { return false } for _, char := range v[1:] { switch char { case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F': continue default: return false } } return true } // Style used on menu items that open another menu func OpensMenuStyle(str string) string { return ColoredString(fmt.Sprintf("%s...", str), color.FgMagenta) } // MarshalIntoYaml gets any json-tagged data and marshal it into yaml saving original json structure. // Useful for structs from 3rd-party libs without yaml tags. func MarshalIntoYaml(data interface{}) ([]byte, error) { return marshalIntoFormat(data, "yaml") } func marshalIntoFormat(data interface{}, format string) ([]byte, error) { // First marshal struct->json to get the resulting structure declared by json tags dataJSON, err := json.MarshalIndent(data, "", " ") if err != nil { return nil, err } switch format { case "json": return dataJSON, err case "yaml": // Use Unmarshal->Marshal hack to convert json into yaml with the original structure preserved var dataMirror yaml.MapSlice if err := yaml.Unmarshal(dataJSON, &dataMirror); err != nil { return nil, err } return yaml.Marshal(dataMirror) default: return nil, errors.New(fmt.Sprintf("Unsupported detailization format: %s", format)) } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/utils/utils_test.go
pkg/utils/utils_test.go
package utils import ( "testing" "github.com/go-errors/errors" "github.com/stretchr/testify/assert" ) // TestSplitLines is a function. func TestSplitLines(t *testing.T) { type scenario struct { multilineString string expected []string } scenarios := []scenario{ { "", []string{}, }, { "\n", []string{}, }, { "hello world !\nhello universe !\n", []string{ "hello world !", "hello universe !", }, }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, SplitLines(s.multilineString)) } } // TestWithPadding is a function. func TestWithPadding(t *testing.T) { type scenario struct { str string padding int expected string } scenarios := []scenario{ { "hello world !", 1, "hello world !", }, { "hello world !", 14, "hello world ! ", }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, WithPadding(s.str, s.padding)) } } // TestNormalizeLinefeeds is a function. func TestNormalizeLinefeeds(t *testing.T) { type scenario struct { byteArray []byte expected []byte } scenarios := []scenario{ { // \r\n []byte{97, 115, 100, 102, 13, 10}, []byte{97, 115, 100, 102, 10}, }, { // bash\r\nblah []byte{97, 115, 100, 102, 13, 10, 97, 115, 100, 102}, []byte{97, 115, 100, 102, 10, 97, 115, 100, 102}, }, { // \r []byte{97, 115, 100, 102, 13}, []byte{97, 115, 100, 102}, }, { // \n []byte{97, 115, 100, 102, 10}, []byte{97, 115, 100, 102, 10}, }, } for _, s := range scenarios { assert.EqualValues(t, string(s.expected), NormalizeLinefeeds(string(s.byteArray))) } } // TestResolvePlaceholderString is a function. func TestResolvePlaceholderString(t *testing.T) { type scenario struct { templateString string arguments map[string]string expected string } scenarios := []scenario{ { "", map[string]string{}, "", }, { "hello", map[string]string{}, "hello", }, { "hello {{arg}}", map[string]string{}, "hello {{arg}}", }, { "hello {{arg}}", map[string]string{"arg": "there"}, "hello there", }, { "hello", map[string]string{"arg": "there"}, "hello", }, { "{{nothing}}", map[string]string{"nothing": ""}, "", }, { "{{}} {{ this }} { should not throw}} an {{{{}}}} error", map[string]string{ "blah": "blah", "this": "won't match", }, "{{}} {{ this }} { should not throw}} an {{{{}}}} error", }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, ResolvePlaceholderString(s.templateString, s.arguments)) } } // TestDisplayArraysAligned is a function. func TestDisplayArraysAligned(t *testing.T) { type scenario struct { input [][]string expected bool } scenarios := []scenario{ { [][]string{{"", ""}, {"", ""}}, true, }, { [][]string{{""}, {"", ""}}, false, }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, displayArraysAligned(s.input)) } } // TestGetPaddedDisplayStrings is a function. func TestGetPaddedDisplayStrings(t *testing.T) { type scenario struct { stringArrays [][]string padWidths []int expected []string } scenarios := []scenario{ { [][]string{{"a", "b"}, {"c", "d"}}, []int{1}, []string{"a b", "c d"}, }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, getPaddedDisplayStrings(s.stringArrays, s.padWidths)) } } // TestGetPadWidths is a function. func TestGetPadWidths(t *testing.T) { type scenario struct { stringArrays [][]string expected []int } scenarios := []scenario{ { [][]string{{""}, {""}}, []int{}, }, { [][]string{{"a"}, {""}}, []int{}, }, { [][]string{{"aa", "b", "ccc"}, {"c", "d", "e"}}, []int{2, 1}, }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, getPadWidths(s.stringArrays)) } } func TestRenderTable(t *testing.T) { type scenario struct { input [][]string expected string expectedErr error } scenarios := []scenario{ { input: [][]string{{"a", "b"}, {"c", "d"}}, expected: "a b\nc d", expectedErr: nil, }, { input: [][]string{{"aaaa", "b"}, {"c", "d"}}, expected: "aaaa b\nc d", expectedErr: nil, }, { input: [][]string{{"a"}, {"c", "d"}}, expected: "", expectedErr: errors.New("Each item must return the same number of strings to display"), }, } for _, s := range scenarios { output, err := RenderTable(s.input) assert.EqualValues(t, s.expected, output) if s.expectedErr != nil { assert.EqualError(t, err, s.expectedErr.Error()) } else { assert.NoError(t, err) } } } func TestMarshalIntoFormat(t *testing.T) { type innerData struct { Foo int `json:"foo"` Bar string `json:"bar"` Baz bool `json:"baz"` } type data struct { Qux int `json:"quz"` Quux innerData `json:"quux"` } type scenario struct { input interface{} format string expected []byte expectedErr error } scenarios := []scenario{ { input: data{1, innerData{2, "foo", true}}, format: "json", expected: []byte(`{ "quz": 1, "quux": { "foo": 2, "bar": "foo", "baz": true } }`), expectedErr: nil, }, { input: data{1, innerData{2, "foo", true}}, format: "yaml", expected: []byte(`quz: 1 quux: bar: foo baz: true foo: 2 `), expectedErr: nil, }, { input: data{1, innerData{2, "foo", true}}, format: "xml", expected: nil, expectedErr: errors.New("Unsupported detailization format: xml"), }, } for _, s := range scenarios { output, err := marshalIntoFormat(s.input, s.format) assert.EqualValues(t, s.expected, output) if s.expectedErr != nil { assert.EqualError(t, err, s.expectedErr.Error()) } else { assert.NoError(t, err) } } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/config/config_windows.go
pkg/config/config_windows.go
package config // GetPlatformDefaultConfig gets the defaults for the platform func GetPlatformDefaultConfig() OSConfig { return OSConfig{ OpenCommand: `cmd /c "start "" {{filename}}"`, OpenLinkCommand: `cmd /c "start "" {{link}}"`, } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/config/app_config_test.go
pkg/config/app_config_test.go
package config import ( "os" "testing" "github.com/jesseduffield/yaml" ) func TestDockerComposeCommandNoFiles(t *testing.T) { composeFiles := []string{} conf, err := NewAppConfig("name", "version", "commit", "date", "buildSource", false, composeFiles, "projectDir") if err != nil { t.Fatalf("Unexpected error: %s", err) } actual := conf.UserConfig.CommandTemplates.DockerCompose expected := "docker compose" if actual != expected { t.Fatalf("Expected %s but got %s", expected, actual) } } func TestDockerComposeCommandSingleFile(t *testing.T) { composeFiles := []string{"one.yml"} conf, err := NewAppConfig("name", "version", "commit", "date", "buildSource", false, composeFiles, "projectDir") if err != nil { t.Fatalf("Unexpected error: %s", err) } actual := conf.UserConfig.CommandTemplates.DockerCompose expected := "docker compose -f one.yml" if actual != expected { t.Fatalf("Expected %s but got %s", expected, actual) } } func TestDockerComposeCommandMultipleFiles(t *testing.T) { composeFiles := []string{"one.yml", "two.yml", "three.yml"} conf, err := NewAppConfig("name", "version", "commit", "date", "buildSource", false, composeFiles, "projectDir") if err != nil { t.Fatalf("Unexpected error: %s", err) } actual := conf.UserConfig.CommandTemplates.DockerCompose expected := "docker compose -f one.yml -f two.yml -f three.yml" if actual != expected { t.Fatalf("Expected %s but got %s", expected, actual) } } func TestWritingToConfigFile(t *testing.T) { // init the AppConfig emptyComposeFiles := []string{} conf, err := NewAppConfig("name", "version", "commit", "date", "buildSource", false, emptyComposeFiles, "projectDir") if err != nil { t.Fatalf("Unexpected error: %s", err) } testFn := func(t *testing.T, ac *AppConfig, newValue bool) { t.Helper() updateFn := func(uc *UserConfig) error { uc.ConfirmOnQuit = newValue return nil } err = ac.WriteToUserConfig(updateFn) if err != nil { t.Fatalf("Unexpected error: %s", err) } file, err := os.OpenFile(ac.ConfigFilename(), os.O_RDONLY, 0o660) if err != nil { t.Fatalf("Unexpected error: %s", err) } sampleUC := UserConfig{} err = yaml.NewDecoder(file).Decode(&sampleUC) if err != nil { t.Fatalf("Unexpected error: %s", err) } err = file.Close() if err != nil { t.Fatalf("Unexpected error: %s", err) } if sampleUC.ConfirmOnQuit != newValue { t.Fatalf("Got %v, Expected %v\n", sampleUC.ConfirmOnQuit, newValue) } } // insert value into an empty file testFn(t, conf, true) // modifying an existing file that already has 'ConfirmOnQuit' testFn(t, conf, false) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/config/config_linux.go
pkg/config/config_linux.go
package config // GetPlatformDefaultConfig gets the defaults for the platform func GetPlatformDefaultConfig() OSConfig { return OSConfig{ OpenCommand: `sh -c "xdg-open {{filename}} >/dev/null"`, OpenLinkCommand: `sh -c "xdg-open {{link}} >/dev/null"`, } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/config/config_default_platform.go
pkg/config/config_default_platform.go
//go:build !windows && !linux // +build !windows,!linux package config // GetPlatformDefaultConfig gets the defaults for the platform func GetPlatformDefaultConfig() OSConfig { return OSConfig{ OpenCommand: "open {{filename}}", OpenLinkCommand: "open {{link}}", } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/config/app_config.go
pkg/config/app_config.go
// Package config handles all the user-configuration. The fields here are // all in PascalCase but in your actual config.yml they'll be in camelCase. // You can view the default config with `lazydocker --config`. // You can open your config file by going to the status panel (using left-arrow) // and pressing 'o'. // You can directly edit the file (e.g. in vim) by pressing 'e' instead. // To see the final config after your user-specific options have been merged // with the defaults, go to the 'about' tab in the status panel. // Because of the way we merge your user config with the defaults you may need // to be careful: if for example you set a `commandTemplates:` yaml key but then // give it no child values, it will scrap all of the defaults and the app will // probably crash. package config import ( "os" "path/filepath" "strings" "time" "github.com/OpenPeeDeeP/xdg" "github.com/jesseduffield/yaml" ) // UserConfig holds all of the user-configurable options type UserConfig struct { // Gui is for configuring visual things like colors and whether we show or // hide things Gui GuiConfig `yaml:"gui,omitempty"` // ConfirmOnQuit when enabled prompts you to confirm you want to quit when you // hit esc or q when no confirmation panels are open ConfirmOnQuit bool `yaml:"confirmOnQuit,omitempty"` // Logs determines how we render/filter a container's logs Logs LogsConfig `yaml:"logs,omitempty"` // CommandTemplates determines what commands actually get called when we run // certain commands CommandTemplates CommandTemplatesConfig `yaml:"commandTemplates,omitempty"` // CustomCommands determines what shows up in your custom commands menu when // you press 'c'. You can use go templates to access three items on the // struct: the DockerCompose command (defaulted to 'docker-compose'), the // Service if present, and the Container if present. The struct types for // those are found in the commands package CustomCommands CustomCommands `yaml:"customCommands,omitempty"` // BulkCommands are commands that apply to all items in a panel e.g. // killing all containers, stopping all services, or pruning all images BulkCommands CustomCommands `yaml:"bulkCommands,omitempty"` // OS determines what defaults are set for opening files and links OS OSConfig `yaml:"oS,omitempty"` // Stats determines how long lazydocker will gather container stats for, and // what stat info to graph Stats StatsConfig `yaml:"stats,omitempty"` // Replacements determines how we render an item's info Replacements Replacements `yaml:"replacements,omitempty"` // For demo purposes: any list item with one of these strings as a substring // will be filtered out and not displayed. // Not documented because it's subject to change Ignore []string `yaml:"ignore,omitempty"` } // ThemeConfig is for setting the colors of panels and some text. type ThemeConfig struct { ActiveBorderColor []string `yaml:"activeBorderColor,omitempty"` InactiveBorderColor []string `yaml:"inactiveBorderColor,omitempty"` SelectedLineBgColor []string `yaml:"selectedLineBgColor,omitempty"` OptionsTextColor []string `yaml:"optionsTextColor,omitempty"` } // GuiConfig is for configuring visual things like colors and whether we show or // hide things type GuiConfig struct { // ScrollHeight determines how many characters you scroll at a time when // scrolling the main panel ScrollHeight int `yaml:"scrollHeight,omitempty"` // Language determines which language the GUI displayed. Language string `yaml:"language,omitempty"` // ScrollPastBottom determines whether you can scroll past the bottom of the // main view ScrollPastBottom bool `yaml:"scrollPastBottom,omitempty"` // IgnoreMouseEvents is for when you do not want to use your mouse to interact // with anything IgnoreMouseEvents bool `yaml:"mouseEvents,omitempty"` // Theme determines what colors and color attributes your panel borders have. // I always set inactiveBorderColor to black because in my terminal it's more // of a grey, but that doesn't work in your average terminal. I highly // recommended finding a combination that works for you Theme ThemeConfig `yaml:"theme,omitempty"` // ShowAllContainers determines whether the Containers panel contains all the // containers returned by `docker ps -a`, or just those containers that aren't // directly linked to a service. It is probably desirable to enable this if // you have multiple containers per service, but otherwise it can cause a lot // of clutter ShowAllContainers bool `yaml:"showAllContainers,omitempty"` // ReturnImmediately determines whether you get the 'press enter to return to // lazydocker' message after a subprocess has completed. You would set this to // true if you often want to see the output of subprocesses before returning // to lazydocker. I would default this to false but then people who want it // set to true won't even know the config option exists. ReturnImmediately bool `yaml:"returnImmediately,omitempty"` // WrapMainPanel determines whether we use word wrap on the main panel WrapMainPanel bool `yaml:"wrapMainPanel,omitempty"` // LegacySortContainers determines if containers should be sorted using legacy approach. // By default, containers are now sorted by status. This setting allows users to // use legacy behaviour instead. LegacySortContainers bool `yaml:"legacySortContainers,omitempty"` // If 0.333, then the side panels will be 1/3 of the screen's width SidePanelWidth float64 `yaml:"sidePanelWidth"` // Determines whether we show the bottom line (the one containing keybinding // info and the status of the app). ShowBottomLine bool `yaml:"showBottomLine"` // When true, increases vertical space used by focused side panel, // creating an accordion effect ExpandFocusedSidePanel bool `yaml:"expandFocusedSidePanel"` // ScreenMode allow user to specify which screen mode will be used on startup ScreenMode string `yaml:"screenMode,omitempty"` // Determines the style of the container status and container health display in the // containers panel. "long": full words (default), "short": one or two characters, // "icon": unicode emoji. ContainerStatusHealthStyle string `yaml:"containerStatusHealthStyle"` // Window border style. // One of 'rounded' (default) | 'single' | 'double' | 'hidden' Border string `yaml:"border"` } // CommandTemplatesConfig determines what commands actually get called when we // run certain commands type CommandTemplatesConfig struct { // RestartService is for restarting a service. docker-compose restart {{ // .Service.Name }} works but I prefer docker-compose up --force-recreate {{ // .Service.Name }} RestartService string `yaml:"restartService,omitempty"` // StartService is just like the above but for starting StartService string `yaml:"startService,omitempty"` // UpService ups the service (creates and starts) UpService string `yaml:"upService,omitempty"` // Runs "docker-compose up -d" Up string `yaml:"up,omitempty"` // downs everything Down string `yaml:"down,omitempty"` // downs and removes volumes DownWithVolumes string `yaml:"downWithVolumes,omitempty"` // DockerCompose is for your docker-compose command. You may want to combine a // few different docker-compose.yml files together, in which case you can set // this to "docker compose -f foo/docker-compose.yml -f // bah/docker-compose.yml". The reason that the other docker-compose command // templates all start with {{ .DockerCompose }} is so that they can make use // of whatever you've set in this value rather than you having to copy and // paste it to all the other commands DockerCompose string `yaml:"dockerCompose,omitempty"` // StopService is the command for stopping a service StopService string `yaml:"stopService,omitempty"` // ServiceLogs get the logs for a service. This is actually not currently // used; we just get the logs of the corresponding container. But we should // probably support explicitly returning the logs of the service when you've // selected the service, given that a service may have multiple containers. ServiceLogs string `yaml:"serviceLogs,omitempty"` // ViewServiceLogs is for when you want to view the logs of a service as a // subprocess. This defaults to having no filter, unlike the in-app logs // commands which will usually filter down to the last hour for the sake of // performance. ViewServiceLogs string `yaml:"viewServiceLogs,omitempty"` // RebuildService is the command for rebuilding a service. Defaults to // something along the lines of `{{ .DockerCompose }} up --build {{ // .Service.Name }}` RebuildService string `yaml:"rebuildService,omitempty"` // RecreateService is for force-recreating a service. I prefer this to // restarting a service because it will also restart any dependent services // and ensure they're running before trying to run the service at hand RecreateService string `yaml:"recreateService,omitempty"` // AllLogs is for showing what you get from doing `docker compose logs`. It // combines all the logs together AllLogs string `yaml:"allLogs,omitempty"` // ViewAllLogs is the command we use when you want to see all logs in a subprocess with no filtering ViewAllLogs string `yaml:"viewAlLogs,omitempty"` // DockerComposeConfig is the command for viewing the config of your docker // compose. It basically prints out the yaml from your docker-compose.yml // file(s) DockerComposeConfig string `yaml:"dockerComposeConfig,omitempty"` // CheckDockerComposeConfig is what we use to check whether we are in a // docker-compose context. If the command returns an error then we clearly // aren't in a docker-compose config and we then just hide the services panel // and only show containers CheckDockerComposeConfig string `yaml:"checkDockerComposeConfig,omitempty"` // ServiceTop is the command for viewing the processes under a given service ServiceTop string `yaml:"serviceTop,omitempty"` } // OSConfig contains config on the level of the os type OSConfig struct { // OpenCommand is the command for opening a file OpenCommand string `yaml:"openCommand,omitempty"` // OpenCommand is the command for opening a link OpenLinkCommand string `yaml:"openLinkCommand,omitempty"` } // GraphConfig specifies how to make a graph of recorded container stats type GraphConfig struct { // Min sets the minimum value that you want to display. If you want to set // this, you should also set MinType to "static". The reason for this is that // if Min == 0, it's not clear if it has not been set (given that the // zero-value of an int is 0) or if it's intentionally been set to 0. Min float64 `yaml:"min,omitempty"` // Max sets the maximum value that you want to display. If you want to set // this, you should also set MaxType to "static". The reason for this is that // if Max == 0, it's not clear if it has not been set (given that the // zero-value of an int is 0) or if it's intentionally been set to 0. Max float64 `yaml:"max,omitempty"` // Height sets the height of the graph in ascii characters Height int `yaml:"height,omitempty"` // Caption sets the caption of the graph. If you want to show CPU Percentage // you could set this to "CPU (%)" Caption string `yaml:"caption,omitempty"` // This is the path to the stat that you want to display. It is based on the // RecordedStats struct in container_stats.go, so feel free to look there to // see all the options available. Alternatively if you go into lazydocker and // go to the stats tab, you'll see that same struct in JSON format, so you can // just PascalCase the path and you'll have a valid path. E.g. // ClientStats.blkio_stats -> "ClientStats.BlkioStats" StatPath string `yaml:"statPath,omitempty"` // This determines the color of the graph. This can be any color attribute, // e.g. 'blue', 'green' Color string `yaml:"color,omitempty"` // MinType and MaxType are each one of "", "static". blank means the min/max // of the data set will be used. "static" means the min/max specified will be // used MinType string `yaml:"minType,omitempty"` // MaxType is just like MinType but for the max value MaxType string `yaml:"maxType,omitempty"` } // StatsConfig contains the stuff relating to stats and graphs type StatsConfig struct { // Graphs contains the configuration for the stats graphs we want to show in // the app Graphs []GraphConfig // MaxDuration tells us how long to collect stats for. Currently this defaults // to "5m" i.e. 5 minutes. MaxDuration time.Duration `yaml:"maxDuration,omitempty"` } // CustomCommands contains the custom commands that you might want to use on any // given service or container type CustomCommands struct { // Containers contains the custom commands for containers Containers []CustomCommand `yaml:"containers,omitempty"` // Services contains the custom commands for services Services []CustomCommand `yaml:"services,omitempty"` // Images contains the custom commands for images Images []CustomCommand `yaml:"images,omitempty"` // Volumes contains the custom commands for volumes Volumes []CustomCommand `yaml:"volumes,omitempty"` // Networks contains the custom commands for networks Networks []CustomCommand `yaml:"networks,omitempty"` } // Replacements contains the stuff relating to rendering a container's info type Replacements struct { // ImageNamePrefixes tells us how to replace a prefix in the Docker image name ImageNamePrefixes map[string]string `yaml:"imageNamePrefixes,omitempty"` } // CustomCommand is a template for a command we want to run against a service or // container type CustomCommand struct { // Name is the name of the command, purely for visual display Name string `yaml:"name"` // Attach tells us whether to switch to a subprocess to interact with the // called program, or just read its output. If Attach is set to false, the // command will run in the background. I'm open to the idea of having a third // option where the output plays in the main panel. Attach bool `yaml:"attach"` // Shell indicates whether to invoke the Command on a shell or not. // Example of a bash invoked command: `/bin/bash -c "{Command}". Shell bool `yaml:"shell"` // Command is the command we want to run. We can use the go templates here as // well. One example might be `{{ .DockerCompose }} exec {{ .Service.Name }} // /bin/sh` Command string `yaml:"command"` // ServiceNames is used to restrict this command to just one or more services. // An example might be 'rails migrate' for your rails api service(s). This // field has no effect on customcommands under the 'communications' part of // the customCommand config. ServiceNames []string `yaml:"serviceNames"` // InternalFunction is the name of a function inside lazydocker that we want to run, as opposed to a command-line command. This is only used internally and can't be configured by the user InternalFunction func() error `yaml:"-"` } type LogsConfig struct { Timestamps bool `yaml:"timestamps,omitempty"` Since string `yaml:"since,omitempty"` Tail string `yaml:"tail,omitempty"` } // GetDefaultConfig returns the application default configuration NOTE (to // contributors, not users): do not default a boolean to true, because false is // the boolean zero value and this will be ignored when parsing the user's // config func GetDefaultConfig() UserConfig { duration, err := time.ParseDuration("3m") if err != nil { panic(err) } return UserConfig{ Gui: GuiConfig{ ScrollHeight: 2, Language: "auto", ScrollPastBottom: false, IgnoreMouseEvents: false, Theme: ThemeConfig{ ActiveBorderColor: []string{"green", "bold"}, InactiveBorderColor: []string{"default"}, SelectedLineBgColor: []string{"blue"}, OptionsTextColor: []string{"blue"}, }, ShowAllContainers: false, ReturnImmediately: false, WrapMainPanel: true, LegacySortContainers: false, SidePanelWidth: 0.3333, ShowBottomLine: true, ExpandFocusedSidePanel: false, ScreenMode: "normal", ContainerStatusHealthStyle: "long", }, ConfirmOnQuit: false, Logs: LogsConfig{ Timestamps: false, Since: "60m", Tail: "", }, CommandTemplates: CommandTemplatesConfig{ DockerCompose: "docker compose", RestartService: "{{ .DockerCompose }} restart {{ .Service.Name }}", StartService: "{{ .DockerCompose }} start {{ .Service.Name }}", Up: "{{ .DockerCompose }} up -d", Down: "{{ .DockerCompose }} down", DownWithVolumes: "{{ .DockerCompose }} down --volumes", UpService: "{{ .DockerCompose }} up -d {{ .Service.Name }}", RebuildService: "{{ .DockerCompose }} up -d --build {{ .Service.Name }}", RecreateService: "{{ .DockerCompose }} up -d --force-recreate {{ .Service.Name }}", StopService: "{{ .DockerCompose }} stop {{ .Service.Name }}", ServiceLogs: "{{ .DockerCompose }} logs --since=60m --follow {{ .Service.Name }}", ViewServiceLogs: "{{ .DockerCompose }} logs --follow {{ .Service.Name }}", AllLogs: "{{ .DockerCompose }} logs --tail=300 --follow", ViewAllLogs: "{{ .DockerCompose }} logs", DockerComposeConfig: "{{ .DockerCompose }} config", CheckDockerComposeConfig: "{{ .DockerCompose }} config --quiet", ServiceTop: "{{ .DockerCompose }} top {{ .Service.Name }}", }, CustomCommands: CustomCommands{ Containers: []CustomCommand{}, Services: []CustomCommand{}, Images: []CustomCommand{}, Volumes: []CustomCommand{}, }, BulkCommands: CustomCommands{ Services: []CustomCommand{ { Name: "up", Command: "{{ .DockerCompose }} up -d", }, { Name: "up (attached)", Command: "{{ .DockerCompose }} up", Attach: true, }, { Name: "stop", Command: "{{ .DockerCompose }} stop", }, { Name: "pull", Command: "{{ .DockerCompose }} pull", Attach: true, }, { Name: "build", Command: "{{ .DockerCompose }} build --parallel --force-rm", Attach: true, }, { Name: "down", Command: "{{ .DockerCompose }} down", }, { Name: "down with volumes", Command: "{{ .DockerCompose }} down --volumes", }, { Name: "down with images", Command: "{{ .DockerCompose }} down --rmi all", }, { Name: "down with volumes and images", Command: "{{ .DockerCompose }} down --volumes --rmi all", }, }, Containers: []CustomCommand{}, Images: []CustomCommand{}, Volumes: []CustomCommand{}, }, OS: GetPlatformDefaultConfig(), Stats: StatsConfig{ MaxDuration: duration, Graphs: []GraphConfig{ { Caption: "CPU (%)", StatPath: "DerivedStats.CPUPercentage", Color: "cyan", }, { Caption: "Memory (%)", StatPath: "DerivedStats.MemoryPercentage", Color: "green", }, }, }, Replacements: Replacements{ ImageNamePrefixes: map[string]string{}, }, } } // AppConfig contains the base configuration fields required for lazydocker. type AppConfig struct { Debug bool `long:"debug" env:"DEBUG" default:"false"` Version string `long:"version" env:"VERSION" default:"unversioned"` Commit string `long:"commit" env:"COMMIT"` BuildDate string `long:"build-date" env:"BUILD_DATE"` Name string `long:"name" env:"NAME" default:"lazydocker"` BuildSource string `long:"build-source" env:"BUILD_SOURCE" default:""` UserConfig *UserConfig ConfigDir string ProjectDir string } // NewAppConfig makes a new app config func NewAppConfig(name, version, commit, date string, buildSource string, debuggingFlag bool, composeFiles []string, projectDir string) (*AppConfig, error) { configDir, err := findOrCreateConfigDir(name) if err != nil { return nil, err } userConfig, err := loadUserConfigWithDefaults(configDir) if err != nil { return nil, err } // Pass compose files as individual -f flags to docker compose if len(composeFiles) > 0 { userConfig.CommandTemplates.DockerCompose += " -f " + strings.Join(composeFiles, " -f ") } appConfig := &AppConfig{ Name: name, Version: version, Commit: commit, BuildDate: date, Debug: debuggingFlag || os.Getenv("DEBUG") == "TRUE", BuildSource: buildSource, UserConfig: userConfig, ConfigDir: configDir, ProjectDir: projectDir, } return appConfig, nil } func configDirForVendor(vendor string, projectName string) string { envConfigDir := os.Getenv("CONFIG_DIR") if envConfigDir != "" { return envConfigDir } configDirs := xdg.New(vendor, projectName) return configDirs.ConfigHome() } func configDir(projectName string) string { legacyConfigDirectory := configDirForVendor("jesseduffield", projectName) if _, err := os.Stat(legacyConfigDirectory); !os.IsNotExist(err) { return legacyConfigDirectory } configDirectory := configDirForVendor("", projectName) return configDirectory } func findOrCreateConfigDir(projectName string) (string, error) { folder := configDir(projectName) err := os.MkdirAll(folder, 0o755) if err != nil { return "", err } return folder, nil } func loadUserConfigWithDefaults(configDir string) (*UserConfig, error) { config := GetDefaultConfig() return loadUserConfig(configDir, &config) } func loadUserConfig(configDir string, base *UserConfig) (*UserConfig, error) { fileName := filepath.Join(configDir, "config.yml") if _, err := os.Stat(fileName); err != nil { if os.IsNotExist(err) { file, err := os.Create(fileName) if err != nil { return nil, err } file.Close() } else { return nil, err } } content, err := os.ReadFile(fileName) if err != nil { return nil, err } if err := yaml.Unmarshal(content, base); err != nil { return nil, err } return base, nil } // WriteToUserConfig allows you to set a value on the user config to be saved // note that if you set a zero-value, it may be ignored e.g. a false or 0 or // empty string this is because we are using the omitempty yaml directive so // that we don't write a heap of zero values to the user's config.yml func (c *AppConfig) WriteToUserConfig(updateConfig func(*UserConfig) error) error { userConfig, err := loadUserConfig(c.ConfigDir, &UserConfig{}) if err != nil { return err } if err := updateConfig(userConfig); err != nil { return err } file, err := os.OpenFile(c.ConfigFilename(), os.O_WRONLY|os.O_CREATE, 0o666) if err != nil { return err } return yaml.NewEncoder(file).Encode(userConfig) } // ConfigFilename returns the filename of the current config file func (c *AppConfig) ConfigFilename() string { return filepath.Join(c.ConfigDir, "config.yml") }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false