Compare commits

..

64 Commits

Author SHA1 Message Date
fatedier
7c8cbeb250 Merge pull request #3550 from fatedier/dev
release v0.51.2
2023-07-25 21:35:08 +08:00
fatedier
e9e12cf888 fix incorrect use of snappy pool (#3549) 2023-07-25 21:31:26 +08:00
fatedier
6430afcfa5 fix a goroutine leak issue caused by Login plugin timeout (#3547) 2023-07-25 15:12:40 +08:00
fatedier
3235addaaa update dependencies (#3539) 2023-07-21 14:34:44 +08:00
fatedier
46ff40543a update github actions (#3538) 2023-07-21 10:30:46 +08:00
fatedier
4fd6301577 Merge pull request #3537 from fatedier/dev
release v0.51.1
2023-07-20 22:38:48 +08:00
fatedier
efcc028a3d fix a race condition issue (#3536) 2023-07-20 22:32:32 +08:00
fatedier
90861b6821 update golib (#3532) 2023-07-17 17:27:43 +08:00
fatedier
8f105adbca update FUNDING.yml (#3520) 2023-07-06 19:58:50 +08:00
fatedier
53626b370c Merge pull request #3517 from fatedier/dev
bump version to v0.51.0
2023-07-05 20:39:25 +08:00
fatedier
b1789afbab update version (#3516) 2023-07-05 20:35:08 +08:00
fatedier
88c7e8bf7c update doc (#3512) 2023-07-02 00:35:33 +08:00
fatedier
fc4e787fe2 frpc: support stop command (#3511) 2023-06-30 17:35:37 +08:00
fatedier
4c4d5f0d0d service.Run supports passing in context (#3504) 2023-06-29 18:04:20 +08:00
fatedier
801e8c6742 support wss between frpc and frps (#3503) 2023-06-29 11:20:45 +08:00
fatedier
4fd800bc48 Merge pull request #3499 from fatedier/dev
release v0.50.0
2023-06-26 17:03:56 +08:00
fatedier
b146989703 add release notes for v0.50.0 (#3498) 2023-06-26 16:48:14 +08:00
fatedier
685d7618f3 change default value of tls_enable and disable_custom_tls_first_byte (#3494) 2023-06-26 00:10:27 +08:00
fatedier
15a245766e fix the issue of duplicate xtcp proxies will cause the previous proxy to become ineffective (#3489) 2023-06-16 00:41:06 +08:00
fatedier
e1cef053be server/proxy: simplify the code (#3488) 2023-06-16 00:14:19 +08:00
fatedier
0d6d968fe8 Merge pull request #3454 from fatedier/dev
release v0.49.0
2023-05-29 01:12:26 +08:00
fatedier
8fb99ef7a9 Merge pull request #3348 from fatedier/dev
bump version
2023-03-08 11:40:31 +08:00
fatedier
88e74ff24d Merge pull request #3300 from fatedier/dev
sync
2023-02-10 01:12:00 +08:00
fatedier
534dc99d55 Merge pull request #3299 from fatedier/dev
sync
2023-02-09 23:06:14 +08:00
fatedier
595aba5a9b Merge pull request #3248 from fatedier/dev
bump version
2023-01-10 10:26:56 +08:00
fatedier
a4189ba474 Merge branch 'dev' 2022-12-18 19:27:22 +08:00
fatedier
9ec84f8143 Merge pull request #3218 from fatedier/dev
release v0.46.0
2022-12-18 18:46:52 +08:00
fatedier
8ab474cc97 remove unsupported platform (#3148) 2022-10-27 10:22:47 +08:00
fatedier
a301046f3d Merge pull request #3147 from fatedier/dev
bump version
2022-10-26 23:18:40 +08:00
fatedier
8888610d83 Merge pull request #3010 from fatedier/dev
release v0.44.0
2022-07-11 00:10:43 +08:00
fatedier
fe5fb0326b Merge pull request #2955 from fatedier/dev
bump version to v0.43.0
2022-05-27 16:27:19 +08:00
fatedier
eb1e19a821 Merge pull request #2906 from fatedier/dev
bump version
2022-04-22 11:32:27 +08:00
fatedier
10f2620131 Merge pull request #2869 from fatedier/dev
bump version to v0.41.0
2022-03-23 21:19:59 +08:00
fatedier
ce677820c6 Merge pull request #2834 from fatedier/dev
bump version
2022-03-11 19:51:32 +08:00
fatedier
88fcc079e8 Merge pull request #2792 from fatedier/dev
bump version
2022-02-09 16:11:20 +08:00
fatedier
2dab5d0bca Merge pull request #2782 from fatedier/dev
bump version
2022-01-26 20:17:54 +08:00
fatedier
143750901e Merge pull request #2638 from fatedier/dev
bump version to v0.38.0
2021-10-25 20:31:13 +08:00
fatedier
997d406ec2 Merge pull request #2508 from fatedier/dev
bump version
2021-08-03 23:13:31 +08:00
fatedier
cfd1a3128a Merge pull request #2426 from fatedier/dev
update workflow file
2021-06-03 00:59:21 +08:00
fatedier
57577ea044 Merge pull request #2425 from fatedier/dev
bump version
2021-06-03 00:14:32 +08:00
fatedier
c5c79e4148 Merge pull request #2324 from fatedier/dev
bump version v0.36.2
2021-03-22 14:56:48 +08:00
fatedier
55da58eca4 Merge pull request #2310 from fatedier/dev
bump version
2021-03-18 11:14:56 +08:00
fatedier
76a1efccd9 update 2021-03-17 11:43:23 +08:00
fatedier
980f084ad1 Merge pull request #2302 from fatedier/dev
bump version
2021-03-15 21:54:52 +08:00
fatedier
3bf1eb8565 Merge pull request #2216 from fatedier/dev
bump version
2021-01-25 16:15:52 +08:00
fatedier
b2ae433e18 Merge pull request #2206 from fatedier/dev
bump version
2021-01-19 20:56:06 +08:00
fatedier
aa0a41ee4e Merge pull request #2088 from fatedier/dev
bump version to v0.34.3
2020-11-20 17:04:55 +08:00
fatedier
1ea1530b36 Merge pull request #2058 from fatedier/dev
bump version to v0.34.2
2020-11-06 14:50:50 +08:00
fatedier
e0c45a1aca Merge pull request #2018 from fatedier/dev
bump version to v0.34.1
2020-09-30 15:13:08 +08:00
fatedier
813c45f5c2 Merge pull request #1993 from fatedier/dev
bump version to v0.34.0
2020-09-20 00:30:51 +08:00
fatedier
aa74dc4646 Merge pull request #1990 from fatedier/dev
bump version to v0.34.0
2020-09-20 00:10:32 +08:00
fatedier
2406ecdfea Merge pull request #1780 from fatedier/dev
bump version
2020-04-27 16:50:34 +08:00
fatedier
8668fef136 Merge pull request #1728 from fatedier/dev
bump version to v0.32.1
2020-04-03 01:14:58 +08:00
fatedier
ea62bc5a34 remove vendor (#1697) 2020-03-11 14:39:43 +08:00
fatedier
23bb76397a Merge pull request #1696 from fatedier/dev
bump version to v0.32.0
2020-03-11 14:30:47 +08:00
fatedier
487c8d7c29 Merge pull request #1637 from fatedier/dev
bump version to v0.31.2
2020-02-04 21:54:28 +08:00
fatedier
f480160e2d Merge pull request #1596 from fatedier/dev
v0.31.1, fix bugs
2020-01-06 15:55:44 +08:00
fatedier
30c246c488 Merge pull request #1588 from fatedier/dev
bump version to v0.31.0
2020-01-03 11:45:22 +08:00
fatedier
75f3bce04d Merge pull request #1542 from fatedier/dev
bump version to v0.30.0
2019-11-28 14:21:27 +08:00
fatedier
adc3adc13b Merge pull request #1494 from fatedier/dev
bump version to v0.29.1
2019-11-02 21:14:50 +08:00
fatedier
e62d9a5242 Merge pull request #1415 from fatedier/dev
bump version to v0.29.0
2019-08-29 21:22:30 +08:00
fatedier
134a46c00b Merge pull request #1369 from fatedier/dev
bump version to v0.28.2
2019-08-09 12:59:13 +08:00
fatedier
ae08811636 Merge pull request #1364 from fatedier/dev
bump version to v0.28.1 and remove support for go1.11
2019-08-08 17:32:57 +08:00
fatedier
6451583e60 Merge pull request #1349 from fatedier/dev
bump version to v0.28.0
2019-08-01 14:04:55 +08:00
69 changed files with 1017 additions and 1307 deletions

1
.github/FUNDING.yml vendored
View File

@@ -1,3 +1,4 @@
# These are supported funding model platforms
github: [fatedier]
custom: ["https://afdian.net/a/fatedier"]

View File

@@ -4,7 +4,3 @@ copilot:summary
### WHY
<!-- author to complete -->
### Walkthrough
copilot:walkthrough

View File

@@ -61,7 +61,7 @@ jobs:
echo "TAG_FRPS_GPR=ghcr.io/fatedier/frps:${{ env.TAG_NAME }}" >> $GITHUB_ENV
- name: Build and push frpc
uses: docker/build-push-action@v3
uses: docker/build-push-action@v4
with:
context: .
file: ./dockerfiles/Dockerfile-for-frpc
@@ -72,7 +72,7 @@ jobs:
${{ env.TAG_FRPC_GPR }}
- name: Build and push frps
uses: docker/build-push-action@v3
uses: docker/build-push-action@v4
with:
context: .
file: ./dockerfiles/Dockerfile-for-frps

View File

@@ -14,7 +14,7 @@ jobs:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
- uses: actions/setup-go@v4
with:
go-version: '1.20'
- uses: actions/checkout@v3
@@ -22,7 +22,7 @@ jobs:
uses: golangci/golangci-lint-action@v3
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: v1.51
version: v1.53
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0

View File

@@ -13,7 +13,7 @@ jobs:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
uses: actions/setup-go@v4
with:
go-version: '1.20'
@@ -22,9 +22,9 @@ jobs:
./package.sh
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v3
uses: goreleaser/goreleaser-action@v4
with:
version: latest
args: release --rm-dist --release-notes=./Release.md
args: release --clean --release-notes=./Release.md
env:
GITHUB_TOKEN: ${{ secrets.GPR_TOKEN }}

View File

@@ -18,7 +18,7 @@ jobs:
pull-requests: write # for actions/stale to close stale PRs
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v6
- uses: actions/stale@v8
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'Issues go stale after 30d of inactivity. Stale issues rot after an additional 7d of inactivity and eventually close.'

View File

@@ -25,9 +25,11 @@ frp also offers a P2P connect mode.
<!-- vim-markdown-toc GFM -->
* [Development Status](#development-status)
* [About V2](#about-v2)
* [Architecture](#architecture)
* [Example Usage](#example-usage)
* [Access your computer in a LAN network via SSH](#access-your-computer-in-a-lan-network-via-ssh)
* [Multiple SSH services sharing the same port](#multiple-ssh-services-sharing-the-same-port)
* [Accessing Internal Web Services with Custom Domains in LAN](#accessing-internal-web-services-with-custom-domains-in-lan)
* [Forward DNS query requests](#forward-dns-query-requests)
* [Forward Unix Domain Socket](#forward-unix-domain-socket)
@@ -89,6 +91,20 @@ We are currently working on version 2 and attempting to perform some code refact
We will transition from version 0 to version 1 at the appropriate time and will only accept bug fixes and improvements, rather than big feature requests.
### About V2
The overall situation is currently unfavorable, and there is significant pressure in both personal and professional aspects.
The complexity and difficulty of the v2 version are much higher than anticipated. I can only work on its development during fragmented time periods, and the constant interruptions disrupt productivity significantly. Given this situation, we will continue to optimize and iterate on the current version until we have more free time to proceed with the major version overhaul.
The concept behind v2 is based on my years of experience and reflection in the cloud-native domain, particularly in K8s and ServiceMesh. Its core is a modernized four-layer and seven-layer proxy, similar to envoy. This proxy itself is highly scalable, not only capable of implementing the functionality of intranet penetration but also applicable to various other domains. Building upon this highly scalable core, we aim to implement all the capabilities of frp v1 while also addressing the functionalities that were previously unachievable or difficult to implement in an elegant manner. Furthermore, we will maintain efficient development and iteration capabilities.
In addition, I envision frp itself becoming a highly extensible system and platform, similar to how we can provide a range of extension capabilities based on K8s. In K8s, we can customize development according to enterprise needs, utilizing features such as CRD, controller mode, webhook, CSI, and CNI. In frp v1, we introduced the concept of server plugins, which implemented some basic extensibility. However, it relies on a simple HTTP protocol and requires users to start independent processes and manage them on their own. This approach is far from flexible and convenient, and real-world demands vary greatly. It is unrealistic to expect a non-profit open-source project maintained by a few individuals to meet everyone's needs.
Finally, we acknowledge that the current design of modules such as configuration management, permission verification, certificate management, and API management is not modern enough. While we may carry out some optimizations in the v1 version, ensuring compatibility remains a challenging issue that requires a considerable amount of effort to address.
We sincerely appreciate your support for frp.
## Architecture
![architecture](/doc/pic/architecture.png)
@@ -140,6 +156,56 @@ Note that the `local_port` (listened on the client) and `remote_port` (exposed o
`ssh -oPort=6000 test@x.x.x.x`
### Multiple SSH services sharing the same port
This example implements multiple SSH services exposed through the same port using a proxy of type tcpmux. Similarly, as long as the client supports the HTTP Connect proxy connection method, port reuse can be achieved in this way.
1. Deploy frps on a machine with a public IP and modify the frps.ini file. Here is a simplified configuration:
```ini
[common]
bind_port = 7000
tcpmux_httpconnect_port = 5002
```
2. Deploy frpc on the internal machine A with the following configuration:
```ini
[common]
server_addr = x.x.x.x
server_port = 7000
[ssh1]
type = tcpmux
multiplexer = httpconnect
custom_domains = machine-a.example.com
local_ip = 127.0.0.1
local_port = 22
```
3. Deploy another frpc on the internal machine B with the following configuration:
```ini
[common]
server_addr = x.x.x.x
server_port = 7000
[ssh2]
type = tcpmux
multiplexer = httpconnect
custom_domains = machine-b.example.com
local_ip = 127.0.0.1
local_port = 22
```
4. To access internal machine A using SSH ProxyCommand, assuming the username is "test":
`ssh -o 'proxycommand socat - PROXY:x.x.x.x:machine-a.example.com:22,proxyport=5002' test@machine-a`
5. To access internal machine B, the only difference is the domain name, assuming the username is "test":
`ssh -o 'proxycommand socat - PROXY:x.x.x.x:machine-b.example.com:22,proxyport=5002' test@machine-b`
### Accessing Internal Web Services with Custom Domains in LAN
Sometimes we need to expose a local web service behind a NAT network to others for testing purposes with our own domain name.
@@ -155,6 +221,8 @@ Unfortunately, we cannot resolve a domain name to a local IP. However, we can us
vhost_http_port = 8080
```
If you want to configure an https proxy, you need to set up the `vhost_https_port`.
2. Start `frps`:
`./frps -c ./frps.ini`
@@ -280,6 +348,7 @@ You may substitute `https2https` for the plugin, and point the `plugin_local_add
[common]
server_addr = x.x.x.x
server_port = 7000
vhost_https_port = 443
[test_https2http]
type = https
@@ -562,11 +631,9 @@ use_compression = true
#### TLS
frp supports the TLS protocol between `frpc` and `frps` since v0.25.0.
Since v0.50.0, the default value of `tls_enable` and `disable_custom_tls_first_byte` has been changed to true, and tls is enabled by default.
For port multiplexing, frp sends a first byte `0x17` to dial a TLS connection.
Configure `tls_enable = true` in the `[common]` section to `frpc.ini` to enable this feature.
For port multiplexing, frp sends a first byte `0x17` to dial a TLS connection. This only takes effect when you set `disable_custom_tls_first_byte` to false.
To **enforce** `frps` to only accept TLS connections - configure `tls_only = true` in the `[common]` section in `frps.ini`. **This is optional.**
@@ -581,7 +648,6 @@ tls_trusted_ca_file = ca.crt
**`frps` TLS settings (under the `[common]` section):**
```ini
tls_only = true
tls_enable = true
tls_cert_file = certificate.crt
tls_key_file = certificate.key
tls_trusted_ca_file = ca.crt

View File

@@ -5,7 +5,7 @@
[README](README.md) | [中文文档](README_zh.md)
frp 是一个专注于内网穿透的高性能的反向代理应用,支持 TCP、UDP、HTTP、HTTPS 等多种协议。可以将内网服务以安全、便捷的方式通过具有公网 IP 节点的中转暴露到公网。
frp 是一个专注于内网穿透的高性能的反向代理应用,支持 TCP、UDP、HTTP、HTTPS 等多种协议,且支持 P2P 通信。可以将内网服务以安全、便捷的方式通过具有公网 IP 节点的中转暴露到公网。
<h3 align="center">Gold Sponsors</h3>
<!--gold sponsors start-->
@@ -20,12 +20,13 @@ frp 是一个专注于内网穿透的高性能的反向代理应用,支持 TCP
通过在具有公网 IP 的节点上部署 frp 服务端,可以轻松地将内网服务穿透到公网,同时提供诸多专业的功能特性,这包括:
* 客户端服务端通信支持 TCP、KCP 以及 Websocket 等多种协议。
* 采用 TCP 连接流式复用,在单个连接间承载更多请求,节省连接建立时间。
* 客户端服务端通信支持 TCP、QUIC、KCP 以及 Websocket 等多种协议。
* 采用 TCP 连接流式复用,在单个连接间承载更多请求,节省连接建立时间,降低请求延迟
* 代理组间的负载均衡。
* 端口复用,多个服务通过同一个服务端端口暴露。
* 多个原生支持的客户端插件静态文件查看HTTP、SOCK5 代理等),便于独立使用 frp 客户端完成某些工作
* 高度扩展性的服务端插件系统,方便结合自身需求进行功能扩展
* 支持 P2P 通信,流量不经过服务器中转,充分利用带宽资源
* 多个原生支持的客户端插件静态文件查看HTTPS/HTTP 协议转换HTTP、SOCK5 代理等),便于独立使用 frp 客户端完成某些工作
* 高度扩展性的服务端插件系统,易于结合自身需求进行功能扩展。
* 服务端和客户端 UI 页面。
## 开发状态
@@ -34,10 +35,24 @@ frp 目前已被很多公司广泛用于测试、生产环境。
master 分支用于发布稳定版本dev 分支用于开发,您可以尝试下载最新的 release 版本进行测试。
我们正在进行 v2 大版本的开发,将会尝试在各个方面进行重构和升级,且不会与 v1 版本进行兼容,预计会持续一段时间。
我们正在进行 v2 大版本的开发,将会尝试在各个方面进行重构和升级,且不会与 v1 版本进行兼容,预计会持续较长的一段时间。
现在的 v0 版本将会在合适的时间切换为 v1 版本并且保证兼容性,后续只做 bug 修复和优化,不再进行大的功能性更新。
### 关于 v2 的一些说明
当前整体形势不佳,面临的生活工作压力很大。
v2 版本的复杂度和难度比我们预期的要高得多。我只能利用零散的时间进行开发,而且由于上下文经常被打断,效率极低。由于这种情况可能会持续一段时间,我们仍然会在当前版本上进行一些优化和迭代,直到我们有更多空闲时间来推进大版本的重构。
v2 的构想是基于我多年在云原生领域,特别是在 K8s 和 ServiceMesh 方面的工作经验和思考。它的核心是一个现代化的四层和七层代理,类似于 envoy。这个代理本身高度可扩展不仅可以用于实现内网穿透的功能还可以应用于更多领域。在这个高度可扩展的内核基础上我们将实现 frp v1 中的所有功能,并且能够以一种更加优雅的方式实现原先架构中无法实现或不易实现的功能。同时,我们将保持高效的开发和迭代能力。
除此之外,我希望 frp 本身也成为一个高度可扩展的系统和平台,就像我们可以基于 K8s 提供一系列扩展能力一样。在 K8s 上,我们可以根据企业需求进行定制化开发,例如使用 CRD、controller 模式、webhook、CSI 和 CNI 等。在 frp v1 中,我们引入了服务端插件的概念,实现了一些简单的扩展性。但是,它实际上依赖于简单的 HTTP 协议,并且需要用户自己启动独立的进程和管理。这种方式远远不够灵活和方便,而且现实世界的需求千差万别,我们不能期望一个由少数人维护的非营利性开源项目能够满足所有人的需求。
最后,我们意识到像配置管理、权限验证、证书管理和管理 API 等模块的当前设计并不够现代化。尽管我们可能在 v1 版本中进行一些优化,但确保兼容性是一个令人头疼的问题,需要投入大量精力来解决。
非常感谢您对 frp 的支持。
## 文档
完整文档已经迁移至 [https://gofrp.org](https://gofrp.org/docs)。
@@ -55,19 +70,23 @@ frp 是一个免费且开源的项目,我们欢迎任何人为其开发和进
**提醒:和项目相关的问题最好在 [issues](https://github.com/fatedier/frp/issues) 中反馈,这样方便其他有类似问题的人可以快速查找解决方法,并且也避免了我们重复回答一些问题。**
##
##
如果您觉得 frp 对你有帮助,欢迎给予我们一定的捐助来维持项目的长期发展。
### GitHub Sponsors
### Sponsors
长期赞助可以帮助我们保持项目的持续发展。
您可以通过 [GitHub Sponsors](https://github.com/sponsors/fatedier) 赞助我们。
国内用户可以通过 [爱发电](https://afdian.net/a/fatedier) 赞助我们。
企业赞助者可以将贵公司的 Logo 以及链接放置在项目 README 文件中。
### 知识星球
如果您想学习 frp 相关的知识和技术,或者寻求任何帮助及咨询,都可以通过微信扫描下方的二维码付费加入知识星球的官方社群:
如果您想了解更多 frp 相关技术以及更新详解,或者寻求任何帮助及咨询,都可以通过微信扫描下方的二维码付费加入知识星球的官方社群:
![zsxq](/doc/pic/zsxq.jpg)

View File

@@ -1,19 +1,8 @@
## Notes
### Features
We have thoroughly refactored xtcp in this version to improve its penetration rate and stability.
* Adds a `completion` command for shell completions.
In this version, different penetration strategies can be attempted by retrying connections multiple times. Once a hole is successfully punched, the strategy will be recorded in the server cache for future reuse. When new users connect, the successfully penetrated tunnel can be reused instead of punching a new hole.
### Fixes
**Due to a significant refactor of xtcp, this version is not compatible with previous versions of xtcp.**
**To use features related to xtcp, both frpc and frps need to be updated to the latest version.**
### New
* The frpc has added the `nathole discover` command for testing the NAT type of the current network.
* `XTCP` has been refactored, resulting in a significant improvement in the success rate of penetration.
* When verifying passwords, use `subtle.ConstantTimeCompare` and introduce a certain delay when the password is incorrect.
### Fix
* Fix the problem of lagging when opening multiple table entries in the frps dashboard.
* fix a goroutine leak issue caused by Login plugin timeout.
* Fix an issue introduced in version 0.51.1, enabling `use_compression` will cause some requests to fail.

View File

@@ -52,6 +52,7 @@ func (svr *Service) RunAdminServer(address string) (err error) {
// 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 File

@@ -24,6 +24,7 @@ import (
"sort"
"strconv"
"strings"
"time"
"github.com/samber/lo"
@@ -38,12 +39,12 @@ type GeneralResponse struct {
}
// /healthz
func (svr *Service) healthz(w http.ResponseWriter, r *http.Request) {
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) {
// GET /api/reload
func (svr *Service) apiReload(w http.ResponseWriter, _ *http.Request) {
res := GeneralResponse{Code: 200}
log.Info("api request [/api/reload]")
@@ -72,6 +73,22 @@ func (svr *Service) apiReload(w http.ResponseWriter, r *http.Request) {
log.Info("success reload conf")
}
// POST /api/stop
func (svr *Service) apiStop(w http.ResponseWriter, _ *http.Request) {
res := GeneralResponse{Code: 200}
log.Info("api request [/api/stop]")
defer func() {
log.Info("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 {
@@ -106,8 +123,8 @@ func NewProxyStatusResp(status *proxy.WorkingStatus, serverAddr string) ProxySta
return psr
}
// GET api/status
func (svr *Service) apiStatus(w http.ResponseWriter, r *http.Request) {
// GET /api/status
func (svr *Service) apiStatus(w http.ResponseWriter, _ *http.Request) {
var (
buf []byte
res StatusResp = make(map[string][]ProxyStatusResp)
@@ -135,8 +152,8 @@ func (svr *Service) apiStatus(w http.ResponseWriter, r *http.Request) {
}
}
// GET api/config
func (svr *Service) apiGetConfig(w http.ResponseWriter, r *http.Request) {
// GET /api/config
func (svr *Service) apiGetConfig(w http.ResponseWriter, _ *http.Request) {
res := GeneralResponse{Code: 200}
log.Info("Http get request [/api/config]")
@@ -175,7 +192,7 @@ func (svr *Service) apiGetConfig(w http.ResponseWriter, r *http.Request) {
res.Msg = strings.Join(newRows, "\n")
}
// PUT api/config
// PUT /api/config
func (svr *Service) apiPutConfig(w http.ResponseWriter, r *http.Request) {
res := GeneralResponse{Code: 200}

View File

@@ -124,7 +124,7 @@ func (ctl *Control) Run() {
go ctl.vm.Run()
}
func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
func (ctl *Control) HandleReqWorkConn(_ *msg.ReqWorkConn) {
xl := ctl.xl
workConn, err := ctl.connectServer()
if err != nil {

View File

@@ -40,7 +40,7 @@ type GeneralTCPProxy struct {
*BaseProxy
}
func NewGeneralTCPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
func NewGeneralTCPProxy(baseProxy *BaseProxy, _ config.ProxyConf) Proxy {
return &GeneralTCPProxy{
BaseProxy: baseProxy,
}

View File

@@ -142,8 +142,9 @@ func (pxy *BaseProxy) HandleTCPWorkConnection(workConn net.Conn, m *msg.StartWor
return
}
}
var compressionResourceRecycleFn func()
if baseConfig.UseCompression {
remote = libio.WithCompression(remote)
remote, compressionResourceRecycleFn = libio.WithCompressionFromPool(remote)
}
// check if we need to send proxy protocol info
@@ -213,4 +214,7 @@ func (pxy *BaseProxy) HandleTCPWorkConnection(workConn net.Conn, m *msg.StartWor
if len(errs) > 0 {
xl.Trace("join connections errors: %v", errs)
}
if compressionResourceRecycleFn != nil {
compressionResourceRecycleFn()
}
}

View File

@@ -77,7 +77,7 @@ func (pxy *SUDPProxy) Close() {
}
}
func (pxy *SUDPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
func (pxy *SUDPProxy) InWorkConn(conn net.Conn, _ *msg.StartWorkConn) {
xl := pxy.xl
xl.Info("incoming a new work connection for sudp proxy, %s", conn.RemoteAddr().String())

View File

@@ -86,7 +86,7 @@ func (pxy *UDPProxy) Close() {
}
}
func (pxy *UDPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
func (pxy *UDPProxy) InWorkConn(conn net.Conn, _ *msg.StartWorkConn) {
xl := pxy.xl
xl.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
// close resources releated with old workConn

View File

@@ -61,6 +61,7 @@ func (pxy *XTCPProxy) InWorkConn(conn net.Conn, startWorkConnMsg *msg.StartWorkC
return
}
xl.Trace("nathole prepare start")
prepareResult, err := nathole.Prepare([]string{pxy.clientCfg.NatHoleSTUNServer})
if err != nil {
xl.Warn("nathole prepare error: %v", err)
@@ -80,6 +81,7 @@ func (pxy *XTCPProxy) InWorkConn(conn net.Conn, startWorkConnMsg *msg.StartWorkC
AssistedAddrs: prepareResult.AssistedAddrs,
}
xl.Trace("nathole exchange info start")
natHoleRespMsg, err := nathole.ExchangeInfo(pxy.ctx, pxy.msgTransporter, transactionID, natHoleClientMsg, 5*time.Second)
if err != nil {
xl.Warn("nathole exchange info error: %v", err)

View File

@@ -86,16 +86,14 @@ func NewService(
visitorCfgs map[string]config.VisitorConf,
cfgFile string,
) (svr *Service, err error) {
ctx, cancel := context.WithCancel(context.Background())
svr = &Service{
authSetter: auth.NewAuthSetter(cfg.ClientConfig),
cfg: cfg,
cfgFile: cfgFile,
pxyCfgs: pxyCfgs,
visitorCfgs: visitorCfgs,
ctx: context.Background(),
exit: 0,
ctx: xlog.NewContext(ctx, xlog.New()),
cancel: cancel,
}
return
}
@@ -106,7 +104,11 @@ func (svr *Service) GetController() *Control {
return svr.ctl
}
func (svr *Service) Run() error {
func (svr *Service) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
svr.ctx = xlog.NewContext(ctx, xlog.New())
svr.cancel = cancel
xl := xlog.FromContextSafe(svr.ctx)
// set custom DNSServer
@@ -135,7 +137,7 @@ func (svr *Service) Run() error {
if svr.cfg.LoginFailExit {
return err
}
util.RandomSleep(10*time.Second, 0.9, 1.1)
util.RandomSleep(5*time.Second, 0.9, 1.1)
} else {
// login success
ctl := NewControl(svr.ctx, svr.runID, conn, cm, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.authSetter)
@@ -161,6 +163,10 @@ func (svr *Service) Run() error {
log.Info("admin server listen on %s:%d", svr.cfg.AdminAddr, svr.cfg.AdminPort)
}
<-svr.ctx.Done()
// service context may not be canceled by svr.Close(), we should call it here to release resources
if atomic.LoadUint32(&svr.exit) == 0 {
svr.Close()
}
return nil
}
@@ -182,7 +188,7 @@ func (svr *Service) keepControllerWorking() {
return
}
// the first three retry with no delay
// the first three attempts with a low delay
if reconnectCounts > 3 {
util.RandomSleep(reconnectDelay, 0.9, 1.1)
xl.Info("wait %v to reconnect", reconnectDelay)
@@ -322,10 +328,13 @@ func (svr *Service) GracefulClose(d time.Duration) {
svr.ctlMu.RLock()
if svr.ctl != nil {
svr.ctl.GracefulClose(d)
svr.ctl = nil
}
svr.ctlMu.RUnlock()
svr.cancel()
if svr.cancel != nil {
svr.cancel()
}
}
type ConnectionManager struct {
@@ -369,7 +378,7 @@ func (cm *ConnectionManager) OpenConnection() error {
}
tlsConfig.NextProtos = []string{"frp"}
conn, err := quic.DialAddrContext(
conn, err := quic.DialAddr(
cm.ctx,
net.JoinHostPort(cm.cfg.ServerAddr, strconv.Itoa(cm.cfg.ServerPort)),
tlsConfig, &quic.Config{
@@ -427,7 +436,11 @@ func (cm *ConnectionManager) realConnect() (net.Conn, error) {
xl := xlog.FromContextSafe(cm.ctx)
var tlsConfig *tls.Config
var err error
if cm.cfg.TLSEnable {
tlsEnable := cm.cfg.TLSEnable
if cm.cfg.Protocol == "wss" {
tlsEnable = true
}
if tlsEnable {
sn := cm.cfg.TLSServerName
if sn == "" {
sn = cm.cfg.ServerAddr
@@ -451,10 +464,23 @@ func (cm *ConnectionManager) realConnect() (net.Conn, error) {
}
dialOptions := []libdial.DialOption{}
protocol := cm.cfg.Protocol
if protocol == "websocket" {
switch protocol {
case "websocket":
protocol = "tcp"
dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: utilnet.DialHookWebsocket()}))
dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: utilnet.DialHookWebsocket(protocol, "")}))
dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{
Hook: utilnet.DialHookCustomTLSHeadByte(tlsConfig != nil, cm.cfg.DisableCustomTLSFirstByte),
}))
dialOptions = append(dialOptions, libdial.WithTLSConfig(tlsConfig))
case "wss":
protocol = "tcp"
dialOptions = append(dialOptions, libdial.WithTLSConfigAndPriority(100, tlsConfig))
// Make sure that if it is wss, the websocket hook is executed after the tls hook.
dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: utilnet.DialHookWebsocket(protocol, tlsConfig.ServerName), Priority: 110}))
default:
dialOptions = append(dialOptions, libdial.WithTLSConfig(tlsConfig))
}
if cm.cfg.ConnectServerLocalIP != "" {
dialOptions = append(dialOptions, libdial.WithLocalAddr(cm.cfg.ConnectServerLocalIP))
}
@@ -464,10 +490,6 @@ func (cm *ConnectionManager) realConnect() (net.Conn, error) {
libdial.WithKeepAlive(time.Duration(cm.cfg.DialServerKeepAlive)*time.Second),
libdial.WithProxy(proxyType, addr),
libdial.WithProxyAuth(auth),
libdial.WithTLSConfig(tlsConfig),
libdial.WithAfterHook(libdial.AfterHook{
Hook: utilnet.DialHookCustomTLSHeadByte(tlsConfig != nil, cm.cfg.DisableCustomTLSFirstByte),
}),
)
conn, err := libdial.DialContext(
cm.ctx,

View File

@@ -126,7 +126,9 @@ func (sv *STCPVisitor) handleConn(userConn net.Conn) {
}
if sv.cfg.UseCompression {
remote = libio.WithCompression(remote)
var recycleFn func()
remote, recycleFn = libio.WithCompressionFromPool(remote)
defer recycleFn()
}
libio.Join(userConn, remote)

View File

@@ -200,7 +200,9 @@ func (sv *XTCPVisitor) handleConn(userConn net.Conn) {
}
}
if sv.cfg.UseCompression {
muxConnRWCloser = libio.WithCompression(muxConnRWCloser)
var recycleFn func()
muxConnRWCloser, recycleFn = libio.WithCompressionFromPool(muxConnRWCloser)
defer recycleFn()
}
_, _, errs := libio.Join(userConn, muxConnRWCloser)
@@ -266,11 +268,13 @@ func (sv *XTCPVisitor) getTunnelConn() (net.Conn, error) {
// 4. Create a tunnel session using an underlying UDP connection.
func (sv *XTCPVisitor) makeNatHole() {
xl := xlog.FromContextSafe(sv.ctx)
xl.Trace("makeNatHole start")
if err := nathole.PreCheck(sv.ctx, sv.helper.MsgTransporter(), sv.cfg.ServerName, 5*time.Second); err != nil {
xl.Warn("nathole precheck error: %v", err)
return
}
xl.Trace("nathole prepare start")
prepareResult, err := nathole.Prepare([]string{sv.clientCfg.NatHoleSTUNServer})
if err != nil {
xl.Warn("nathole prepare error: %v", err)
@@ -294,6 +298,7 @@ func (sv *XTCPVisitor) makeNatHole() {
AssistedAddrs: prepareResult.AssistedAddrs,
}
xl.Trace("nathole exchange info start")
natHoleRespMsg, err := nathole.ExchangeInfo(sv.ctx, sv.helper.MsgTransporter(), transactionID, natHoleVisitorMsg, 5*time.Second)
if err != nil {
listenConn.Close()
@@ -365,7 +370,7 @@ func (ks *KCPTunnelSession) Init(listenConn *net.UDPConn, raddr *net.UDPAddr) er
return nil
}
func (ks *KCPTunnelSession) OpenConn(ctx context.Context) (net.Conn, error) {
func (ks *KCPTunnelSession) OpenConn(_ context.Context) (net.Conn, error) {
ks.mu.RLock()
defer ks.mu.RUnlock()
session := ks.session
@@ -408,7 +413,7 @@ func (qs *QUICTunnelSession) Init(listenConn *net.UDPConn, raddr *net.UDPAddr) e
return fmt.Errorf("create tls config error: %v", err)
}
tlsConfig.NextProtos = []string{"frp"}
quicConn, err := quic.Dial(listenConn, raddr, raddr.String(), tlsConfig,
quicConn, err := quic.Dial(context.Background(), listenConn, raddr, tlsConfig,
&quic.Config{
MaxIdleTimeout: time.Duration(qs.clientCfg.QUICMaxIdleTimeout) * time.Second,
MaxIncomingStreams: int64(qs.clientCfg.QUICMaxIncomingStreams),

View File

@@ -15,6 +15,7 @@
package sub
import (
"context"
"fmt"
"io/fs"
"net"
@@ -76,7 +77,8 @@ var (
bindAddr string
bindPort int
tlsEnable bool
tlsEnable bool
tlsServerName string
)
func init() {
@@ -88,13 +90,14 @@ func init() {
func RegisterCommonFlags(cmd *cobra.Command) {
cmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address")
cmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
cmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp or websocket")
cmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp, kcp, quic, websocket, wss")
cmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
cmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
cmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
cmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
cmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
cmd.PersistentFlags().BoolVarP(&tlsEnable, "tls_enable", "", false, "enable frpc tls")
cmd.PersistentFlags().BoolVarP(&tlsEnable, "tls_enable", "", true, "enable frpc tls")
cmd.PersistentFlags().StringVarP(&tlsServerName, "tls_server_name", "", "", "specify the custom server name of tls certificate")
cmd.PersistentFlags().StringVarP(&dnsServer, "dns_server", "", "", "specify dns server instead of using system default one")
}
@@ -150,12 +153,11 @@ func Execute() {
}
}
func handleSignal(svr *client.Service, doneCh chan struct{}) {
func handleTermSignal(svr *client.Service) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
svr.GracefulClose(500 * time.Millisecond)
close(doneCh)
}
func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) {
@@ -186,6 +188,7 @@ func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) {
cfg.ClientConfig = auth.GetDefaultClientConf()
cfg.Token = token
cfg.TLSEnable = tlsEnable
cfg.TLSServerName = tlsServerName
cfg.Complete()
if err = cfg.Validate(); err != nil {
@@ -223,16 +226,12 @@ func startService(
return
}
closedDoneCh := make(chan struct{})
shouldGracefulClose := cfg.Protocol == "kcp" || cfg.Protocol == "quic"
// Capture the exit signal if we use kcp or quic.
if shouldGracefulClose {
go handleSignal(svr, closedDoneCh)
go handleTermSignal(svr)
}
err = svr.Run()
if err == nil && shouldGracefulClose {
<-closedDoneCh
}
_ = svr.Run(context.Background())
return
}

84
cmd/frpc/sub/stop.go Normal file
View File

@@ -0,0 +1,84 @@
// 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 sub
import (
"encoding/base64"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/fatedier/frp/pkg/config"
)
func init() {
rootCmd.AddCommand(stopCmd)
}
var stopCmd = &cobra.Command{
Use: "stop",
Short: "Stop the running frpc",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, _, _, err := config.ParseClientConfig(cfgFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = stopClient(cfg)
if err != nil {
fmt.Printf("frpc stop error: %v\n", err)
os.Exit(1)
}
fmt.Printf("stop success\n")
return nil
},
}
func stopClient(clientCfg config.ClientCommonConf) error {
if clientCfg.AdminPort == 0 {
return fmt.Errorf("admin_port shoud be set if you want to use stop feature")
}
req, err := http.NewRequest("POST", "http://"+
clientCfg.AdminAddr+":"+fmt.Sprintf("%d", clientCfg.AdminPort)+"/api/stop", nil)
if err != nil {
return err
}
authStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(clientCfg.AdminUser+":"+
clientCfg.AdminPwd))
req.Header.Add("Authorization", authStr)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
return nil
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("code [%d], %s", resp.StatusCode, strings.TrimSpace(string(body)))
}

View File

@@ -15,6 +15,7 @@
package main
import (
"context"
"fmt"
"os"
@@ -210,6 +211,6 @@ func runServer(cfg config.ServerCommonConf) (err error) {
return err
}
log.Info("frps started successfully")
svr.Run()
svr.Run(context.Background())
return
}

View File

@@ -95,7 +95,7 @@ user = your_name
login_fail_exit = true
# communication protocol used to connect to server
# supports tcp, kcp, quic and websocket now, default is tcp
# supports tcp, kcp, quic, websocket and wss now, default is tcp
protocol = tcp
# set client binding ip when connect server, default is empty.
@@ -107,7 +107,8 @@ connect_server_local_ip = 0.0.0.0
# quic_max_idle_timeout = 30
# quic_max_incoming_streams = 100000
# if tls_enable is true, frpc will connect frps by tls
# If tls_enable is true, frpc will connect frps by tls.
# Since v0.50.0, the default value has been changed to true, and tls is enabled by default.
tls_enable = true
# tls_cert_file = client.crt
@@ -140,9 +141,10 @@ udp_packet_size = 1500
# include other config files for proxies.
# includes = ./confd/*.ini
# By default, frpc will connect frps with first custom byte if tls is enabled.
# If DisableCustomTLSFirstByte is true, frpc will not send that custom byte.
disable_custom_tls_first_byte = false
# If the disable_custom_tls_first_byte is set to false, frpc will establish a connection with frps using the
# first custom byte when tls is enabled.
# Since v0.50.0, the default value has been changed to true, and the first custom byte is disabled by default.
disable_custom_tls_first_byte = true
# Enable golang pprof handlers in admin listener.
# Admin port must be set first.

88
go.mod
View File

@@ -4,74 +4,82 @@ go 1.20
require (
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5
github.com/coreos/go-oidc/v3 v3.4.0
github.com/coreos/go-oidc/v3 v3.6.0
github.com/fatedier/beego v0.0.0-20171024143340-6c6a4f5bd5eb
github.com/fatedier/golib v0.1.1-0.20230320133937-a7edcc8c793d
github.com/fatedier/golib v0.1.1-0.20230725122706-dcbaee8eef40
github.com/fatedier/kcp-go v2.0.4-0.20190803094908-fe8645b0a904+incompatible
github.com/go-playground/validator/v10 v10.11.0
github.com/go-playground/validator/v10 v10.14.1
github.com/google/uuid v1.3.0
github.com/gorilla/mux v1.8.0
github.com/gorilla/websocket v1.5.0
github.com/hashicorp/yamux v0.1.1
github.com/onsi/ginkgo/v2 v2.8.3
github.com/onsi/gomega v1.27.0
github.com/pion/stun v0.4.0
github.com/pires/go-proxyproto v0.6.2
github.com/prometheus/client_golang v1.13.0
github.com/quic-go/quic-go v0.34.0
github.com/rodaine/table v1.0.1
github.com/onsi/ginkgo/v2 v2.11.0
github.com/onsi/gomega v1.27.8
github.com/pion/stun v0.6.1
github.com/pires/go-proxyproto v0.7.0
github.com/prometheus/client_golang v1.16.0
github.com/quic-go/quic-go v0.36.2
github.com/rodaine/table v1.1.0
github.com/samber/lo v1.38.1
github.com/spf13/cobra v1.1.3
github.com/stretchr/testify v1.8.1
golang.org/x/net v0.7.0
golang.org/x/oauth2 v0.3.0
golang.org/x/sync v0.1.0
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8
github.com/spf13/cobra v1.7.0
github.com/stretchr/testify v1.8.4
golang.org/x/net v0.12.0
golang.org/x/oauth2 v0.10.0
golang.org/x/sync v0.3.0
golang.org/x/time v0.3.0
gopkg.in/ini.v1 v1.67.0
k8s.io/apimachinery v0.26.1
k8s.io/client-go v0.26.1
k8s.io/apimachinery v0.27.4
k8s.io/client-go v0.27.4
)
require (
github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logr/logr v1.2.3 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/go-jose/go-jose/v3 v3.0.0 // indirect
github.com/go-logr/logr v1.2.4 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
github.com/golang/mock v1.6.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.3 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/klauspost/cpuid/v2 v2.0.6 // indirect
github.com/klauspost/reedsolomon v1.9.15 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/pion/transport/v2 v2.0.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/pion/dtls/v2 v2.2.7 // indirect
github.com/pion/logging v0.2.2 // indirect
github.com/pion/transport/v2 v2.2.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.37.0 // indirect
github.com/prometheus/procfs v0.8.0 // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.42.0 // indirect
github.com/prometheus/procfs v0.10.1 // indirect
github.com/quic-go/qtls-go1-19 v0.3.2 // indirect
github.com/quic-go/qtls-go1-20 v0.2.2 // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 // indirect
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b // indirect
github.com/tjfoc/gmsm v1.4.1 // indirect
golang.org/x/crypto v0.4.0 // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/exp v0.0.0-20221205204356-47842c84f3db // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/sys v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect
golang.org/x/tools v0.6.0 // indirect
golang.org/x/mod v0.10.0 // indirect
golang.org/x/sys v0.10.0 // indirect
golang.org/x/text v0.11.0 // indirect
golang.org/x/tools v0.9.3 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/square/go-jose.v2 v2.6.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/utils v0.0.0-20221107191617-1a15be271d1d // indirect
k8s.io/utils v0.0.0-20230209194617-a36077c30491 // indirect
)
// TODO(fatedier): Temporary use the modified version, update to the official version after merging into the official repository.
replace github.com/hashicorp/yamux => github.com/fatedier/yamux v0.0.0-20230628132301-7aca4898904d

896
go.sum

File diff suppressed because it is too large Load Diff

View File

@@ -20,6 +20,7 @@ import (
"path/filepath"
"strings"
"github.com/samber/lo"
"gopkg.in/ini.v1"
"github.com/fatedier/frp/pkg/auth"
@@ -117,7 +118,7 @@ type ClientCommonConf struct {
Start []string `ini:"start" json:"start"`
// Start map[string]struct{} `json:"start"`
// Protocol specifies the protocol to use when interacting with the server.
// Valid values are "tcp", "kcp", "quic" and "websocket". By default, this value
// Valid values are "tcp", "kcp", "quic", "websocket" and "wss". By default, this value
// is "tcp".
Protocol string `ini:"protocol" json:"protocol"`
// QUIC protocol options
@@ -127,6 +128,7 @@ type ClientCommonConf struct {
// TLSEnable specifies whether or not TLS should be used when communicating
// with the server. If "tls_cert_file" and "tls_key_file" are valid,
// client will load the supplied tls configuration.
// Since v0.50.0, the default value has been changed to true, and tls is enabled by default.
TLSEnable bool `ini:"tls_enable" json:"tls_enable"`
// TLSCertPath specifies the path of the cert file that client will
// load. It only works when "tls_enable" is true and "tls_key_file" is valid.
@@ -142,8 +144,9 @@ type ClientCommonConf struct {
// TLSServerName specifies the custom server name of tls certificate. By
// default, server name if same to ServerAddr.
TLSServerName string `ini:"tls_server_name" json:"tls_server_name"`
// By default, frpc will connect frps with first custom byte if tls is enabled.
// If DisableCustomTLSFirstByte is true, frpc will not send that custom byte.
// If the disable_custom_tls_first_byte is set to false, frpc will establish a connection with frps using the
// first custom byte when tls is enabled.
// Since v0.50.0, the default value has been changed to true, and the first custom byte is disabled by default.
DisableCustomTLSFirstByte bool `ini:"disable_custom_tls_first_byte" json:"disable_custom_tls_first_byte"`
// HeartBeatInterval specifies at what interval heartbeats are sent to the
// server, in seconds. It is not recommended to change this value. By
@@ -168,32 +171,34 @@ type ClientCommonConf struct {
// GetDefaultClientConf returns a client configuration with default values.
func GetDefaultClientConf() ClientCommonConf {
return ClientCommonConf{
ClientConfig: auth.GetDefaultClientConf(),
ServerAddr: "0.0.0.0",
ServerPort: 7000,
NatHoleSTUNServer: "stun.easyvoip.com:3478",
DialServerTimeout: 10,
DialServerKeepAlive: 7200,
HTTPProxy: os.Getenv("http_proxy"),
LogFile: "console",
LogWay: "console",
LogLevel: "info",
LogMaxDays: 3,
AdminAddr: "127.0.0.1",
PoolCount: 1,
TCPMux: true,
TCPMuxKeepaliveInterval: 60,
LoginFailExit: true,
Start: make([]string, 0),
Protocol: "tcp",
QUICKeepalivePeriod: 10,
QUICMaxIdleTimeout: 30,
QUICMaxIncomingStreams: 100000,
HeartbeatInterval: 30,
HeartbeatTimeout: 90,
Metas: make(map[string]string),
UDPPacketSize: 1500,
IncludeConfigFiles: make([]string, 0),
ClientConfig: auth.GetDefaultClientConf(),
ServerAddr: "0.0.0.0",
ServerPort: 7000,
NatHoleSTUNServer: "stun.easyvoip.com:3478",
DialServerTimeout: 10,
DialServerKeepAlive: 7200,
HTTPProxy: os.Getenv("http_proxy"),
LogFile: "console",
LogWay: "console",
LogLevel: "info",
LogMaxDays: 3,
AdminAddr: "127.0.0.1",
PoolCount: 1,
TCPMux: true,
TCPMuxKeepaliveInterval: 60,
LoginFailExit: true,
Start: make([]string, 0),
Protocol: "tcp",
QUICKeepalivePeriod: 10,
QUICMaxIdleTimeout: 30,
QUICMaxIncomingStreams: 100000,
TLSEnable: true,
DisableCustomTLSFirstByte: true,
HeartbeatInterval: 30,
HeartbeatTimeout: 90,
Metas: make(map[string]string),
UDPPacketSize: 1500,
IncludeConfigFiles: make([]string, 0),
}
}
@@ -226,7 +231,7 @@ func (cfg *ClientCommonConf) Validate() error {
}
}
if cfg.Protocol != "tcp" && cfg.Protocol != "kcp" && cfg.Protocol != "websocket" && cfg.Protocol != "quic" {
if !lo.Contains([]string{"tcp", "kcp", "quic", "websocket", "wss"}, cfg.Protocol) {
return fmt.Errorf("invalid protocol")
}

View File

@@ -258,40 +258,41 @@ func Test_LoadClientCommonConf(t *testing.T) {
OidcTokenEndpointURL: "endpoint_url",
},
},
ServerAddr: "0.0.0.9",
ServerPort: 7009,
NatHoleSTUNServer: "stun.easyvoip.com:3478",
DialServerTimeout: 10,
DialServerKeepAlive: 7200,
HTTPProxy: "http://user:passwd@192.168.1.128:8080",
LogFile: "./frpc.log9",
LogWay: "file",
LogLevel: "info9",
LogMaxDays: 39,
DisableLogColor: false,
AdminAddr: "127.0.0.9",
AdminPort: 7409,
AdminUser: "admin9",
AdminPwd: "admin9",
AssetsDir: "./static9",
PoolCount: 59,
TCPMux: true,
TCPMuxKeepaliveInterval: 60,
User: "your_name",
LoginFailExit: true,
Protocol: "tcp",
QUICKeepalivePeriod: 10,
QUICMaxIdleTimeout: 30,
QUICMaxIncomingStreams: 100000,
TLSEnable: true,
TLSCertFile: "client.crt",
TLSKeyFile: "client.key",
TLSTrustedCaFile: "ca.crt",
TLSServerName: "example.com",
DNSServer: "8.8.8.9",
Start: []string{"ssh", "dns"},
HeartbeatInterval: 39,
HeartbeatTimeout: 99,
ServerAddr: "0.0.0.9",
ServerPort: 7009,
NatHoleSTUNServer: "stun.easyvoip.com:3478",
DialServerTimeout: 10,
DialServerKeepAlive: 7200,
HTTPProxy: "http://user:passwd@192.168.1.128:8080",
LogFile: "./frpc.log9",
LogWay: "file",
LogLevel: "info9",
LogMaxDays: 39,
DisableLogColor: false,
AdminAddr: "127.0.0.9",
AdminPort: 7409,
AdminUser: "admin9",
AdminPwd: "admin9",
AssetsDir: "./static9",
PoolCount: 59,
TCPMux: true,
TCPMuxKeepaliveInterval: 60,
User: "your_name",
LoginFailExit: true,
Protocol: "tcp",
QUICKeepalivePeriod: 10,
QUICMaxIdleTimeout: 30,
QUICMaxIncomingStreams: 100000,
TLSEnable: true,
TLSCertFile: "client.crt",
TLSKeyFile: "client.key",
TLSTrustedCaFile: "ca.crt",
TLSServerName: "example.com",
DisableCustomTLSFirstByte: true,
DNSServer: "8.8.8.9",
Start: []string{"ssh", "dns"},
HeartbeatInterval: 39,
HeartbeatTimeout: 99,
Metas: map[string]string{
"var1": "123",
"var2": "234",

View File

@@ -527,11 +527,8 @@ func (cfg *TCPProxyConf) ValidateForClient() (err error) {
return
}
func (cfg *TCPProxyConf) ValidateForServer(serverCfg ServerCommonConf) error {
if err := cfg.BaseProxyConf.validateForServer(); err != nil {
return err
}
return nil
func (cfg *TCPProxyConf) ValidateForServer(_ ServerCommonConf) error {
return cfg.BaseProxyConf.validateForServer()
}
// TCPMux
@@ -644,11 +641,8 @@ func (cfg *UDPProxyConf) ValidateForClient() (err error) {
return
}
func (cfg *UDPProxyConf) ValidateForServer(serverCfg ServerCommonConf) error {
if err := cfg.BaseProxyConf.validateForServer(); err != nil {
return err
}
return nil
func (cfg *UDPProxyConf) ValidateForServer(_ ServerCommonConf) error {
return cfg.BaseProxyConf.validateForServer()
}
// HTTP
@@ -821,11 +815,8 @@ func (cfg *SUDPProxyConf) ValidateForClient() (err error) {
return nil
}
func (cfg *SUDPProxyConf) ValidateForServer(serverCfg ServerCommonConf) error {
if err := cfg.BaseProxyConf.validateForServer(); err != nil {
return err
}
return nil
func (cfg *SUDPProxyConf) ValidateForServer(_ ServerCommonConf) error {
return cfg.BaseProxyConf.validateForServer()
}
// STCP
@@ -875,11 +866,8 @@ func (cfg *STCPProxyConf) ValidateForClient() (err error) {
return
}
func (cfg *STCPProxyConf) ValidateForServer(serverCfg ServerCommonConf) error {
if err := cfg.BaseProxyConf.validateForServer(); err != nil {
return err
}
return nil
func (cfg *STCPProxyConf) ValidateForServer(_ ServerCommonConf) error {
return cfg.BaseProxyConf.validateForServer()
}
// XTCP
@@ -928,9 +916,6 @@ func (cfg *XTCPProxyConf) ValidateForClient() (err error) {
return
}
func (cfg *XTCPProxyConf) ValidateForServer(serverCfg ServerCommonConf) error {
if err := cfg.BaseProxyConf.validateForServer(); err != nil {
return err
}
return nil
func (cfg *XTCPProxyConf) ValidateForServer(_ ServerCommonConf) error {
return cfg.BaseProxyConf.validateForServer()
}

View File

@@ -35,7 +35,7 @@ var (
testProxyPrefix = "test."
)
func Test_Proxy_Interface(t *testing.T) {
func Test_Proxy_Interface(_ *testing.T) {
for name := range proxyConfTypeMap {
NewConfByType(name)
}

View File

@@ -25,7 +25,7 @@ import (
const testVisitorPrefix = "test."
func Test_Visitor_Interface(t *testing.T) {
func Test_Visitor_Interface(_ *testing.T) {
for name := range visitorConfTypeMap {
DefaultVisitorConf(name)
}

View File

@@ -129,7 +129,7 @@ func (m *serverMetrics) CloseProxy(name string, proxyType string) {
}
}
func (m *serverMetrics) OpenConnection(name string, proxyType string) {
func (m *serverMetrics) OpenConnection(name string, _ string) {
m.info.CurConns.Inc(1)
m.mu.Lock()
@@ -141,7 +141,7 @@ func (m *serverMetrics) OpenConnection(name string, proxyType string) {
}
}
func (m *serverMetrics) CloseConnection(name string, proxyType string) {
func (m *serverMetrics) CloseConnection(name string, _ string) {
m.info.CurConns.Dec(1)
m.mu.Lock()
@@ -153,7 +153,7 @@ func (m *serverMetrics) CloseConnection(name string, proxyType string) {
}
}
func (m *serverMetrics) AddTrafficIn(name string, proxyType string, trafficBytes int64) {
func (m *serverMetrics) AddTrafficIn(name string, _ string, trafficBytes int64) {
m.info.TotalTrafficIn.Inc(trafficBytes)
m.mu.Lock()
@@ -166,7 +166,7 @@ func (m *serverMetrics) AddTrafficIn(name string, proxyType string, trafficBytes
}
}
func (m *serverMetrics) AddTrafficOut(name string, proxyType string, trafficBytes int64) {
func (m *serverMetrics) AddTrafficOut(name string, _ string, trafficBytes int64) {
m.info.TotalTrafficOut.Inc(trafficBytes)
m.mu.Lock()

View File

@@ -29,11 +29,11 @@ func (m *serverMetrics) CloseClient() {
m.clientCount.Dec()
}
func (m *serverMetrics) NewProxy(name string, proxyType string) {
func (m *serverMetrics) NewProxy(_ string, proxyType string) {
m.proxyCount.WithLabelValues(proxyType).Inc()
}
func (m *serverMetrics) CloseProxy(name string, proxyType string) {
func (m *serverMetrics) CloseProxy(_ string, proxyType string) {
m.proxyCount.WithLabelValues(proxyType).Dec()
}

View File

@@ -121,7 +121,7 @@ func (c *Controller) CleanWorker(ctx context.Context) {
}
}
func (c *Controller) ListenClient(name string, sk string, allowUsers []string) chan string {
func (c *Controller) ListenClient(name string, sk string, allowUsers []string) (chan string, error) {
cfg := &ClientCfg{
name: name,
sk: sk,
@@ -130,8 +130,11 @@ func (c *Controller) ListenClient(name string, sk string, allowUsers []string) c
}
c.mu.Lock()
defer c.mu.Unlock()
if _, ok := c.clientCfgs[name]; ok {
return nil, fmt.Errorf("proxy [%s] is repeated", name)
}
c.clientCfgs[name] = cfg
return cfg.sidCh
return cfg.sidCh, nil
}
func (c *Controller) CloseClient(name string) {
@@ -191,7 +194,7 @@ func (c *Controller) HandleVisitor(m *msg.NatHoleVisitor, transporter transport.
_ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, err.Error()))
return
}
log.Trace("handle visitor message, sid [%s]", sid)
log.Trace("handle visitor message, sid [%s], server name: %s", sid, m.ProxyName)
defer func() {
c.mu.Lock()
@@ -253,7 +256,7 @@ func (c *Controller) HandleClient(m *msg.NatHoleClient, transporter transport.Me
if !ok {
return
}
log.Trace("handle client message, sid [%s]", session.sid)
log.Trace("handle client message, sid [%s], server name: %s", session.sid, m.ProxyName)
session.clientMsg = m
session.clientTransporter = transporter
select {

View File

@@ -45,10 +45,7 @@ func DecodeMessageInto(data, key []byte, m msg.Message) error {
return err
}
if err := msg.ReadMsgInto(bytes.NewReader(buf), m); err != nil {
return err
}
return nil
return msg.ReadMsgInto(bytes.NewReader(buf), m)
}
type ChangedAddress struct {

View File

@@ -97,7 +97,7 @@ func NewHTTP2HTTPSPlugin(params map[string]string) (Plugin, error) {
return p, nil
}
func (p *HTTP2HTTPSPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
func (p *HTTP2HTTPSPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ []byte) {
wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
_ = p.l.PutConn(wrapConn)
}
@@ -107,8 +107,5 @@ func (p *HTTP2HTTPSPlugin) Name() string {
}
func (p *HTTP2HTTPSPlugin) Close() error {
if err := p.s.Close(); err != nil {
return err
}
return nil
return p.s.Close()
}

View File

@@ -68,7 +68,7 @@ func (hp *HTTPProxy) Name() string {
return PluginHTTPProxy
}
func (hp *HTTPProxy) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
func (hp *HTTPProxy) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ []byte) {
wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
sc, rd := libnet.NewSharedConn(wrapConn)

View File

@@ -122,7 +122,7 @@ func (p *HTTPS2HTTPPlugin) genTLSConfig() (*tls.Config, error) {
return config, nil
}
func (p *HTTPS2HTTPPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
func (p *HTTPS2HTTPPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ []byte) {
wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
_ = p.l.PutConn(wrapConn)
}
@@ -132,8 +132,5 @@ func (p *HTTPS2HTTPPlugin) Name() string {
}
func (p *HTTPS2HTTPPlugin) Close() error {
if err := p.s.Close(); err != nil {
return err
}
return nil
return p.s.Close()
}

View File

@@ -127,7 +127,7 @@ func (p *HTTPS2HTTPSPlugin) genTLSConfig() (*tls.Config, error) {
return config, nil
}
func (p *HTTPS2HTTPSPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
func (p *HTTPS2HTTPSPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ []byte) {
wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
_ = p.l.PutConn(wrapConn)
}
@@ -137,8 +137,5 @@ func (p *HTTPS2HTTPSPlugin) Name() string {
}
func (p *HTTPS2HTTPSPlugin) Close() error {
if err := p.s.Close(); err != nil {
return err
}
return nil
return p.s.Close()
}

View File

@@ -50,7 +50,7 @@ func NewSocks5Plugin(params map[string]string) (p Plugin, err error) {
return
}
func (sp *Socks5Plugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
func (sp *Socks5Plugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ []byte) {
defer conn.Close()
wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
_ = sp.Server.ServeConn(wrapConn)

View File

@@ -76,7 +76,7 @@ func NewStaticFilePlugin(params map[string]string) (Plugin, error) {
return sp, nil
}
func (sp *StaticFilePlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
func (sp *StaticFilePlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ []byte) {
wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
_ = sp.l.PutConn(wrapConn)
}

View File

@@ -51,7 +51,7 @@ func NewUnixDomainSocketPlugin(params map[string]string) (p Plugin, err error) {
return
}
func (uds *UnixDomainSocketPlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
func (uds *UnixDomainSocketPlugin) Handle(conn io.ReadWriteCloser, _ net.Conn, extraBufToLocal []byte) {
localConn, err := net.DialUnix("unix", nil, uds.UnixAddr)
if err != nil {
return

View File

@@ -120,8 +120,5 @@ func (p *httpPlugin) do(ctx context.Context, r *Request, res *Response) error {
if err != nil {
return err
}
if err = json.Unmarshal(buf, res); err != nil {
return err
}
return nil
return json.Unmarshal(buf, res)
}

View File

@@ -103,9 +103,7 @@ func NewServerTLSConfig(certPath, keyPath, caPath string) (*tls.Config, error) {
func NewClientTLSConfig(certPath, keyPath, caPath, serverName string) (*tls.Config, error) {
base := &tls.Config{}
if certPath == "" || keyPath == "" {
// client will not generate tls conf by itself
} else {
if certPath != "" && keyPath != "" {
cert, err := newCustomTLSKeyPair(certPath, keyPath)
if err != nil {
return nil, err

View File

@@ -21,9 +21,15 @@ func DialHookCustomTLSHeadByte(enableTLS bool, disableCustomTLSHeadByte bool) li
}
}
func DialHookWebsocket() libdial.AfterHookFunc {
func DialHookWebsocket(protocol string, host string) libdial.AfterHookFunc {
return func(ctx context.Context, c net.Conn, addr string) (context.Context, net.Conn, error) {
addr = "ws://" + addr + FrpWebsocketPath
if protocol != "wss" {
protocol = "ws"
}
if host == "" {
host = addr
}
addr = protocol + "://" + host + FrpWebsocketPath
uri, err := url.Parse(addr)
if err != nil {
return nil, nil, err

View File

@@ -140,15 +140,15 @@ func (c *FakeUDPConn) RemoteAddr() net.Addr {
return c.remoteAddr
}
func (c *FakeUDPConn) SetDeadline(t time.Time) error {
func (c *FakeUDPConn) SetDeadline(_ time.Time) error {
return nil
}
func (c *FakeUDPConn) SetReadDeadline(t time.Time) error {
func (c *FakeUDPConn) SetReadDeadline(_ time.Time) error {
return nil
}
func (c *FakeUDPConn) SetWriteDeadline(t time.Time) error {
func (c *FakeUDPConn) SetWriteDeadline(_ time.Time) error {
return nil
}
@@ -263,4 +263,4 @@ func (l *UDPListener) Addr() net.Addr {
type ConnectedUDPConn struct{ *net.UDPConn }
// WriteTo redirects all writes to the Write syscall, which is 4 times faster.
func (c *ConnectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) { return c.Write(b) }
func (c *ConnectedUDPConn) WriteTo(b []byte, _ net.Addr) (int, error) { return c.Write(b) }

View File

@@ -66,7 +66,7 @@ func (muxer *HTTPConnectTCPMuxer) readHTTPConnectRequest(rd io.Reader) (host, ht
return
}
func (muxer *HTTPConnectTCPMuxer) sendConnectResponse(c net.Conn, reqInfo map[string]string) error {
func (muxer *HTTPConnectTCPMuxer) sendConnectResponse(c net.Conn, _ map[string]string) error {
if muxer.passthrough {
return nil
}

View File

@@ -19,7 +19,7 @@ import (
"strings"
)
var version = "0.49.0"
var version = "0.51.2"
func Full() string {
return version

View File

@@ -74,10 +74,10 @@ type readOnlyConn struct {
}
func (conn readOnlyConn) Read(p []byte) (int, error) { return conn.reader.Read(p) }
func (conn readOnlyConn) Write(p []byte) (int, error) { return 0, io.ErrClosedPipe }
func (conn readOnlyConn) Write(_ []byte) (int, error) { return 0, io.ErrClosedPipe }
func (conn readOnlyConn) Close() error { return nil }
func (conn readOnlyConn) LocalAddr() net.Addr { return nil }
func (conn readOnlyConn) RemoteAddr() net.Addr { return nil }
func (conn readOnlyConn) SetDeadline(t time.Time) error { return nil }
func (conn readOnlyConn) SetReadDeadline(t time.Time) error { return nil }
func (conn readOnlyConn) SetWriteDeadline(t time.Time) error { return nil }
func (conn readOnlyConn) SetDeadline(_ time.Time) error { return nil }
func (conn readOnlyConn) SetReadDeadline(_ time.Time) error { return nil }
func (conn readOnlyConn) SetWriteDeadline(_ time.Time) error { return nil }

View File

@@ -29,7 +29,6 @@ import (
"github.com/fatedier/frp/pkg/auth"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/consts"
pkgerr "github.com/fatedier/frp/pkg/errors"
"github.com/fatedier/frp/pkg/msg"
plugin "github.com/fatedier/frp/pkg/plugin/server"
@@ -55,13 +54,14 @@ func NewControlManager() *ControlManager {
}
}
func (cm *ControlManager) Add(runID string, ctl *Control) (oldCtl *Control) {
func (cm *ControlManager) Add(runID string, ctl *Control) (old *Control) {
cm.mu.Lock()
defer cm.mu.Unlock()
oldCtl, ok := cm.ctlsByRunID[runID]
var ok bool
old, ok = cm.ctlsByRunID[runID]
if ok {
oldCtl.Replaced(ctl)
old.Replaced(ctl)
}
cm.ctlsByRunID[runID] = ctl
return
@@ -141,14 +141,13 @@ type Control struct {
// replace old controller instantly.
runID string
// control status
status string
readerShutdown *shutdown.Shutdown
writerShutdown *shutdown.Shutdown
managerShutdown *shutdown.Shutdown
allShutdown *shutdown.Shutdown
started bool
mu sync.RWMutex
// Server configuration information
@@ -187,7 +186,6 @@ func NewControl(
portsUsedNum: 0,
lastPing: time.Now(),
runID: loginMsg.RunID,
status: consts.Working,
readerShutdown: shutdown.New(),
writerShutdown: shutdown.New(),
managerShutdown: shutdown.New(),
@@ -208,11 +206,19 @@ func (ctl *Control) Start() {
Error: "",
}
_ = msg.WriteMsg(ctl.conn, loginRespMsg)
ctl.mu.Lock()
ctl.started = true
ctl.mu.Unlock()
go ctl.writer()
for i := 0; i < ctl.poolCount; i++ {
ctl.sendCh <- &msg.ReqWorkConn{}
}
go func() {
for i := 0; i < ctl.poolCount; i++ {
// ignore error here, that means that this control is closed
_ = errors.PanicToError(func() {
ctl.sendCh <- &msg.ReqWorkConn{}
})
}
}()
go ctl.manager()
go ctl.reader()
@@ -418,6 +424,14 @@ func (ctl *Control) stoper() {
// block until Control closed
func (ctl *Control) WaitClosed() {
ctl.mu.RLock()
started := ctl.started
ctl.mu.RUnlock()
if !started {
ctl.allShutdown.Done()
return
}
ctl.allShutdown.WaitDone()
}
@@ -434,10 +448,9 @@ func (ctl *Control) manager() {
defer ctl.managerShutdown.Done()
var heartbeatCh <-chan time.Time
if ctl.serverCfg.TCPMux || ctl.serverCfg.HeartbeatTimeout <= 0 {
// Don't need application heartbeat here.
// yamux will do same thing.
} else {
// Don't need application heartbeat if TCPMux is enabled,
// yamux will do same thing.
if !ctl.serverCfg.TCPMux && ctl.serverCfg.HeartbeatTimeout > 0 {
heartbeat := time.NewTicker(time.Second)
defer heartbeat.Stop()
heartbeatCh = heartbeat.C
@@ -577,6 +590,11 @@ func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (remoteAddr string, err
}()
}
if ctl.pxyManager.Exist(pxyMsg.ProxyName) {
err = fmt.Errorf("proxy [%s] already exists", pxyMsg.ProxyName)
return
}
remoteAddr, err = pxy.Run()
if err != nil {
return

View File

@@ -55,11 +55,11 @@ type serverInfoResp struct {
}
// /healthz
func (svr *Service) Healthz(w http.ResponseWriter, r *http.Request) {
func (svr *Service) Healthz(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(200)
}
// api/serverinfo
// /api/serverinfo
func (svr *Service) APIServerInfo(w http.ResponseWriter, r *http.Request) {
res := GeneralResponse{Code: 200}
defer func() {
@@ -176,7 +176,7 @@ type GetProxyInfoResp struct {
Proxies []*ProxyStatsInfo `json:"proxies"`
}
// api/proxy/:type
// /api/proxy/:type
func (svr *Service) APIProxyByType(w http.ResponseWriter, r *http.Request) {
res := GeneralResponse{Code: 200}
params := mux.Vars(r)
@@ -244,7 +244,7 @@ type GetProxyStatsResp struct {
Status string `json:"status"`
}
// api/proxy/:type/:name
// /api/proxy/:type/:name
func (svr *Service) APIProxyByTypeAndName(w http.ResponseWriter, r *http.Request) {
res := GeneralResponse{Code: 200}
params := mux.Vars(r)
@@ -307,7 +307,7 @@ func (svr *Service) getProxyStatsByTypeAndName(proxyType string, proxyName strin
return
}
// api/traffic/:name
// /api/traffic/:name
type GetProxyTrafficResp struct {
Name string `json:"name"`
TrafficIn []int64 `json:"traffic_in"`

View File

@@ -43,7 +43,7 @@ func (ctl *HTTPGroupController) Register(
return g.Register(proxyName, group, groupKey, routeConfig)
}
func (ctl *HTTPGroupController) UnRegister(proxyName, group string, routeConfig vhost.RouteConfig) {
func (ctl *HTTPGroupController) UnRegister(proxyName, group string, _ vhost.RouteConfig) {
indexKey := group
ctl.mu.Lock()
defer ctl.mu.Unlock()

View File

@@ -27,11 +27,11 @@ func Register(m ServerMetrics) {
type noopServerMetrics struct{}
func (noopServerMetrics) NewClient() {}
func (noopServerMetrics) CloseClient() {}
func (noopServerMetrics) NewProxy(name string, proxyType string) {}
func (noopServerMetrics) CloseProxy(name string, proxyType string) {}
func (noopServerMetrics) OpenConnection(name string, proxyType string) {}
func (noopServerMetrics) CloseConnection(name string, proxyType string) {}
func (noopServerMetrics) AddTrafficIn(name string, proxyType string, trafficBytes int64) {}
func (noopServerMetrics) AddTrafficOut(name string, proxyType string, trafficBytes int64) {}
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) {}

View File

@@ -17,10 +17,10 @@ package proxy
import (
"io"
"net"
"reflect"
"strings"
libio "github.com/fatedier/golib/io"
"golang.org/x/time/rate"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/util/limit"
@@ -30,6 +30,10 @@ import (
"github.com/fatedier/frp/server/metrics"
)
func init() {
RegisterProxyFactory(reflect.TypeOf(&config.HTTPProxyConf{}), NewHTTPProxy)
}
type HTTPProxy struct {
*BaseProxy
cfg *config.HTTPProxyConf
@@ -37,6 +41,17 @@ type HTTPProxy struct {
closeFuncs []func()
}
func NewHTTPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
unwrapped, ok := cfg.(*config.HTTPProxyConf)
if !ok {
return nil
}
return &HTTPProxy{
BaseProxy: baseProxy,
cfg: unwrapped,
}
}
func (pxy *HTTPProxy) Run() (remoteAddr string, err error) {
xl := pxy.xl
routeConfig := vhost.RouteConfig{
@@ -137,10 +152,6 @@ func (pxy *HTTPProxy) GetConf() config.ProxyConf {
return pxy.cfg
}
func (pxy *HTTPProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *HTTPProxy) GetRealConn(remoteAddr string) (workConn net.Conn, err error) {
xl := pxy.xl
rAddr, errRet := net.ResolveTCPAddr("tcp", remoteAddr)

View File

@@ -15,20 +15,34 @@
package proxy
import (
"reflect"
"strings"
"golang.org/x/time/rate"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/util/util"
"github.com/fatedier/frp/pkg/util/vhost"
)
func init() {
RegisterProxyFactory(reflect.TypeOf(&config.HTTPSProxyConf{}), NewHTTPSProxy)
}
type HTTPSProxy struct {
*BaseProxy
cfg *config.HTTPSProxyConf
}
func NewHTTPSProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
unwrapped, ok := cfg.(*config.HTTPSProxyConf)
if !ok {
return nil
}
return &HTTPSProxy{
BaseProxy: baseProxy,
cfg: unwrapped,
}
}
func (pxy *HTTPSProxy) Run() (remoteAddr string, err error) {
xl := pxy.xl
routeConfig := &vhost.RouteConfig{}
@@ -67,7 +81,7 @@ func (pxy *HTTPSProxy) Run() (remoteAddr string, err error) {
addrs = append(addrs, util.CanonicalAddr(routeConfig.Domain, pxy.serverCfg.VhostHTTPSPort))
}
pxy.startListenHandler(pxy, HandleUserTCPConnection)
pxy.startCommonTCPListenersHandler()
remoteAddr = strings.Join(addrs, ",")
return
}
@@ -76,10 +90,6 @@ func (pxy *HTTPSProxy) GetConf() config.ProxyConf {
return pxy.cfg
}
func (pxy *HTTPSProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *HTTPSProxy) Close() {
pxy.BaseProxy.Close()
}

View File

@@ -19,6 +19,7 @@ import (
"fmt"
"io"
"net"
"reflect"
"strconv"
"sync"
"time"
@@ -36,6 +37,12 @@ import (
"github.com/fatedier/frp/server/metrics"
)
var proxyFactoryRegistry = map[reflect.Type]func(*BaseProxy, config.ProxyConf) Proxy{}
func RegisterProxyFactory(proxyConfType reflect.Type, factory func(*BaseProxy, config.ProxyConf) Proxy) {
proxyFactoryRegistry[proxyConfType] = factory
}
type GetWorkConnFn func() (net.Conn, error)
type Proxy interface {
@@ -63,6 +70,7 @@ type BaseProxy struct {
limiter *rate.Limiter
userInfo plugin.UserInfo
loginMsg *msg.Login
pxyConf config.ProxyConf
mu sync.RWMutex
xl *xlog.Logger
@@ -93,6 +101,10 @@ func (pxy *BaseProxy) GetLoginMsg() *msg.Login {
return pxy.loginMsg
}
func (pxy *BaseProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *BaseProxy) Close() {
xl := xlog.FromContextSafe(pxy.ctx)
xl.Info("proxy closing")
@@ -155,10 +167,8 @@ func (pxy *BaseProxy) GetWorkConnFromPool(src, dst net.Addr) (workConn net.Conn,
return
}
// startListenHandler start a goroutine handler for each listener.
// p: p will just be passed to handler(Proxy, utilnet.Conn).
// handler: each proxy type can set different handler function to deal with connections accepted from listeners.
func (pxy *BaseProxy) startListenHandler(p Proxy, handler func(Proxy, net.Conn, config.ServerCommonConf)) {
// 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) {
@@ -187,12 +197,74 @@ func (pxy *BaseProxy) startListenHandler(p Proxy, handler func(Proxy, net.Conn,
return
}
xl.Info("get a user connection [%s]", c.RemoteAddr().String())
go handler(p, c, pxy.serverCfg)
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()
serverCfg := pxy.serverCfg
cfg := pxy.pxyConf.GetBaseConfig()
// server plugin hook
rc := pxy.GetResourceController()
content := &plugin.NewUserConnContent{
User: pxy.GetUserInfo(),
ProxyName: pxy.GetName(),
ProxyType: cfg.ProxyType,
RemoteAddr: userConn.RemoteAddr().String(),
}
_, err := rc.PluginManager.NewUserConn(content)
if err != nil {
xl.Warn("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.Trace("handler user tcp connection, use_encryption: %t, use_compression: %t", cfg.UseEncryption, cfg.UseCompression)
if cfg.UseEncryption {
local, err = libio.WithEncryption(local, []byte(serverCfg.Token))
if err != nil {
xl.Error("create encryption stream error: %v", err)
return
}
}
if cfg.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.Debug("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.ProxyType
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.Debug("join connections closed")
}
func NewProxy(ctx context.Context, userInfo plugin.UserInfo, rc *controller.ResourceController, poolCount int,
getWorkConnFn GetWorkConnFn, pxyConf config.ProxyConf, serverCfg config.ServerCommonConf, loginMsg *msg.Login,
) (pxy Proxy, err error) {
@@ -216,114 +288,18 @@ func NewProxy(ctx context.Context, userInfo plugin.UserInfo, rc *controller.Reso
ctx: xlog.NewContext(ctx, xl),
userInfo: userInfo,
loginMsg: loginMsg,
pxyConf: pxyConf,
}
switch cfg := pxyConf.(type) {
case *config.TCPProxyConf:
basePxy.usedPortsNum = 1
pxy = &TCPProxy{
BaseProxy: &basePxy,
cfg: cfg,
}
case *config.TCPMuxProxyConf:
pxy = &TCPMuxProxy{
BaseProxy: &basePxy,
cfg: cfg,
}
case *config.HTTPProxyConf:
pxy = &HTTPProxy{
BaseProxy: &basePxy,
cfg: cfg,
}
case *config.HTTPSProxyConf:
pxy = &HTTPSProxy{
BaseProxy: &basePxy,
cfg: cfg,
}
case *config.UDPProxyConf:
basePxy.usedPortsNum = 1
pxy = &UDPProxy{
BaseProxy: &basePxy,
cfg: cfg,
}
case *config.STCPProxyConf:
pxy = &STCPProxy{
BaseProxy: &basePxy,
cfg: cfg,
}
case *config.XTCPProxyConf:
pxy = &XTCPProxy{
BaseProxy: &basePxy,
cfg: cfg,
}
case *config.SUDPProxyConf:
pxy = &SUDPProxy{
BaseProxy: &basePxy,
cfg: cfg,
}
default:
factory := proxyFactoryRegistry[reflect.TypeOf(pxyConf)]
if factory == nil {
return pxy, fmt.Errorf("proxy type not support")
}
return
}
// HandleUserTCPConnection is used for incoming user TCP connections.
// It can be used for tcp, http, https type.
func HandleUserTCPConnection(pxy Proxy, userConn net.Conn, serverCfg config.ServerCommonConf) {
xl := xlog.FromContextSafe(pxy.Context())
defer userConn.Close()
// server plugin hook
rc := pxy.GetResourceController()
content := &plugin.NewUserConnContent{
User: pxy.GetUserInfo(),
ProxyName: pxy.GetName(),
ProxyType: pxy.GetConf().GetBaseConfig().ProxyType,
RemoteAddr: userConn.RemoteAddr().String(),
pxy = factory(&basePxy, pxyConf)
if pxy == nil {
return nil, fmt.Errorf("proxy not created")
}
_, err := rc.PluginManager.NewUserConn(content)
if err != nil {
xl.Warn("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
cfg := pxy.GetConf().GetBaseConfig()
xl.Trace("handler user tcp connection, use_encryption: %t, use_compression: %t", cfg.UseEncryption, cfg.UseCompression)
if cfg.UseEncryption {
local, err = libio.WithEncryption(local, []byte(serverCfg.Token))
if err != nil {
xl.Error("create encryption stream error: %v", err)
return
}
}
if cfg.UseCompression {
local = libio.WithCompression(local)
}
if pxy.GetLimiter() != nil {
local = libio.WrapReadWriteCloser(limit.NewReader(local, pxy.GetLimiter()), limit.NewWriter(local, pxy.GetLimiter()), func() error {
return local.Close()
})
}
xl.Debug("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 := pxy.GetConf().GetBaseConfig().ProxyType
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.Debug("join connections closed")
return pxy, nil
}
type Manager struct {
@@ -350,6 +326,13 @@ func (pm *Manager) Add(name string, pxy Proxy) error {
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()

View File

@@ -15,16 +15,31 @@
package proxy
import (
"golang.org/x/time/rate"
"reflect"
"github.com/fatedier/frp/pkg/config"
)
func init() {
RegisterProxyFactory(reflect.TypeOf(&config.STCPProxyConf{}), NewSTCPProxy)
}
type STCPProxy struct {
*BaseProxy
cfg *config.STCPProxyConf
}
func NewSTCPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
unwrapped, ok := cfg.(*config.STCPProxyConf)
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
@@ -40,7 +55,7 @@ func (pxy *STCPProxy) Run() (remoteAddr string, err error) {
pxy.listeners = append(pxy.listeners, listener)
xl.Info("stcp proxy custom listen success")
pxy.startListenHandler(pxy, HandleUserTCPConnection)
pxy.startCommonTCPListenersHandler()
return
}
@@ -48,10 +63,6 @@ func (pxy *STCPProxy) GetConf() config.ProxyConf {
return pxy.cfg
}
func (pxy *STCPProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *STCPProxy) Close() {
pxy.BaseProxy.Close()
pxy.rc.VisitorManager.CloseListener(pxy.GetName())

View File

@@ -15,16 +15,31 @@
package proxy
import (
"golang.org/x/time/rate"
"reflect"
"github.com/fatedier/frp/pkg/config"
)
func init() {
RegisterProxyFactory(reflect.TypeOf(&config.SUDPProxyConf{}), NewSUDPProxy)
}
type SUDPProxy struct {
*BaseProxy
cfg *config.SUDPProxyConf
}
func NewSUDPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
unwrapped, ok := cfg.(*config.SUDPProxyConf)
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
@@ -40,7 +55,7 @@ func (pxy *SUDPProxy) Run() (remoteAddr string, err error) {
pxy.listeners = append(pxy.listeners, listener)
xl.Info("sudp proxy custom listen success")
pxy.startListenHandler(pxy, HandleUserTCPConnection)
pxy.startCommonTCPListenersHandler()
return
}
@@ -48,10 +63,6 @@ func (pxy *SUDPProxy) GetConf() config.ProxyConf {
return pxy.cfg
}
func (pxy *SUDPProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *SUDPProxy) Close() {
pxy.BaseProxy.Close()
pxy.rc.VisitorManager.CloseListener(pxy.GetName())

View File

@@ -17,24 +17,39 @@ package proxy
import (
"fmt"
"net"
"reflect"
"strconv"
"golang.org/x/time/rate"
"github.com/fatedier/frp/pkg/config"
)
func init() {
RegisterProxyFactory(reflect.TypeOf(&config.TCPProxyConf{}), NewTCPProxy)
}
type TCPProxy struct {
*BaseProxy
cfg *config.TCPProxyConf
realPort int
realBindPort int
}
func NewTCPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
unwrapped, ok := cfg.(*config.TCPProxyConf)
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.Group != "" {
l, realPort, errRet := pxy.rc.TCPGroupCtl.Listen(pxy.name, pxy.cfg.Group, pxy.cfg.GroupKey, pxy.serverCfg.ProxyBindAddr, pxy.cfg.RemotePort)
l, realBindPort, errRet := pxy.rc.TCPGroupCtl.Listen(pxy.name, pxy.cfg.Group, pxy.cfg.GroupKey, pxy.serverCfg.ProxyBindAddr, pxy.cfg.RemotePort)
if errRet != nil {
err = errRet
return
@@ -44,20 +59,20 @@ func (pxy *TCPProxy) Run() (remoteAddr string, err error) {
l.Close()
}
}()
pxy.realPort = realPort
pxy.realBindPort = realBindPort
pxy.listeners = append(pxy.listeners, l)
xl.Info("tcp proxy listen port [%d] in group [%s]", pxy.cfg.RemotePort, pxy.cfg.Group)
} else {
pxy.realPort, err = pxy.rc.TCPPortManager.Acquire(pxy.name, pxy.cfg.RemotePort)
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.realPort)
pxy.rc.TCPPortManager.Release(pxy.realBindPort)
}
}()
listener, errRet := net.Listen("tcp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realPort)))
listener, errRet := net.Listen("tcp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realBindPort)))
if errRet != nil {
err = errRet
return
@@ -66,9 +81,9 @@ func (pxy *TCPProxy) Run() (remoteAddr string, err error) {
xl.Info("tcp proxy listen port [%d]", pxy.cfg.RemotePort)
}
pxy.cfg.RemotePort = pxy.realPort
remoteAddr = fmt.Sprintf(":%d", pxy.realPort)
pxy.startListenHandler(pxy, HandleUserTCPConnection)
pxy.cfg.RemotePort = pxy.realBindPort
remoteAddr = fmt.Sprintf(":%d", pxy.realBindPort)
pxy.startCommonTCPListenersHandler()
return
}
@@ -76,13 +91,9 @@ func (pxy *TCPProxy) GetConf() config.ProxyConf {
return pxy.cfg
}
func (pxy *TCPProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *TCPProxy) Close() {
pxy.BaseProxy.Close()
if pxy.cfg.Group == "" {
pxy.rc.TCPPortManager.Release(pxy.realPort)
pxy.rc.TCPPortManager.Release(pxy.realBindPort)
}
}

View File

@@ -17,21 +17,35 @@ package proxy
import (
"fmt"
"net"
"reflect"
"strings"
"golang.org/x/time/rate"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/consts"
"github.com/fatedier/frp/pkg/util/util"
"github.com/fatedier/frp/pkg/util/vhost"
)
func init() {
RegisterProxyFactory(reflect.TypeOf(&config.TCPMuxProxyConf{}), NewTCPMuxProxy)
}
type TCPMuxProxy struct {
*BaseProxy
cfg *config.TCPMuxProxyConf
}
func NewTCPMuxProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
unwrapped, ok := cfg.(*config.TCPMuxProxyConf)
if !ok {
return nil
}
return &TCPMuxProxy{
BaseProxy: baseProxy,
cfg: unwrapped,
}
}
func (pxy *TCPMuxProxy) httpConnectListen(
domain, routeByHTTPUser, httpUser, httpPwd string, addrs []string) ([]string, error,
) {
@@ -78,7 +92,7 @@ func (pxy *TCPMuxProxy) httpConnectRun() (remoteAddr string, err error) {
}
}
pxy.startListenHandler(pxy, HandleUserTCPConnection)
pxy.startCommonTCPListenersHandler()
remoteAddr = strings.Join(addrs, ",")
return remoteAddr, err
}
@@ -101,10 +115,6 @@ func (pxy *TCPMuxProxy) GetConf() config.ProxyConf {
return pxy.cfg
}
func (pxy *TCPMuxProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *TCPMuxProxy) Close() {
pxy.BaseProxy.Close()
}

View File

@@ -19,12 +19,12 @@ import (
"fmt"
"io"
"net"
"reflect"
"strconv"
"time"
"github.com/fatedier/golib/errors"
libio "github.com/fatedier/golib/io"
"golang.org/x/time/rate"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
@@ -34,11 +34,15 @@ import (
"github.com/fatedier/frp/server/metrics"
)
func init() {
RegisterProxyFactory(reflect.TypeOf(&config.UDPProxyConf{}), NewUDPProxy)
}
type UDPProxy struct {
*BaseProxy
cfg *config.UDPProxyConf
realPort int
realBindPort int
// udpConn is the listener of udp packages
udpConn *net.UDPConn
@@ -59,21 +63,33 @@ type UDPProxy struct {
isClosed bool
}
func NewUDPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
unwrapped, ok := cfg.(*config.UDPProxyConf)
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.realPort, err = pxy.rc.UDPPortManager.Acquire(pxy.name, pxy.cfg.RemotePort)
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.realPort)
pxy.rc.UDPPortManager.Release(pxy.realBindPort)
}
}()
remoteAddr = fmt.Sprintf(":%d", pxy.realPort)
pxy.cfg.RemotePort = pxy.realPort
addr, errRet := net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realPort)))
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
@@ -233,10 +249,6 @@ func (pxy *UDPProxy) GetConf() config.ProxyConf {
return pxy.cfg
}
func (pxy *UDPProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *UDPProxy) Close() {
pxy.mu.Lock()
defer pxy.mu.Unlock()
@@ -254,5 +266,5 @@ func (pxy *UDPProxy) Close() {
close(pxy.readCh)
close(pxy.sendCh)
}
pxy.rc.UDPPortManager.Release(pxy.realPort)
pxy.rc.UDPPortManager.Release(pxy.realBindPort)
}

View File

@@ -16,14 +16,18 @@ package proxy
import (
"fmt"
"reflect"
"github.com/fatedier/golib/errors"
"golang.org/x/time/rate"
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
)
func init() {
RegisterProxyFactory(reflect.TypeOf(&config.XTCPProxyConf{}), NewXTCPProxy)
}
type XTCPProxy struct {
*BaseProxy
cfg *config.XTCPProxyConf
@@ -31,6 +35,17 @@ type XTCPProxy struct {
closeCh chan struct{}
}
func NewXTCPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
unwrapped, ok := cfg.(*config.XTCPProxyConf)
if !ok {
return nil
}
return &XTCPProxy{
BaseProxy: baseProxy,
cfg: unwrapped,
}
}
func (pxy *XTCPProxy) Run() (remoteAddr string, err error) {
xl := pxy.xl
@@ -43,7 +58,10 @@ func (pxy *XTCPProxy) Run() (remoteAddr string, err error) {
if len(allowUsers) == 0 {
allowUsers = []string{pxy.GetUserInfo().User}
}
sidCh := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk, allowUsers)
sidCh, err := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk, allowUsers)
if err != nil {
return "", err
}
go func() {
for {
select {
@@ -72,10 +90,6 @@ func (pxy *XTCPProxy) GetConf() config.ProxyConf {
return pxy.cfg
}
func (pxy *XTCPProxy) GetLimiter() *rate.Limiter {
return pxy.limiter
}
func (pxy *XTCPProxy) Close() {
pxy.BaseProxy.Close()
pxy.rc.NatHoleController.CloseClient(pxy.GetName())

View File

@@ -70,7 +70,7 @@ type Service struct {
kcpListener net.Listener
// Accept connections using quic
quicListener quic.Listener
quicListener *quic.Listener
// Accept connections using websocket
websocketListener net.Listener
@@ -115,7 +115,6 @@ func NewService(cfg config.ServerCommonConf) (svr *Service, err error) {
return
}
ctx, cancel := context.WithCancel(context.Background())
svr = &Service{
ctlManager: NewControlManager(),
pxyManager: proxy.NewManager(),
@@ -129,8 +128,7 @@ func NewService(cfg config.ServerCommonConf) (svr *Service, err error) {
authVerifier: auth.NewAuthVerifier(cfg.ServerConfig),
tlsConfig: tlsConfig,
cfg: cfg,
ctx: ctx,
cancel: cancel,
ctx: context.Background(),
}
// Create tcpmux httpconnect multiplexer.
@@ -329,7 +327,11 @@ func NewService(cfg config.ServerCommonConf) (svr *Service, err error) {
return
}
func (svr *Service) Run() {
func (svr *Service) Run(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
svr.ctx = ctx
svr.cancel = cancel
if svr.kcpListener != nil {
go svr.HandleListener(svr.kcpListener)
}
@@ -343,27 +345,39 @@ func (svr *Service) Run() {
go svr.rc.NatHoleController.CleanWorker(svr.ctx)
}
svr.HandleListener(svr.listener)
<-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()
svr.kcpListener = nil
}
if svr.quicListener != nil {
svr.quicListener.Close()
svr.quicListener = nil
}
if svr.websocketListener != nil {
svr.websocketListener.Close()
svr.websocketListener = nil
}
if svr.tlsListener != nil {
svr.tlsListener.Close()
svr.tlsConfig = nil
}
if svr.listener != nil {
svr.listener.Close()
svr.listener = nil
}
svr.cancel()
svr.ctlManager.Close()
if svr.cancel != nil {
svr.cancel()
}
return nil
}
@@ -485,7 +499,7 @@ func (svr *Service) HandleListener(l net.Listener) {
}
}
func (svr *Service) HandleQUICListener(l quic.Listener) {
func (svr *Service) HandleQUICListener(l *quic.Listener) {
// Listen for incoming connections from client.
for {
c, err := l.Accept(context.Background())
@@ -538,7 +552,7 @@ func (svr *Service) RegisterControl(ctlConn net.Conn, loginMsg *msg.Login) (err
ctl := NewControl(ctx, svr.rc, svr.pxyManager, svr.pluginManager, svr.authVerifier, ctlConn, loginMsg, svr.cfg)
if oldCtl := svr.ctlManager.Add(loginMsg.RunID, ctl); oldCtl != nil {
oldCtl.allShutdown.WaitDone()
oldCtl.WaitClosed()
}
ctl.Start()

View File

@@ -298,6 +298,7 @@ var _ = ginkgo.Describe("[Feature: Basic]", func() {
case "xtcp":
localPortName = framework.TCPEchoServerPort
protocol = "tcp"
ginkgo.Skip("stun server is not stable")
}
correctSK := "abc"
@@ -331,24 +332,29 @@ var _ = ginkgo.Describe("[Feature: Basic]", func() {
proxyExtraConfig string
visitorExtraConfig string
expectError bool
user2 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",
@@ -358,6 +364,7 @@ var _ = ginkgo.Describe("[Feature: Basic]", func() {
use_encryption = true
use_compression = true
`,
skipXTCP: true,
},
{
proxyName: "with-error-sk",
@@ -371,7 +378,7 @@ var _ = ginkgo.Describe("[Feature: Basic]", func() {
visitorSK: correctSK,
proxyExtraConfig: "allow_users = another, user2",
visitorExtraConfig: "server_user = user1",
user2: true,
deployUser2Client: true,
},
{
proxyName: "not-allowed-user",
@@ -387,7 +394,7 @@ var _ = ginkgo.Describe("[Feature: Basic]", func() {
visitorSK: correctSK,
proxyExtraConfig: "allow_users = *",
visitorExtraConfig: "server_user = user1",
user2: true,
deployUser2Client: true,
},
}
@@ -399,7 +406,7 @@ var _ = ginkgo.Describe("[Feature: Basic]", func() {
config := getProxyVisitorConf(
test.proxyName, test.bindPortName, test.visitorSK, test.commonExtraConfig+"\n"+test.visitorExtraConfig,
) + "\n"
if test.user2 {
if test.deployUser2Client {
clientUser2VisitorConf += config
} else {
clientVisitorConf += config
@@ -409,9 +416,16 @@ var _ = ginkgo.Describe("[Feature: Basic]", func() {
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(3 * time.Second)
r.Timeout(timeout)
}).
Protocol(protocol).
PortName(test.bindPortName).

View File

@@ -101,4 +101,32 @@ var _ = ginkgo.Describe("[Feature: ClientManage]", func() {
}).Port(dashboardPort).
Ensure(framework.ExpectResponseCode(401))
})
ginkgo.It("stop", func() {
serverConf := consts.DefaultServerConfig
adminPort := f.AllocPort()
testPort := f.AllocPort()
clientConf := consts.DefaultClientConfig + 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 := clientsdk.New("127.0.0.1", adminPort)
err := client.Stop()
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()
})
})

View File

@@ -3,6 +3,7 @@ package basic
import (
"fmt"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
@@ -13,9 +14,13 @@ import (
)
type generalTestConfigures struct {
server string
client string
expectError bool
server string
client string
clientPrefix string
client2 string
client2Prefix string
testDelay time.Duration
expectError bool
}
func renderBindPortConfig(protocol string) string {
@@ -30,6 +35,9 @@ func renderBindPortConfig(protocol string) string {
func runClientServerTest(f *framework.Framework, configures *generalTestConfigures) {
serverConf := consts.DefaultServerConfig
clientConf := consts.DefaultClientConfig
if configures.clientPrefix != "" {
clientConf = configures.clientPrefix
}
serverConf += fmt.Sprintf(`
%s
@@ -54,7 +62,23 @@ func runClientServerTest(f *framework.Framework, configures *generalTestConfigur
framework.UDPEchoServerPort, udpPortName,
)
f.RunProcesses([]string{serverConf}, []string{clientConf})
clientConfs := []string{clientConf}
if configures.client2 != "" {
client2Conf := consts.DefaultClientConfig
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").
@@ -84,6 +108,33 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
}
})
// 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",
@@ -101,11 +152,13 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
supportProtocols := []string{"tcp", "kcp", "quic", "websocket"}
for _, protocol := range supportProtocols {
tmp := protocol
defineClientServerTest("TLS over "+strings.ToUpper(tmp), f, &generalTestConfigures{
// 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 = true
client: fmt.Sprintf(`tls_enable = false
protocol = %s
`, protocol),
})
@@ -113,10 +166,10 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
defineClientServerTest("enable tls_only, client with TLS", f, &generalTestConfigures{
server: "tls_only = true",
client: "tls_enable = true",
})
defineClientServerTest("enable tls_only, client without TLS", f, &generalTestConfigures{
server: "tls_only = true",
client: "tls_enable = false",
expectError: true,
})
})
@@ -155,7 +208,6 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
`, renderBindPortConfig(tmp), caCrtPath),
client: fmt.Sprintf(`
protocol = %s
tls_enable = true
tls_cert_file = %s
tls_key_file = %s
`, tmp, clientCrtPath, clientKeyPath),
@@ -172,7 +224,6 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
`, renderBindPortConfig(tmp), serverCrtPath, serverKeyPath, caCrtPath),
client: fmt.Sprintf(`
protocol = %s
tls_enable = true
tls_cert_file = %s
tls_key_file = %s
tls_trusted_ca_file = %s
@@ -211,7 +262,6 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
tls_trusted_ca_file = %s
`, serverCrtPath, serverKeyPath, caCrtPath),
client: fmt.Sprintf(`
tls_enable = true
tls_server_name = example.com
tls_cert_file = %s
tls_key_file = %s
@@ -228,7 +278,6 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
tls_trusted_ca_file = %s
`, serverCrtPath, serverKeyPath, caCrtPath),
client: fmt.Sprintf(`
tls_enable = true
tls_server_name = invalid.com
tls_cert_file = %s
tls_key_file = %s
@@ -239,7 +288,7 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
})
})
ginkgo.Describe("TLS with disable_custom_tls_first_byte", func() {
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
@@ -248,9 +297,8 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
%s
`, renderBindPortConfig(protocol)),
client: fmt.Sprintf(`
tls_enable = true
protocol = %s
disable_custom_tls_first_byte = true
disable_custom_tls_first_byte = false
`, protocol),
})
}
@@ -266,9 +314,7 @@ var _ = ginkgo.Describe("[Feature: Client-Server]", func() {
%s
`, renderBindPortConfig(protocol)),
client: fmt.Sprintf(`
tls_enable = true
protocol = %s
disable_custom_tls_first_byte = true
`, protocol),
})
}

View File

@@ -37,7 +37,7 @@ var _ = ginkgo.Describe("[Feature: Server Manager]", func() {
[tcp-port-not-allowed]
type = tcp
local_port = {{ .%s }}
remote_port = 20001
remote_port = 25001
`, framework.TCPEchoServerPort)
clientConf += fmt.Sprintf(`
[tcp-port-unavailable]
@@ -55,7 +55,7 @@ var _ = ginkgo.Describe("[Feature: Server Manager]", func() {
[udp-port-not-allowed]
type = udp
local_port = {{ .%s }}
remote_port = 20003
remote_port = 25003
`, framework.UDPEchoServerPort)
f.RunProcesses([]string{serverConf}, []string{clientConf})
@@ -65,7 +65,7 @@ var _ = ginkgo.Describe("[Feature: Server Manager]", func() {
framework.NewRequestExpect(f).PortName(tcpPortName).Ensure()
// Not Allowed
framework.NewRequestExpect(f).Port(25003).ExpectError(true).Ensure()
framework.NewRequestExpect(f).Port(25001).ExpectError(true).Ensure()
// Unavailable, already bind by frps
framework.NewRequestExpect(f).PortName(consts.PortServerName).ExpectError(true).Ensure()

View File

@@ -56,10 +56,7 @@ func (m *MockServers) Run() error {
if err := m.udsEchoServer.Run(); err != nil {
return err
}
if err := m.httpSimpleServer.Run(); err != nil {
return err
}
return nil
return m.httpSimpleServer.Run()
}
func (m *MockServers) Close() {

View File

@@ -62,6 +62,15 @@ func (c *Client) Reload() error {
return err
}
func (c *Client) Stop() error {
req, err := http.NewRequest("POST", "http://"+c.address+"/api/stop", nil)
if err != nil {
return err
}
_, err = c.do(req)
return err
}
func (c *Client) GetConfig() (string, error) {
req, err := http.NewRequest("GET", "http://"+c.address+"/api/config", nil)
if err != nil {